Merge "Fixing an ommitted conditional on a StrongBox test"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 7bb2bdf..e42e0d9 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -48,6 +48,8 @@
 $(call add-clean-step, rm -rf $(OUT_DIR)/host/common/obj/JAVA_LIBRARIES/cts-tradefed_intermediates/com/android/compatibility/SuiteInfo.java)
 $(call add-clean-step, rm -rf $(HOST_OUT)/cts/android-cts/testcases/CtsUiHostTestCases*)
 $(call add-clean-step, rm -rf $(HOST_OUT)/cts_instant/android-cts_instant/testcases/CtsJobSchedulerTestCases*)
+$(call add-clean-step, rm -rf $(HOST_OUT)/cts_instant/android-cts_instant/testcases/CtsUiHostTestCases*)
+$(call add-clean-step, rm -rf $(HOST_OUT)/cts_instant/android-cts_instant/testcases/CtsDpiTestCases2*)
 
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk
index 245fc54..98b95f4 100644
--- a/apps/CtsVerifier/Android.mk
+++ b/apps/CtsVerifier/Android.mk
@@ -53,7 +53,6 @@
 LOCAL_JAVA_LIBRARIES += android.test.runner.stubs
 LOCAL_JAVA_LIBRARIES += android.test.base.stubs
 LOCAL_JAVA_LIBRARIES += android.test.mock.stubs
-LOCAL_JAVA_LIBRARIES += bouncycastle
 LOCAL_JAVA_LIBRARIES += voip-common
 
 LOCAL_PACKAGE_NAME := CtsVerifier
@@ -89,7 +88,7 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := androidx.legacy_legacy-support-v4 \
                                compatibility-common-util-devicesidelib \
-                               compatibility-device-util \
+                               compatibility-device-util
 
 include $(BUILD_STATIC_JAVA_LIBRARY)
 
diff --git a/apps/CtsVerifier/res/layout/camera_fov_calibration_photo_capture.xml b/apps/CtsVerifier/res/layout/camera_fov_calibration_photo_capture.xml
index 7f8efa0..c142b15 100644
--- a/apps/CtsVerifier/res/layout/camera_fov_calibration_photo_capture.xml
+++ b/apps/CtsVerifier/res/layout/camera_fov_calibration_photo_capture.xml
@@ -49,7 +49,6 @@
             android:layout_alignParentBottom="true"
             android:layout_alignParentLeft="true"
             android:padding="10sp"
-            android:popupBackground="#ffffff"
             android:textSize="18sp" />
     </RelativeLayout>
 
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 9ec5dd3..2ae318e 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -3329,7 +3329,10 @@
     <string name="disallow_config_mobile_networks">Disallow config mobile networks</string>
     <string name="disallow_config_mobile_networks_action">Configuring mobile networks</string>
     <string name="disallow_config_tethering">Disallow config tethering</string>
-    <string name="disallow_config_tethering_action">Configuring tethering and portable hotspots</string>
+    <string name="disallow_config_tethering_action">
+        Configuring tethering and portable hotspots.\n
+        NOTE: If the device does not support tethering please skip this test and mark it as passing.\n
+    </string>
     <string name="disallow_config_wifi">Disallow config Wi-Fi</string>
     <string name="disallow_config_wifi_action">Modifying Wi-Fi configuration</string>
     <string name="disallow_debugging_features">Disallow debugging features</string>
@@ -3347,7 +3350,28 @@
     <string name="disallow_outgoing_beam">Disallow outgoing beam</string>
     <string name="disallow_outgoing_beam_action">Switching on android beam</string>
     <string name="disallow_remove_user">Disallow remove user</string>
-    <string name="disallow_remove_user_action">Removing other users (please create a user and attempt to remove it to verify). This test should also be considered as passed if \'remove user\' option cannot be found in Settings</string>
+    <string name="device_owner_disallow_remove_user_info">
+        Please press \'Create uninitialized user\' to create a user that is not set up. Then press the
+        \'Set restriction\' button to set the user restriction. Then press \'Go\' to open \'Settings\',
+        and manually find and open \'Multiple users\' setting. \n\n
+
+        Mark this test as passed if:\n\n
+        - The uninitialized user cannot be removed.\n
+        - \'Remove user\' option is disabled with an info icon on it. Clicking on it triggers a support dialog.\n\n
+
+        Use the Back button to return to this page.
+    </string>
+    <string name="managed_user_disallow_remove_user_info">
+        Please press the \'Set restriction\' button to set the user restriction.
+        Then press \'Go\' to open \'Settings\', and manually find and open \'Multiple users\' setting. \n\n
+
+        Mark this test as passed if one of the following conditions is met:\n\n
+        - \'Remove user\' option is disabled with an info icon on it. Clicking on it triggers a support dialog.\n
+        - \'Remove user\' option cannot be found.\n \n
+
+        Use the Back button to return to this page.
+    </string>
+    <string name="device_owner_disallow_remove_user_create_user">Create uninitialized user</string>
     <string name="disallow_remove_managed_profile">Disallow remove managed profile</string>
     <string name="disallow_remove_managed_profile_action">Removing the work profile. It shouldn\'t be possible neither from the Accounts screen nor the Device Administrators screen (after selecting the Device Administrator that corresponds to the badged version of \"CTS Verifier\")</string>
     <string name="disallow_share_location">Disallow share location</string>
@@ -4461,14 +4485,14 @@
     <!-- USB Audio Peripheral Play Test -->
     <string name="usbaudio_play_test"> USB Audio Peripheral Play Test</string>
     <string name="usbaudio_play_info">
-        This test requires that you have connected a mandated USB Audio Interface peripheral and
+        This test requires that you have connected a USB Audio Interface peripheral and
         some way to monitor the output. Press the \"Play\" button and verify that a tone is produced.
        </string>
 
     <!-- USB Audio Peripheral Record Test -->
     <string name="usbaudio_record_test"> USB Audio Peripheral Record Test</string>
     <string name="usbaudio_record_info">
-        This test requires that you have connected a mandated USB Audio Interface peripheral.
+        This test requires that you have connected a USB Audio Interface peripheral.
         Connect the outputs to the inputs (with patch cables). Start playback by pressing the
         \"Record Loopback\" button and verify that the recorded signal is displayed in the wave
         display view. (It may be necessary to adjust the input controls on the peripheral).
@@ -4477,9 +4501,11 @@
     <!-- USB Audio Peripheral Buttons Test -->
     <string name="usbaudio_buttons_test"> USB Audio Peripheral Buttons Test</string>
     <string name="usbaudio_buttons_info">
-        This test requires that you have connected a mandated USB Audio headset. Press each
-        \"transport\" button and verify that it is recognized by the test.
-       </string>
+        This test requires that you have connected a USB Audio headset that supports the
+        Android USB audio headset buttons specification. Press each
+        \"transport\" button and verify that it is recognized by the test. When each of the
+        buttons has been recognized the \"pass\" button will be enabled.
+    </string>
 
     <!-- Telecom tests -->
     <string name="telecom_enable_phone_account_test"> Telecom Enable Phone Account Test</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/peripheralprofile/ProfileManager.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/peripheralprofile/ProfileManager.java
index 9cec7fa..a56cd3f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/peripheralprofile/ProfileManager.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/peripheralprofile/ProfileManager.java
@@ -46,7 +46,11 @@
 
     private static final String mBuiltInprofiles =
         "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>" +
-        "<ProfileList Version=\"1.0.0\">" +
+            "<ProfileList Version=\"1.0.0\">" +
+            "<PeripheralProfile ProfileName=\"AudioBox USB 96\" ProfileDescription=\"PreSonus AudioBox USB 96\" ProductName=\"USB-Audio - AudioBox USB 96\">" +
+                "<OutputDevInfo ChanCounts=\"2\" ChanPosMasks=\"12\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"44100,48000,88200,96000\"/>" +
+                "<InputDevInfo ChanCounts=\"2\" ChanPosMasks=\"12\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"44100,48000,88200,96000\"/>" +
+            "</PeripheralProfile>" +
             "<PeripheralProfile ProfileName=\"Audio Interface\" ProfileDescription=\"Presonus AudioVox 44VSL\" ProductName=\"USB-Audio - AudioBox 44 VSL\">" +
                 "<OutputDevInfo ChanCounts=\"2,4\" ChanPosMasks=\"12\" ChanIndexMasks=\"15\" Encodings=\"4\" SampleRates=\"44100,48000,88200,96000\" />" +
                 "<InputDevInfo ChanCounts=\"1,2,4\" ChanPosMasks=\"12,16\" ChanIndexMasks=\"15\" Encodings=\"4\" SampleRates=\"44100,48000,88200,96000\" />" +
@@ -59,6 +63,18 @@
                 "<OutputDevInfo ChanCounts=\"2\" ChanPosMasks=\"12\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"44100,48000\" />" +
                 "<InputDevInfo ChanCounts=\"1,2\" ChanPosMasks=\"12,16\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"44100,48000\" />" +
             "</PeripheralProfile>" +
+            "<PeripheralProfile ProfileName=\"Focusrite 2i4\" ProfileDescription=\"Focusrite Scarlett 2i4\" ProductName=\"USB-Audio - Scarlett 2i4 USB\">" +
+                "<OutputDevInfo ChanCounts=\"2,3,4\" ChanPosMasks=\"12\" ChanIndexMasks=\"3,7,15\" Encodings=\"4\" SampleRates=\"44100,48000,88200,96000\"/>" +
+                "<InputDevInfo ChanCounts=\"1,2\" ChanPosMasks=\"12,16\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"44100,48000,88200,96000\"/>" +
+            "</PeripheralProfile>" +
+            "<PeripheralProfile ProfileName=\"Behringer UMC204HD\" ProfileDescription=\"Behringer UMC204HD\" ProductName=\"USB-Audio - UMC204HD 192k\">" +
+                "<OutputDevInfo ChanCounts=\"2,4\" ChanPosMasks=\"12\" ChanIndexMasks=\"15\" Encodings=\"2,4\" SampleRates=\"44100,48000,88200,96000,176400,192000\"/>" +
+                "<InputDevInfo ChanCounts=\"2\" ChanPosMasks=\"12\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"44100,48000,88200,96000,176400,192000\"/>" +
+            "</PeripheralProfile>" +
+            "<PeripheralProfile ProfileName=\"Roland Rubix24\" ProfileDescription=\"Roland Rubix24\" ProductName=\"USB-Audio - Rubix24\">" +
+                "<OutputDevInfo ChanCounts=\"2,4\" ChanPosMasks=\"12\" ChanIndexMasks=\"15\" Encodings=\"4\" SampleRates=\"44100,48000,96000,192000\"/>" +
+                "<InputDevInfo ChanCounts=\"2\" ChanPosMasks=\"12\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"44100,48000,96000,192000\"/>" +
+            "</PeripheralProfile>" +
             "<PeripheralProfile ProfileName=\"Pixel USB-C Dongle + Wired Analog Headset\" ProfileDescription=\"Reference USB Dongle\" ProductName=\"USB-Audio - USB-C to 3.5mm-Headphone Adapte\">" +
                 "<OutputDevInfo ChanCounts=\"2\" ChanPosMasks=\"12\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"48000\" />" +
                 "<InputDevInfo ChanCounts=\"1,2\" ChanPosMasks=\"12,16\" ChanIndexMasks=\"3\" Encodings=\"4\" SampleRates=\"48000\" />" +
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
index 75d884f..0022518 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
@@ -77,6 +77,7 @@
     private static final String MANAGED_USER_TEST_ID = "MANAGED_USER_UI";
     private static final String REMOVE_DEVICE_OWNER_TEST_ID = "REMOVE_DEVICE_OWNER";
     private static final String DISALLOW_AMBIENT_DISPLAY_ID = "DISALLOW_AMBIENT_DISPLAY";
+    private static final String DISALLOW_REMOVE_USER_TEST_ID = "DISALLOW_REMOVE_USER";
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -400,6 +401,22 @@
                             new ButtonInfo(
                                     R.string.device_owner_settings_go,
                                     new Intent(Settings.ACTION_SETTINGS))}));
+
+            // DISALLOW_REMOVE_USER
+            adapter.add(createInteractiveTestItem(this, DISALLOW_REMOVE_USER_TEST_ID,
+                    R.string.disallow_remove_user,
+                    R.string.device_owner_disallow_remove_user_info,
+                    new ButtonInfo[]{
+                            new ButtonInfo(
+                                    R.string.device_owner_disallow_remove_user_create_user,
+                                    createCreateManagedUserWithoutSetupIntent()),
+                            new ButtonInfo(
+                                    R.string.device_owner_user_restriction_set,
+                                    CommandReceiverActivity.createSetUserRestrictionIntent(
+                                            UserManager.DISALLOW_REMOVE_USER, true)),
+                            new ButtonInfo(
+                                    R.string.device_owner_settings_go,
+                                    new Intent(Settings.ACTION_SETTINGS))}));
         }
 
         // Network logging UI
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ManagedUserPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ManagedUserPositiveTestActivity.java
index aa20b68..dd2a639 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ManagedUserPositiveTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ManagedUserPositiveTestActivity.java
@@ -24,6 +24,7 @@
 import android.content.pm.PackageManager;
 import android.database.DataSetObserver;
 import android.os.Bundle;
+import android.os.UserManager;
 import android.provider.Settings;
 
 import com.android.cts.verifier.ArrayTestListAdapter;
@@ -49,6 +50,7 @@
     private static final String DISABLE_STATUS_BAR_TEST_ID = "DISABLE_STATUS_BAR";
     private static final String DISABLE_KEYGUARD_TEST_ID = "DISABLE_KEYGUARD";
     private static final String POLICY_TRANSPARENCY_TEST_ID = "POLICY_TRANSPARENCY";
+    private static final String DISALLOW_REMOVE_USER_TEST_ID = "DISALLOW_REMOVE_USER";
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -148,6 +150,19 @@
                                         CommandReceiverActivity.COMMAND_SET_KEYGUARD_DISABLED,
                                         false))}));
 
+        // DISALLOW_REMOVE_USER
+        adapter.add(createInteractiveTestItem(this, DISALLOW_REMOVE_USER_TEST_ID,
+                R.string.disallow_remove_user,
+                R.string.managed_user_disallow_remove_user_info,
+                new ButtonInfo[]{
+                        new ButtonInfo(
+                                R.string.device_owner_user_restriction_set,
+                                CommandReceiverActivity.createSetUserRestrictionIntent(
+                                        UserManager.DISALLOW_REMOVE_USER, true)),
+                        new ButtonInfo(
+                                R.string.device_owner_settings_go,
+                                new Intent(Settings.ACTION_SETTINGS))}));
+
         // Policy Transparency
         final Intent policyTransparencyTestIntent = new Intent(this,
                 PolicyTransparencyTestListActivity.class);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
index 90f0dc3..f004ace 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
@@ -47,7 +47,6 @@
         UserManager.DISALLOW_NETWORK_RESET,
         UserManager.DISALLOW_OUTGOING_BEAM,
         UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
-        UserManager.DISALLOW_REMOVE_USER,
         UserManager.DISALLOW_SHARE_LOCATION,
         UserManager.DISALLOW_UNINSTALL_APPS,
         UserManager.DISALLOW_UNIFIED_PASSWORD,
@@ -77,7 +76,6 @@
             R.string.disallow_network_reset,
             R.string.disallow_outgoing_beam,
             R.string.disallow_remove_managed_profile,
-            R.string.disallow_remove_user,
             R.string.disallow_share_location,
             R.string.disallow_uninstall_apps,
             R.string.disallow_unified_challenge,
@@ -105,7 +103,6 @@
             R.string.disallow_network_reset_action,
             R.string.disallow_outgoing_beam_action,
             R.string.disallow_remove_managed_profile_action,
-            R.string.disallow_remove_user_action,
             R.string.disallow_share_location_action,
             R.string.disallow_uninstall_apps_action,
             R.string.disallow_unified_challenge_action,
@@ -133,7 +130,6 @@
             Settings.ACTION_SETTINGS,
             Settings.ACTION_NFC_SETTINGS,
             Settings.ACTION_SETTINGS,
-            Settings.ACTION_SETTINGS,
             Settings.ACTION_LOCATION_SOURCE_SETTINGS,
             Settings.ACTION_APPLICATION_SETTINGS,
             Settings.ACTION_SECURITY_SETTINGS,
@@ -175,7 +171,6 @@
                     UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
                     UserManager.DISALLOW_MODIFY_ACCOUNTS,
                     UserManager.DISALLOW_OUTGOING_BEAM,
-                    UserManager.DISALLOW_REMOVE_USER,
                     UserManager.DISALLOW_SHARE_LOCATION,
                     UserManager.DISALLOW_UNINSTALL_APPS,
                     UserManager.DISALLOW_CONFIG_DATE_TIME,
@@ -237,7 +232,6 @@
         final PackageManager pm = context.getPackageManager();
         switch (restriction) {
             case UserManager.DISALLOW_ADD_USER:
-            case UserManager.DISALLOW_REMOVE_USER:
                 return UserManager.supportsMultipleUsers();
             case UserManager.DISALLOW_ADJUST_VOLUME:
                 return pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java
index 74a0ba4..83b84e7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/FingerprintBoundKeysTest.java
@@ -69,6 +69,8 @@
     private static final int CONFIRM_CREDENTIALS_REQUEST_CODE = 1;
     private static final int FINGERPRINT_PERMISSION_REQUEST_CODE = 0;
 
+    protected boolean useStrongBox;
+
     private FingerprintManager mFingerprintManager;
     private KeyguardManager mKeyguardManager;
     private FingerprintAuthDialogFragment mFingerprintDialog;
@@ -88,6 +90,7 @@
     @Override
     public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] state) {
         if (requestCode == FINGERPRINT_PERMISSION_REQUEST_CODE && state[0] == PackageManager.PERMISSION_GRANTED) {
+            useStrongBox = false;
             mFingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
             mKeyguardManager = (KeyguardManager) getSystemService(KeyguardManager.class);
             Button startTestButton = (Button) findViewById(R.id.sec_start_test_button);
@@ -108,18 +111,22 @@
             startTestButton.setOnClickListener(new OnClickListener() {
                 @Override
                 public void onClick(View v) {
-                    createKey(false /* hasValidityDuration */);
-                    prepareEncrypt();
-                    if (tryEncrypt()) {
-                        showToast("Test failed. Key accessible without auth.");
-                    } else {
-                        showAuthenticationScreen();
-                    }
+                    startTest();
                 }
             });
         }
     }
 
+    protected void startTest() {
+        createKey(false /* hasValidityDuration */);
+        prepareEncrypt();
+        if (tryEncrypt()) {
+            showToast("Test failed. Key accessible without auth.");
+        } else {
+            showAuthenticationScreen();
+        }
+    }
+
     /**
      * Creates a symmetric key in the Android Key Store which requires auth
      */
@@ -141,6 +148,7 @@
                     .setUserAuthenticationValidityDurationSeconds(
                         hasValidityDuration ? AUTHENTICATION_DURATION_SECONDS : -1)
                     .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
+                    .setIsStrongBoxBacked(useStrongBox)
                     .build());
             keyGenerator.generateKey();
             if (DEBUG) {
@@ -176,7 +184,7 @@
         return mCipher;
     }
 
-    protected boolean doValidityDurationTest() {
+    protected boolean doValidityDurationTest(boolean useStrongBox) {
         mCipher = null;
         createKey(true /* hasValidityDuration */);
         if (prepareEncrypt()) {
@@ -251,6 +259,7 @@
         private FingerprintManager mFingerprintManager;
         private FingerprintManagerCallback mFingerprintManagerCallback;
         private boolean mSelfCancelled;
+        private boolean hasStrongBox;
 
         class FingerprintManagerCallback extends FingerprintManager.AuthenticationCallback {
             @Override
@@ -281,15 +290,22 @@
                 if (DEBUG) {
                     Log.i(TAG,"onAuthenticationSucceeded");
                 }
-                if (mActivity.tryEncrypt() && mActivity.doValidityDurationTest()) {
+                hasStrongBox = getContext().getPackageManager()
+                                    .hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE);
+                if (mActivity.tryEncrypt() && mActivity.doValidityDurationTest(false)) {
                     try {
                         Thread.sleep(3000);
                     } catch (Exception e) {
                         throw new RuntimeException("Failed to sleep", e);
                     }
-                    if (!mActivity.doValidityDurationTest()) {
-                        showToast("Test passed.");
-                        mActivity.getPassButton().setEnabled(true);
+                    if (!mActivity.doValidityDurationTest(false)) {
+                        showToast(String.format("Test passed. useStrongBox: %b",
+                                                mActivity.useStrongBox));
+                        if (mActivity.useStrongBox || !hasStrongBox) {
+                            mActivity.getPassButton().setEnabled(true);
+                        } else {
+                            showToast("Rerunning with StrongBox");
+                        }
                         FingerprintAuthDialogFragment.this.dismiss();
                     } else {
                         showToast("Test failed. Key accessible after validity time limit.");
@@ -304,6 +320,11 @@
         public void onDismiss(DialogInterface dialog) {
             mCancellationSignal.cancel();
             mSelfCancelled = true;
+            // Start the test again, but with StrongBox if supported
+            if (!mActivity.useStrongBox && hasStrongBox) {
+                mActivity.useStrongBox = true;
+                mActivity.startTest();
+            }
         }
 
         private void setActivity(FingerprintBoundKeysTest activity) {
diff --git a/common/device-side/nativetesthelper/jni/Android.bp b/common/device-side/nativetesthelper/jni/Android.bp
index 91eb0ac..871207e 100644
--- a/common/device-side/nativetesthelper/jni/Android.bp
+++ b/common/device-side/nativetesthelper/jni/Android.bp
@@ -23,6 +23,7 @@
 
     shared_libs: ["libnativehelper_compat_libc++"],
     whole_static_libs: ["libgtest_ndk_c++"],
+    export_include_dirs: ["include"],
     sdk_version: "current",
     stl: "c++_static",
     cflags: [
diff --git a/common/device-side/nativetesthelper/jni/gtest_wrapper.cpp b/common/device-side/nativetesthelper/jni/gtest_wrapper.cpp
index eda919c..cfc4475 100644
--- a/common/device-side/nativetesthelper/jni/gtest_wrapper.cpp
+++ b/common/device-side/nativetesthelper/jni/gtest_wrapper.cpp
@@ -20,8 +20,17 @@
 
 #include <jni.h>
 #include <nativehelper/ScopedLocalRef.h>
+#include <nativetesthelper_jni/utils.h>
 #include <gtest/gtest.h>
 
+static JavaVM* gVm = nullptr;
+JavaVM* GetJavaVM() {
+    return gVm;
+}
+static void RegisterJavaVm(JNIEnv* env) {
+    (void)env->GetJavaVM(&gVm);
+}
+
 namespace {
 
 struct {
@@ -152,6 +161,8 @@
 extern "C"
 JNIEXPORT void JNICALL
 Java_com_android_gtestrunner_GtestRunner_nInitialize(JNIEnv *env, jclass, jstring className, jobject suite) {
+    RegisterJavaVm(env);
+
     // Initialize gtest, removing the default result printer
     int argc = 1;
     const char* argv[] = { "gtest_wrapper" };
diff --git a/common/device-side/nativetesthelper/jni/include/nativetesthelper_jni/utils.h b/common/device-side/nativetesthelper/jni/include/nativetesthelper_jni/utils.h
new file mode 100644
index 0000000..604d4ba5
--- /dev/null
+++ b/common/device-side/nativetesthelper/jni/include/nativetesthelper_jni/utils.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <jni.h>
+
+// This is used by setting up @TargetLibrary in an APK test which opens up and executes the gtest
+// containing this library.
+
+/**
+ * The JVM associated with this test run or nullptr if not available.
+ */
+JavaVM* GetJavaVM();
+
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
index a76cace..a8e3b68 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
@@ -32,7 +32,7 @@
     android.test.runner.stubs \
     junit \
     android.test.base.stubs \
-    bouncycastle
+    bouncycastle-unbundled
 
 LOCAL_USE_AAPT2 := true
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
old mode 100644
new mode 100755
index 0146826..28dd552
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -408,34 +408,42 @@
         if (!mHasFeature) {
             return;
         }
+        // Backup stay awake setting because testGenerateLogs() will turn it off.
+        final String stayAwake = getDevice().getSetting("global", "stay_on_while_plugged_in");
+        try {
+            // Turn logging on.
+            executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
+            // Reboot to ensure ro.device_owner is set to true in logd and logging is on.
+            rebootAndWaitUntilReady();
 
-        // Turn logging on.
-        executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
-        // Reboot to ensure ro.device_owner is set to true in logd and logging is on.
-        rebootAndWaitUntilReady();
-
-        // Generate various types of events on device side and check that they are logged.
-        executeDeviceTestMethod(".SecurityLoggingTest", "testGenerateLogs");
-        getDevice().executeShellCommand("dpm force-security-logs");
-        executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyGeneratedLogs");
-
-        // Reboot the device, so the security event ids are reset.
-        rebootAndWaitUntilReady();
-
-        // Verify event ids are consistent across a consecutive batch.
-        for (int batchNumber = 0; batchNumber < 3; batchNumber++) {
-            generateDummySecurityLogs();
+            // Generate various types of events on device side and check that they are logged.
+            executeDeviceTestMethod(".SecurityLoggingTest", "testGenerateLogs");
             getDevice().executeShellCommand("dpm force-security-logs");
-            executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyLogIds",
-                    Collections.singletonMap(ARG_SECURITY_LOGGING_BATCH_NUMBER,
-                            Integer.toString(batchNumber)));
-        }
+            executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyGeneratedLogs");
 
-        // Immediately attempting to fetch events again should fail.
-        executeDeviceTestMethod(".SecurityLoggingTest",
-                "testSecurityLoggingRetrievalRateLimited");
-        // Turn logging off.
-        executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
+            // Reboot the device, so the security event ids are reset.
+            rebootAndWaitUntilReady();
+
+            // Verify event ids are consistent across a consecutive batch.
+            for (int batchNumber = 0; batchNumber < 3; batchNumber++) {
+                generateDummySecurityLogs();
+                getDevice().executeShellCommand("dpm force-security-logs");
+                executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyLogIds",
+                        Collections.singletonMap(ARG_SECURITY_LOGGING_BATCH_NUMBER,
+                                Integer.toString(batchNumber)));
+            }
+
+            // Immediately attempting to fetch events again should fail.
+            executeDeviceTestMethod(".SecurityLoggingTest",
+                    "testSecurityLoggingRetrievalRateLimited");
+            // Turn logging off.
+            executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
+        } finally {
+            // Restore stay awake setting.
+            if (stayAwake != null) {
+                getDevice().setSetting("global", "stay_on_while_plugged_in", stayAwake);
+            }
+        }
     }
 
     private void generateDummySecurityLogs() throws DeviceNotAvailableException {
diff --git a/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
index 65cb2a5..9234387 100644
--- a/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
@@ -490,7 +490,7 @@
     }
 
     private void assertApproximateTimeInState(int index, long duration) throws Exception {
-        assertValueRange("st", "", index, (long) (0.8 * duration), 2 * duration);
+        assertValueRange("st", "", index, (long) (0.7 * duration), 2 * duration);
     }
 
     /**
diff --git a/hostsidetests/jvmti/TEST_MAPPING b/hostsidetests/jvmti/TEST_MAPPING
new file mode 100644
index 0000000..cb75014
--- /dev/null
+++ b/hostsidetests/jvmti/TEST_MAPPING
@@ -0,0 +1,271 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsJvmtiAttachingHostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRedefineClassesHostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest902HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest903HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest904HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest905HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest906HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest907HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest908HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest910HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest911HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest912HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest913HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest914HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest915HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest917HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest918HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest919HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest920HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest922HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest923HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest924HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest926HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest927HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest928HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest930HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest931HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest932HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest940HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest942HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest944HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest945HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest947HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest951HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest982HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest983HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest984HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest985HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest986HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest988HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest989HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest990HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest991HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest992HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest993HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest994HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest995HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest996HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest997HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1900HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1901HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1902HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1903HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1904HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1906HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1907HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1908HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1909HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1910HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1911HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1912HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1913HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1914HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1915HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1916HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1917HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1920HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1921HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1922HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1923HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1924HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1925HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1926HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1927HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1928HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1930HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1931HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1932HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1933HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1934HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1936HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1937HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1939HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1941HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1942HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1943HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiRunTest1953HostTestCases"
+    },
+    {
+      "name": "CtsJvmtiTaggingHostTestCases"
+    },
+    {
+      "name": "CtsJvmtiTrackingHostTestCases"
+    }
+  ]
+}
diff --git a/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java b/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
index dbd6ecd..b00c1da 100644
--- a/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
+++ b/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
@@ -23,16 +23,12 @@
 import art.Main;
 
 /**
- * Check tagging-related functionality.
+ * Check tracking-related functionality.
  */
 public class JvmtiTrackingTest extends JvmtiTestBase {
 
     @Before
     public void setUp() throws Exception {
-        // Bind our native methods.
-        Main.bindAgentJNI("android/jvmti/cts/JvmtiTrackingTest",
-                getClass().getClassLoader());
-
         prefetchClassNames();
     }
 
diff --git a/hostsidetests/jvmti/base/jni/cts_agent.cpp b/hostsidetests/jvmti/base/jni/cts_agent.cpp
index 665a47e..3f3a836 100644
--- a/hostsidetests/jvmti/base/jni/cts_agent.cpp
+++ b/hostsidetests/jvmti/base/jni/cts_agent.cpp
@@ -25,12 +25,26 @@
 
 namespace art {
 
+extern void register_art_Main(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiRedefineClassesTest(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiTaggingTest(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv*, JNIEnv*);
+
 static void InformMainAttach(jvmtiEnv* jenv,
                              JNIEnv* env,
                              const char* class_name,
                              const char* method_name) {
+  // Register native methods from available classes
+  // The agent is used with each test class, but we don't know which class is currently available.
+  // For that reason, we try to register the native methods in each one. Each function returns
+  // without throwing an error if the specified class can't be found.
+  register_art_Main(jenv, env);
+  register_android_jvmti_cts_JvmtiRedefineClassesTest(jenv, env);
+  register_android_jvmti_cts_JvmtiTaggingTest(jenv, env);
+  register_android_jvmti_cts_JvmtiTrackingTest(jenv, env);
+
   // Use JNI to load the class.
-  ScopedLocalRef<jclass> klass(env, FindClass(jenv, env, class_name, nullptr));
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env, class_name, nullptr));
   CHECK(klass.get() != nullptr) << class_name;
 
   jmethodID method = env->GetStaticMethodID(klass.get(), method_name, "()V");
diff --git a/hostsidetests/jvmti/base/jni/redefine.cpp b/hostsidetests/jvmti/base/jni/redefine.cpp
index f96108c..1a044ca 100644
--- a/hostsidetests/jvmti/base/jni/redefine.cpp
+++ b/hostsidetests/jvmti/base/jni/redefine.cpp
@@ -23,6 +23,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "jni_binder.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
@@ -172,5 +173,40 @@
   env->ReleaseByteArrayElements(dex_bytes, redef_bytes, 0);
 }
 
+static JNINativeMethod gMethods[] = {
+  { "redefineClass", "(Ljava/lang/Class;[B)I",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_redefineClass },
+
+  { "retransformClass", "(Ljava/lang/Class;)I",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_retransformClass },
+
+  { "setTransformationEvent", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_setTransformationEvent },
+
+  { "clearTransformations", "()V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_clearTransformations },
+
+  { "setPopTransformations", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_setPopTransformations },
+
+  { "pushTransformationResult", "(Ljava/lang/String;[B)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_pushTransformationResult },
+};
+
+void register_android_jvmti_cts_JvmtiRedefineClassesTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiRedefineClassesTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiRedefineClassesTest class";
+  }
+}
+
 }  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/tagging.cpp b/hostsidetests/jvmti/base/jni/tagging.cpp
index 372805b..35d83d7 100644
--- a/hostsidetests/jvmti/base/jni/tagging.cpp
+++ b/hostsidetests/jvmti/base/jni/tagging.cpp
@@ -18,6 +18,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "jni_binder.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
@@ -127,5 +128,48 @@
   return CreateObjectArray(env, 3, "java/lang/Object", callback);
 }
 
+static JNINativeMethod gMethodsForMain[] = {
+  { "setTag", "(Ljava/lang/Object;J)V",
+          (void*)Java_android_jvmti_cts_JniBindings_setTag },
+
+  { "getTag", "(Ljava/lang/Object;)J",
+          (void*)Java_android_jvmti_cts_JniBindings_getTag },
+};
+
+void register_art_Main(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env, "art/Main", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethodsForMain,
+          sizeof(gMethodsForMain) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for Main class";
+  }
+}
+
+static JNINativeMethod gMethods[] = {
+  { "getTaggedObjects", "([JZZ)[Ljava/lang/Object;",
+          (void*)Java_android_jvmti_cts_JvmtiTaggingTest_getTaggedObjects },
+};
+
+void register_android_jvmti_cts_JvmtiTaggingTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiTaggingTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiTaggingTest class";
+  }
+}
+
 }  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/tracking.cpp b/hostsidetests/jvmti/base/jni/tracking.cpp
index 23acde9..5474319 100644
--- a/hostsidetests/jvmti/base/jni/tracking.cpp
+++ b/hostsidetests/jvmti/base/jni/tracking.cpp
@@ -21,6 +21,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/stringprintf.h"
+#include "jni_binder.h"
 #include "jvmti_helper.h"
 #include "scoped_local_ref.h"
 #include "scoped_utf_chars.h"
@@ -104,4 +105,30 @@
   return env->NewStringUTF(result.c_str());
 }
 
+static JNINativeMethod gMethods[] = {
+  { "setupObjectAllocCallback", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_setupObjectAllocCallback },
+
+  { "enableAllocationTracking", "(Ljava/lang/Thread;Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_enableAllocationTracking },
+
+  { "getAndResetAllocationTrackingString", "()Ljava/lang/String;",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_getAndResetAllocationTrackingString },
+};
+
+void register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiTrackingTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiTrackingTest class";
+  }
+}
+
 }  // namespace art
diff --git a/hostsidetests/jvmti/run-tests/Android.mk b/hostsidetests/jvmti/run-tests/Android.mk
index 3628877..f9edd2f 100644
--- a/hostsidetests/jvmti/run-tests/Android.mk
+++ b/hostsidetests/jvmti/run-tests/Android.mk
@@ -132,6 +132,7 @@
   src/1941-dispose-stress/src/art/Test1941.java \
   src/1942-suspend-raw-monitor-exit/src/art/Test1942.java \
   src/1943-suspend-raw-monitor-wait/src/art/Test1943.java \
+  src/1953-pop-frame/src/art/Test1953.java \
 
 JVMTI_RUN_TEST_GENERATED_NUMBERS := \
   901 \
@@ -221,6 +222,7 @@
   1941 \
   1942 \
   1943 \
+  1953 \
 
 # Try to enforce that the directories correspond to the Java files we pull in.
 JVMTI_RUN_TEST_DIR_CHECK := $(sort $(foreach DIR,$(addprefix src/,$(JVMTI_RUN_TEST_GENERATED_NUMBERS)), \
diff --git a/hostsidetests/jvmti/run-tests/test-1953/Android.mk b/hostsidetests/jvmti/run-tests/test-1953/Android.mk
new file mode 100644
index 0000000..1bcbee5
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-1953/Android.mk
@@ -0,0 +1,21 @@
+# 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_MODULE := CtsJvmtiRunTest1953HostTestCases
+
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-1953/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-1953/AndroidTest.xml
new file mode 100644
index 0000000..9309740
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-1953/AndroidTest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for CTS JVMTI test cases">
+    <option name="test-suite-tag" value="cts"/>
+    <option name="config-descriptor:metadata" key="component" value="art" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest1953DeviceApp.apk" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest1953HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest1953DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_1953" />
+        <option name="runtime-hint" value="8s"/>
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-1953/app/Android.mk b/hostsidetests/jvmti/run-tests/test-1953/app/Android.mk
new file mode 100644
index 0000000..53cb264
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-1953/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest1953DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-1953/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-1953/app/AndroidManifest.xml
new file mode 100644
index 0000000..d3c4495
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-1953/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_1953">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="1953" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_1953" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-1953/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-1953/jarjar-rules.txt
new file mode 100644
index 0000000..972a3f3
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-1953/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest1953@1
diff --git a/hostsidetests/net/src/com/android/cts/net/ProcNetTest.java b/hostsidetests/net/src/com/android/cts/net/ProcNetTest.java
new file mode 100644
index 0000000..19e61c6
--- /dev/null
+++ b/hostsidetests/net/src/com/android/cts/net/ProcNetTest.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.tradefed.testtype.IDeviceTest;
+
+import java.lang.Integer;
+import java.lang.String;
+import java.util.Arrays;
+import java.util.List;
+import java.util.ArrayList;
+
+/**
+ * Host-side tests for values in /proc/net.
+ *
+ * These tests analyze /proc/net to verify that certain networking properties are correct.
+ */
+public class ProcNetTest extends DeviceTestCase implements IBuildReceiver, IDeviceTest {
+    private static final String SPI_TIMEOUT_SYSCTL = "/proc/sys/net/core/xfrm_acq_expires";
+    private static final int MIN_ACQ_EXPIRES = 3600;
+    // Global sysctls. Must be present and set to 1.
+    private static final String[] GLOBAL_SYSCTLS = {
+        "/proc/sys/net/ipv4/fwmark_reflect",
+        "/proc/sys/net/ipv6/fwmark_reflect",
+        "/proc/sys/net/ipv4/tcp_fwmark_accept",
+    };
+
+    // Per-interface IPv6 autoconf sysctls.
+    private static final String IPV6_SYSCTL_DIR = "/proc/sys/net/ipv6/conf";
+    private static final String AUTOCONF_SYSCTL = "accept_ra_rt_table";
+
+    // Expected values for MIN|MAX_PLEN.
+    private static final String ACCEPT_RA_RT_INFO_MIN_PLEN_STRING = "accept_ra_rt_info_min_plen";
+    private static final int ACCEPT_RA_RT_INFO_MIN_PLEN_VALUE = 48;
+    private static final String ACCEPT_RA_RT_INFO_MAX_PLEN_STRING = "accept_ra_rt_info_max_plen";
+    private static final int ACCEPT_RA_RT_INFO_MAX_PLEN_VALUE = 64;
+    // Expected values for RFC 7559 router soliciations.
+    // Maximum number of router solicitations to send. -1 means no limit.
+    private static final int IPV6_WIFI_ROUTER_SOLICITATIONS = -1;
+    private ITestDevice mDevice;
+    private IBuildInfo mBuild;
+    private String[] mSysctlDirs;
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setBuild(IBuildInfo build) {
+        mBuild = build;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setDevice(ITestDevice device) {
+        super.setDevice(device);
+        mDevice = device;
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mSysctlDirs = getSysctlDirs();
+    }
+
+    private String[] getSysctlDirs() throws Exception {
+        String interfaceDirs[] = mDevice.executeAdbCommand("shell", "ls", "-1",
+                IPV6_SYSCTL_DIR).split("\n");
+        List<String> interfaceDirsList = new ArrayList<String>(Arrays.asList(interfaceDirs));
+        interfaceDirsList.remove("all");
+        interfaceDirsList.remove("lo");
+        return interfaceDirsList.toArray(new String[interfaceDirsList.size()]);
+    }
+
+
+    protected void assertLess(String sysctl, int a, int b) {
+        assertTrue("value of " + sysctl + ": expected < " + b + " but was: " + a, a < b);
+    }
+
+    protected void assertAtLeast(String sysctl, int a, int b) {
+        assertTrue("value of " + sysctl + ": expected >= " + b + " but was: " + a, a >= b);
+    }
+
+    public int readIntFromPath(String path) throws Exception {
+        String mode = mDevice.executeAdbCommand("shell", "stat", "-c", "%a", path).trim();
+        String user = mDevice.executeAdbCommand("shell", "stat", "-c", "%u", path).trim();
+        String group = mDevice.executeAdbCommand("shell", "stat", "-c", "%g", path).trim();
+        assertEquals(mode, "644");
+        assertEquals(user, "0");
+        assertEquals(group, "0");
+        return Integer.parseInt(mDevice.executeAdbCommand("shell", "cat", path).trim());
+    }
+
+    /**
+     * Checks that SPI default timeouts are overridden, and set to a reasonable length of time
+     */
+    public void testMinAcqExpires() throws Exception {
+        int value = readIntFromPath(SPI_TIMEOUT_SYSCTL);
+        assertAtLeast(SPI_TIMEOUT_SYSCTL, value, MIN_ACQ_EXPIRES);
+    }
+
+    /**
+     * Checks that the sysctls for multinetwork kernel features are present and
+     * enabled.
+     */
+    public void testProcSysctls() throws Exception {
+        for (String sysctl : GLOBAL_SYSCTLS) {
+            int value = readIntFromPath(sysctl);
+            assertEquals(sysctl, 1, value);
+        }
+
+        for (String interfaceDir : mSysctlDirs) {
+            String path = IPV6_SYSCTL_DIR + "/" + interfaceDir + "/" + AUTOCONF_SYSCTL;
+            int value = readIntFromPath(path);
+            assertLess(path, value, 0);
+        }
+    }
+
+    /**
+     * Verify that accept_ra_rt_info_{min,max}_plen exists and is set to the expected value
+     */
+    public void testAcceptRaRtInfoMinMaxPlen() throws Exception {
+        for (String interfaceDir : mSysctlDirs) {
+            String path = IPV6_SYSCTL_DIR + "/" + interfaceDir + "/" + "accept_ra_rt_info_min_plen";
+            int value = readIntFromPath(path);
+            assertEquals(path, value, ACCEPT_RA_RT_INFO_MIN_PLEN_VALUE);
+            path = IPV6_SYSCTL_DIR + "/" + interfaceDir + "/" + "accept_ra_rt_info_max_plen";
+            value = readIntFromPath(path);
+            assertEquals(path, value, ACCEPT_RA_RT_INFO_MAX_PLEN_VALUE);
+        }
+    }
+
+    /**
+     * Verify that router_solicitations exists and is set to the expected value
+     * and verify that router_solicitation_max_interval exists and is in an acceptable interval.
+     */
+    public void testRouterSolicitations() throws Exception {
+        for (String interfaceDir : mSysctlDirs) {
+            String path = IPV6_SYSCTL_DIR + "/" + interfaceDir + "/" + "router_solicitations";
+            int value = readIntFromPath(path);
+            assertEquals(IPV6_WIFI_ROUTER_SOLICITATIONS, value);
+            path = IPV6_SYSCTL_DIR + "/" + interfaceDir + "/" + "router_solicitation_max_interval";
+            int interval = readIntFromPath(path);
+            final int lowerBoundSec = 15 * 60;
+            final int upperBoundSec = 60 * 60;
+            assertTrue(lowerBoundSec <= interval);
+            assertTrue(interval <= upperBoundSec);
+        }
+    }
+}
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.mk
index 7a3e054..bcded5b 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.mk
@@ -31,9 +31,5 @@
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_USE_AAPT2 := true
-# Disable AAPT2 manifest checks to fix:
-# cts/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/AndroidManifest.xml:28: error: unexpected element <additional-certificate> found in <manifest><application><uses-static-library>.
-# TODO(b/79755007): Remove when AAPT2 recognizes the manifest elements.
-LOCAL_AAPT_FLAGS += --warn-manifest-validation
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java b/hostsidetests/security/src/android/cts/security/KernelConfigTest.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/KernelConfigTest.java
rename to hostsidetests/security/src/android/cts/security/KernelConfigTest.java
diff --git a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java b/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
rename to hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
diff --git a/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
index 8709f14..9469a0c 100644
--- a/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
+++ b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
@@ -18,6 +18,7 @@
 
 import android.app.Activity;
 import android.content.Intent;
+import android.content.res.Configuration;
 import android.os.Build;
 import android.os.Bundle;
 import android.theme.app.modifiers.DatePickerModifier;
@@ -76,6 +77,11 @@
         mTheme = THEMES[themeIndex];
 
         setTheme(mTheme.id);
+
+        // Force text scaling to 1.0 regardless of system default.
+        Configuration config = new Configuration();
+        config.fontScale = 1.0f;
+        getResources().updateConfiguration(config, null);
         setContentView(R.layout.theme_test);
 
         mViewGroup = (ReferenceViewGroup) findViewById(R.id.reference_view_group);
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
index e559f18..3ac1314 100644
--- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
+++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -89,7 +89,7 @@
         super.setUp();
 
         mDevice = getDevice();
-
+        mDevice.executeShellCommand("settings put system font_scale 1.0");
         final String density = getDensityBucketForDevice(mDevice);
         final String referenceZipAssetPath = String.format("/%s.zip", density);
         mReferences = extractReferenceImages(referenceZipAssetPath);
@@ -273,7 +273,8 @@
         final Pattern p = Pattern.compile("Override density: (\\d+)");
         final Matcher m = p.matcher(output);
         if (m.find()) {
-            return Integer.parseInt(m.group(1));
+            throw new RuntimeException("Cannot test device running at non-default density: "
+                    + Integer.parseInt(m.group(1)));
         }
 
         final String densityProp;
diff --git a/hostsidetests/ui/Android.mk b/hostsidetests/ui/Android.mk
index 90fdad2..5450454 100644
--- a/hostsidetests/ui/Android.mk
+++ b/hostsidetests/ui/Android.mk
@@ -30,8 +30,8 @@
 
 LOCAL_CTS_TEST_PACKAGE := android.ui.cts
 
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := general-tests cts_instant
+# *Not* tagged as a cts test artifact intentionally: b/109660132
+LOCAL_COMPATIBILITY_SUITE := general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/tests/app/app/Android.mk b/tests/app/app/Android.mk
index 2d24cb5..69c6d76 100644
--- a/tests/app/app/Android.mk
+++ b/tests/app/app/Android.mk
@@ -48,9 +48,5 @@
 LOCAL_PRIVATE_PLATFORM_APIS := true
 
 LOCAL_USE_AAPT2 := true
-# Disable AAPT2 manifest checks to fix:
-# cts/tests/app/app/AndroidManifest.xml:25: error: unexpected element <meta-data> found in <manifest><permission>.
-# TODO(b/79755007): Remove when AAPT2 recognizes the manifest elements.
-LOCAL_AAPT_FLAGS += --warn-manifest-validation
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
index 7924d93..b6a031a 100644
--- a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
@@ -914,10 +914,12 @@
      * Test that the foreground service app op does prevent the foreground state.
      */
     public void testForegroundServiceAppOp() throws Exception {
+        // Use default timeout value 5000
         final ServiceProcessController controller = new ServiceProcessController(mContext,
-                getInstrumentation(), STUB_PACKAGE_NAME, mAllProcesses, WAIT_TIME);
+                getInstrumentation(), STUB_PACKAGE_NAME, mAllProcesses);
+        // Use default timeout value 5000
         final ServiceConnectionHandler conn = new ServiceConnectionHandler(mContext,
-                mServiceIntent, WAIT_TIME);
+                mServiceIntent);
         final WatchUidRunner uidWatcher = controller.getUidWatcher();
 
         try {
diff --git a/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/app/src/android/app/cts/ActivityManagerTest.java
index be30de1..747c52e 100644
--- a/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -437,11 +437,13 @@
      * lifetime tests.
      */
     private void launchHome() throws Exception {
-        Intent intent = new Intent(Intent.ACTION_MAIN);
-        intent.addCategory(Intent.CATEGORY_HOME);
-        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        mContext.startActivity(intent);
-        Thread.sleep(WAIT_TIME);
+        if (!noHomeScreen()) {
+            Intent intent = new Intent(Intent.ACTION_MAIN);
+            intent.addCategory(Intent.CATEGORY_HOME);
+            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            mContext.startActivity(intent);
+            Thread.sleep(WAIT_TIME);
+        }
     }
 
    /**
diff --git a/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/app/src/android/app/cts/SystemFeaturesTest.java
index 40774c7..09d99a3 100644
--- a/tests/app/src/android/app/cts/SystemFeaturesTest.java
+++ b/tests/app/src/android/app/cts/SystemFeaturesTest.java
@@ -43,6 +43,8 @@
 import android.telephony.TelephonyManager;
 import android.test.InstrumentationTestCase;
 
+import com.android.compatibility.common.util.PropertyUtil;
+
 import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -495,6 +497,7 @@
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION) &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_WATCH) &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_EMBEDDED) &&
+                !isAndroidEmulator() &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_PC)) {
             // USB accessory mode is only a requirement for devices with USB ports supporting
             // peripheral mode. As there is no public API to distinguish a device with only host
@@ -543,6 +546,10 @@
         }
     }
 
+    private boolean isAndroidEmulator() {
+        return PropertyUtil.propertyEquals("ro.kernel.qemu", "1");
+    }
+
     private void assertFeature(boolean exist, String feature) {
         if (exist) {
             assertAvailable(feature);
diff --git a/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java b/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
index b772ce2..30f7a85 100644
--- a/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
+++ b/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
@@ -29,10 +29,14 @@
 
     private boolean mReady;
 
+    private boolean mStarted;
+    private Bundle mExtras;
+
     @Override
     public void onReady() {
         super.onReady();
         mReady = true;
+        showSessionIfReady();
     }
 
     @Override
@@ -43,13 +47,18 @@
             stopSelf();
             return START_NOT_STICKY;
         }
-        if (mReady) {
-            Bundle extras = intent.getExtras() != null ? intent.getExtras() : new Bundle();
-            showSession(extras, 0);
-        }
+        mExtras = intent.getExtras() != null ? intent.getExtras() : new Bundle();
+        mStarted = true;
+        showSessionIfReady();
         return START_NOT_STICKY;
     }
 
+    private void showSessionIfReady() {
+        if (mReady && mStarted) {
+            showSession(mExtras, 0);
+        }
+    };
+
     /**
      * Starts the assistant voice interaction service, which initiates a new session that starts
      * the assistant activity.
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java
index 0d09a2d..41f4006 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java
@@ -404,14 +404,14 @@
         assumeTrue("Skipping test: no rotation support", supportsRotation());
 
         LogSeparator logSeparator = separateLogs();
-        launchActivity(PORTRAIT_ORIENTATION_ACTIVITY);
+        launchActivity(PORTRAIT_ORIENTATION_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
         mAmWmState.assertVisibility(PORTRAIT_ORIENTATION_ACTIVITY, true /* visible */);
 
         assertLifecycleCounts(PORTRAIT_ORIENTATION_ACTIVITY, logSeparator, 1 /* create */,
                 1 /* start */, 1 /* resume */, 0 /* pause */, 0 /* stop */, 0 /* destroy */,
                 0 /* config */);
 
-        launchActivity(LANDSCAPE_ORIENTATION_ACTIVITY);
+        launchActivity(LANDSCAPE_ORIENTATION_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
         mAmWmState.assertVisibility(LANDSCAPE_ORIENTATION_ACTIVITY, true /* visible */);
 
         assertLifecycleCounts(PORTRAIT_ORIENTATION_ACTIVITY, logSeparator, 1 /* create */,
@@ -421,7 +421,7 @@
                 1 /* start */, 1 /* resume */, 0 /* pause */, 0 /* stop */, 0 /* destroy */,
                 0 /* config */);
 
-        launchActivity(PORTRAIT_ORIENTATION_ACTIVITY);
+        launchActivity(PORTRAIT_ORIENTATION_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
         mAmWmState.assertVisibility(PORTRAIT_ORIENTATION_ACTIVITY, true /* visible */);
 
         assertLifecycleCounts(PORTRAIT_ORIENTATION_ACTIVITY, logSeparator, 2 /* create */,
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
index a873c09..94e9b63 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
@@ -565,7 +565,7 @@
 
         // Launch first PIP activity
         launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
-        waitForEnterPip(PIP_ACTIVITY);
+        waitForEnterPipAnimationComplete(PIP_ACTIVITY);
 
         // Launch second PIP activity
         launchActivity(PIP_ACTIVITY2, EXTRA_ENTER_PIP, "true");
diff --git a/tests/framework/base/activitymanager/src/android/server/am/DisplaySizeTest.java b/tests/framework/base/activitymanager/src/android/server/am/DisplaySizeTest.java
index 98e3ba7..83ceabd 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/DisplaySizeTest.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/DisplaySizeTest.java
@@ -93,10 +93,12 @@
                 EXTRA_LAUNCH_ANOTHER_ACTIVITY, getActivityName(TEST_ACTIVITY));
         executeShellCommand(startActivityOnTop);
         mAmWmState.assertActivityDisplayed(TEST_ACTIVITY);
+        final LogSeparator logSeparator = separateLogs();
 
         try (final ScreenDensitySession screenDensitySession = new ScreenDensitySession()) {
             screenDensitySession.setUnsupportedDensity();
 
+            assertActivityLifecycle(TEST_ACTIVITY, true /* relaunched */, logSeparator);
             pressBackButton();
 
             mAmWmState.assertActivityDisplayed(SMALLEST_WIDTH_ACTIVITY);
diff --git a/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml b/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
index e7b3453..c044981 100644
--- a/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
@@ -18,7 +18,8 @@
         package="android.server.wm.dndsourceapp"
         android:targetSandboxVersion="2">
     <application android:label="CtsDnDSource">
-        <activity android:name="android.server.wm.dndsourceapp.DragSource">
+        <activity android:name="android.server.wm.dndsourceapp.DragSource"
+                android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER"/>
diff --git a/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml b/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
index 09a0bc9..7d50b70 100644
--- a/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
@@ -18,7 +18,8 @@
         package="android.server.wm.dndtargetapp"
         android:targetSandboxVersion="2">
     <application android:label="CtsDnDTarget">
-        <activity android:name="android.server.wm.dndtargetapp.DropTarget">
+        <activity android:name="android.server.wm.dndtargetapp.DropTarget"
+                android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER"/>
diff --git a/tests/jdwp/TEST_MAPPING b/tests/jdwp/TEST_MAPPING
new file mode 100644
index 0000000..0c53164
--- /dev/null
+++ b/tests/jdwp/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsJdwpTestCases"
+    }
+  ]
+}
diff --git a/tests/jdwp/runner/device-side/src/com/android/compatibility/dalvik/DalvikTestRunner.java b/tests/jdwp/runner/device-side/src/com/android/compatibility/dalvik/DalvikTestRunner.java
index 99daac1..cce81d0 100644
--- a/tests/jdwp/runner/device-side/src/com/android/compatibility/dalvik/DalvikTestRunner.java
+++ b/tests/jdwp/runner/device-side/src/com/android/compatibility/dalvik/DalvikTestRunner.java
@@ -29,6 +29,8 @@
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
@@ -39,6 +41,7 @@
 import java.util.List;
 import java.util.Scanner;
 import java.util.Set;
+import java.util.function.Consumer;
 
 /**
  * Runs tests against the Dalvik VM.
@@ -120,33 +123,59 @@
         System.out.println(String.format("end-run:%d", end - start));
     }
 
+    private static void iterateTests(Test test, Set<String> includes, Set<String> excludes,
+            Consumer<Test> sink) {
+        if (test instanceof TestSuite) {
+            // If the test is a suite it could contain multiple tests, these need to be split
+            // out into separate tests so they can be filtered
+            TestSuite suite = (TestSuite) test;
+            Enumeration<Test> enumerator = suite.tests();
+            while (enumerator.hasMoreElements()) {
+                iterateTests(enumerator.nextElement(), includes, excludes, sink);
+            }
+            return;
+        }
+        if (shouldRun(test, includes, excludes)) {
+            sink.accept(test);
+        }
+    }
+
     /* Recursively collect tests, since Test elements of the TestSuite may also be TestSuite
      * objects containing Tests. */
     private static void collectTests(TestSuite suite, TestListener listener,
             Set<String> includes, Set<String> excludes) {
-
-        Enumeration<Test> tests = suite.tests();
-        while (tests.hasMoreElements()) {
-            Test test = tests.nextElement();
-            if (test instanceof TestSuite) {
-                collectTests((TestSuite) test, listener, includes, excludes);
-            } else if (shouldCollect(test, includes, excludes)) {
-                listener.startTest(test);
-                listener.endTest(test);
-            }
-        }
+        iterateTests(suite, includes, excludes, test -> {
+            listener.startTest(test);
+            listener.endTest(test);
+        });
     }
 
-    /* Copied from FilterableTestSuite.shouldRun(), which is private */
-    private static boolean shouldCollect(Test test, Set<String> includes, Set<String> excludes) {
+    private static boolean packageFilterApplies(String className, Set<String> filters) {
+      // Traditional meaning: equality.
+      int index = className.lastIndexOf('.');
+      String packageName = index < 0 ? "" : className.substring(0, index);
+      if (filters.contains(packageName)) {
+        return true;
+      }
+
+      // See if it's a name prefix, for JarJared names.
+      for (String filter : filters) {
+        if (className.startsWith(filter) && className.length() > filter.length() &&
+                className.charAt(filter.length()) == '_') {
+            return true;
+        }
+      }
+
+      return false;
+    }
+
+    private static boolean shouldRun(Test test, Set<String> includes, Set<String> excludes) {
         String fullName = test.toString();
         String[] parts = fullName.split("[\\(\\)]");
         String className = parts[1];
         String methodName = String.format("%s#%s", className, parts[0]);
-        int index = className.lastIndexOf('.');
-        String packageName = index < 0 ? "" : className.substring(0, index);
 
-        if (excludes.contains(packageName)) {
+        if (packageFilterApplies(className, excludes)) {
             // Skip package because it was excluded
             return false;
         }
@@ -161,7 +190,7 @@
         return includes.isEmpty()
                 || includes.contains(methodName)
                 || includes.contains(className)
-                || includes.contains(packageName);
+                || packageFilterApplies(className, includes);
     }
 
     private static void loadFilters(String filename, Set<String> filters) {
@@ -308,7 +337,20 @@
         }
 
         public static String stringify(Throwable error) {
-            return Arrays.toString(error.getStackTrace()).replaceAll("\n", " ");
+            String output = null;
+            try {
+              try (StringWriter sw = new StringWriter()) {
+                try (PrintWriter pw = new PrintWriter(sw)) {
+                  error.printStackTrace(pw);
+                }
+                output = sw.toString();
+              }
+            } catch (Exception e) {
+              if (output == null) {
+                output = error.toString() + Arrays.toString(error.getStackTrace());
+              }
+            }
+            return output.replace("\n", "^~^");
         }
     }
 
@@ -337,77 +379,25 @@
             mExcludes = excludes;
         }
 
-        /**
-         * {@inheritDoc}
-         */
+        private static class CountConsumer implements Consumer<Test> {
+            public int count = 0;
+
+            @Override
+            public void accept(Test t) {
+                count++;
+            }
+        }
+
         @Override
         public int countTestCases() {
-            return countTests(this);
+            CountConsumer counter = new CountConsumer();
+            iterateTests(this, mIncludes, mExcludes, counter);
+            return counter.count;
         }
 
-        private int countTests(Test test) {
-            if (test instanceof TestSuite) {
-                // If the test is a suite it could contain multiple tests, these need to be split
-                // out into separate tests so they can be filtered
-                TestSuite suite = (TestSuite) test;
-                Enumeration<Test> enumerator = suite.tests();
-                int count = 0;
-                while (enumerator.hasMoreElements()) {
-                    count += countTests(enumerator.nextElement());
-                }
-                return count;
-            } else if (shouldRun(test)) {
-                return 1;
-            }
-            return 0;
-        }
-
-        /**
-         * {@inheritDoc}
-         */
         @Override
         public void runTest(Test test, TestResult result) {
-            runTests(test, result);
-        }
-
-        private void runTests(Test test, TestResult result) {
-            if (test instanceof TestSuite) {
-                // If the test is a suite it could contain multiple tests, these need to be split
-                // out into separate tests so they can be filtered
-                TestSuite suite = (TestSuite) test;
-                Enumeration<Test> enumerator = suite.tests();
-                while (enumerator.hasMoreElements()) {
-                    runTests(enumerator.nextElement(), result);
-                }
-            } else if (shouldRun(test)) {
-                test.run(result);
-            }
-        }
-
-        private boolean shouldRun(Test test) {
-            String fullName = test.toString();
-            String[] parts = fullName.split("[\\(\\)]");
-            String className = parts[1];
-            String methodName = String.format("%s#%s", className, parts[0]);
-            int index = className.lastIndexOf('.');
-            String packageName = index < 0 ? "" : className.substring(0, index);
-
-            if (mExcludes.contains(packageName)) {
-                // Skip package because it was excluded
-                return false;
-            }
-            if (mExcludes.contains(className)) {
-                // Skip class because it was excluded
-                return false;
-            }
-            if (mExcludes.contains(methodName)) {
-                // Skip method because it was excluded
-                return false;
-            }
-            return mIncludes.isEmpty()
-                    || mIncludes.contains(methodName)
-                    || mIncludes.contains(className)
-                    || mIncludes.contains(packageName);
+            iterateTests(test, mIncludes, mExcludes, t -> t.run(result));
         }
     }
 }
diff --git a/tests/jdwp/runner/host-side/resources/expectations/external_oj_libjdwp_art_failures.txt b/tests/jdwp/runner/host-side/resources/expectations/external_oj_libjdwp_art_failures.txt
index 61cf050..72c81cf 100644
--- a/tests/jdwp/runner/host-side/resources/expectations/external_oj_libjdwp_art_failures.txt
+++ b/tests/jdwp/runner/host-side/resources/expectations/external_oj_libjdwp_art_failures.txt
@@ -8,45 +8,45 @@
   description: "Test fails due to unexpectedly getting the thread-groups of zombie threads",
   result: EXEC_FAILED,
   bug: 66906414,
-  name: "org.apache.harmony.jpda.tests.jdwp.ThreadReference.ThreadGroup002Test#testThreadGroup002"
+  name: "org.apache.harmony.jpda.tests.jdwp.ThreadReference_ThreadGroup002Test#testThreadGroup002"
 },
 {
   description: "This test is incorrect since it blindly requests local variables without checking their slot numbers.",
   result: EXEC_FAILED,
   bug: 74028528,
-  name: "org.apache.harmony.jpda.tests.jdwp.Events.Breakpoint003Test#testBreakPointInFrameworkCode"
+  name: "org.apache.harmony.jpda.tests.jdwp.Events_Breakpoint003Test#testBreakPointInFrameworkCode"
 },
 {
   description: "Test fails due to static values not being set correctly.",
   result: EXEC_FAILED,
   bug: 66905894,
-  name: "org.apache.harmony.jpda.tests.jdwp.ReferenceType.GetValues006Test#testGetValues006"
+  name: "org.apache.harmony.jpda.tests.jdwp.ReferenceType_GetValues006Test#testGetValues006"
 },
 {
   description: "Tests that fail on both ART and RI. These tests are likely incorrect",
   result: EXEC_FAILED,
   bug: 66906734,
-  names: [ "org.apache.harmony.jpda.tests.jdwp.ArrayReference.SetValues003Test#testSetValues003_InvalidIndex",
-           "org.apache.harmony.jpda.tests.jdwp.ClassType.InvokeMethod002Test#testInvokeMethod_wrong_argument_types",
-           "org.apache.harmony.jpda.tests.jdwp.ClassType.InvokeMethodTest#testInvokeMethod002",
-           "org.apache.harmony.jpda.tests.jdwp.ClassType.InvokeMethodTest#testInvokeMethod003",
-           "org.apache.harmony.jpda.tests.jdwp.ClassType.NewInstanceTest#testNewInstance002",
-           "org.apache.harmony.jpda.tests.jdwp.ClassType.SetValues002Test#testSetValues002",
-           "org.apache.harmony.jpda.tests.jdwp.Events.ClassPrepare002Test#testClassPrepareCausedByDebugger",
-           "org.apache.harmony.jpda.tests.jdwp.Events.ExceptionCaughtTest#testExceptionEvent_ThrowLocation_FromNative",
-           "org.apache.harmony.jpda.tests.jdwp.ObjectReference.DisableCollectionTest#testDisableCollection_null",
-           "org.apache.harmony.jpda.tests.jdwp.ObjectReference.EnableCollectionTest#testEnableCollection_invalid",
-           "org.apache.harmony.jpda.tests.jdwp.ObjectReference.EnableCollectionTest#testEnableCollection_null",
-           "org.apache.harmony.jpda.tests.jdwp.ObjectReference.GetValues002Test#testGetValues002",
-           "org.apache.harmony.jpda.tests.jdwp.ObjectReference.SetValues003Test#testSetValues003",
-           "org.apache.harmony.jpda.tests.jdwp.ObjectReference.SetValuesTest#testSetValues001",
-           "org.apache.harmony.jpda.tests.jdwp.ReferenceType.FieldsWithGenericTest#testFieldsWithGeneric001",
-           "org.apache.harmony.jpda.tests.jdwp.ReferenceType.GetValues002Test#testGetValues002",
-           "org.apache.harmony.jpda.tests.jdwp.ReferenceType.GetValues004Test#testGetValues004",
-           "org.apache.harmony.jpda.tests.jdwp.StringReference.ValueTest#testStringReferenceValueTest001_NullString",
-           "org.apache.harmony.jpda.tests.jdwp.ThreadGroupReference.ChildrenTest#testChildren_NullObject",
-           "org.apache.harmony.jpda.tests.jdwp.ThreadGroupReference.NameTest#testName001_NullObject",
-           "org.apache.harmony.jpda.tests.jdwp.ThreadGroupReference.ParentTest#testParent_NullObject",
-           "org.apache.harmony.jpda.tests.jdwp.VirtualMachine.CapabilitiesNewTest#testCapabilitiesNew001" ]
+  names: [ "org.apache.harmony.jpda.tests.jdwp.ArrayReference_SetValues003Test#testSetValues003_InvalidIndex",
+           "org.apache.harmony.jpda.tests.jdwp.ClassType_InvokeMethod002Test#testInvokeMethod_wrong_argument_types",
+           "org.apache.harmony.jpda.tests.jdwp.ClassType_InvokeMethodTest#testInvokeMethod002",
+           "org.apache.harmony.jpda.tests.jdwp.ClassType_InvokeMethodTest#testInvokeMethod003",
+           "org.apache.harmony.jpda.tests.jdwp.ClassType_NewInstanceTest#testNewInstance002",
+           "org.apache.harmony.jpda.tests.jdwp.ClassType_SetValues002Test#testSetValues002",
+           "org.apache.harmony.jpda.tests.jdwp.Events_ClassPrepare002Test#testClassPrepareCausedByDebugger",
+           "org.apache.harmony.jpda.tests.jdwp.Events_ExceptionCaughtTest#testExceptionEvent_ThrowLocation_FromNative",
+           "org.apache.harmony.jpda.tests.jdwp.ObjectReference_DisableCollectionTest#testDisableCollection_null",
+           "org.apache.harmony.jpda.tests.jdwp.ObjectReference_EnableCollectionTest#testEnableCollection_invalid",
+           "org.apache.harmony.jpda.tests.jdwp.ObjectReference_EnableCollectionTest#testEnableCollection_null",
+           "org.apache.harmony.jpda.tests.jdwp.ObjectReference_GetValues002Test#testGetValues002",
+           "org.apache.harmony.jpda.tests.jdwp.ObjectReference_SetValues003Test#testSetValues003",
+           "org.apache.harmony.jpda.tests.jdwp.ObjectReference_SetValuesTest#testSetValues001",
+           "org.apache.harmony.jpda.tests.jdwp.ReferenceType_FieldsWithGenericTest#testFieldsWithGeneric001",
+           "org.apache.harmony.jpda.tests.jdwp.ReferenceType_GetValues002Test#testGetValues002",
+           "org.apache.harmony.jpda.tests.jdwp.ReferenceType_GetValues004Test#testGetValues004",
+           "org.apache.harmony.jpda.tests.jdwp.StringReference_ValueTest#testStringReferenceValueTest001_NullString",
+           "org.apache.harmony.jpda.tests.jdwp.ThreadGroupReference_ChildrenTest#testChildren_NullObject",
+           "org.apache.harmony.jpda.tests.jdwp.ThreadGroupReference_NameTest#testName001_NullObject",
+           "org.apache.harmony.jpda.tests.jdwp.ThreadGroupReference_ParentTest#testParent_NullObject",
+           "org.apache.harmony.jpda.tests.jdwp.VirtualMachine_CapabilitiesNewTest#testCapabilitiesNew001" ]
 }
 ]
diff --git a/tests/jdwp/runner/host-side/resources/expectations/jdwp-known-failures.txt b/tests/jdwp/runner/host-side/resources/expectations/jdwp-known-failures.txt
index 3354b62..910d7b8 100644
--- a/tests/jdwp/runner/host-side/resources/expectations/jdwp-known-failures.txt
+++ b/tests/jdwp/runner/host-side/resources/expectations/jdwp-known-failures.txt
@@ -5,30 +5,30 @@
 {
   description: "CTS JDWP known failures",
   names: [
-    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand.OnthrowDebuggerLaunchTest#testDebuggerLaunch001",
-    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand.OnthrowDebuggerLaunchTest#testDebuggerLaunch002",
-    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand.OnthrowDebuggerLaunchTest#testDebuggerLaunch003",
-    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand.OnthrowDebuggerLaunchTest#testDebuggerLaunch004",
-    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand.OnthrowLaunchDebugger001#testDebugger002",
-    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand.OnthrowLaunchDebugger002#testDebugger",
-    "org.apache.harmony.jpda.tests.jdwp.Events.ClassUnloadTest#testClassUnloadEvent",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorContendedEnterTest#testMonitorContendedEnterForClassMatch",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorContendedEnteredTest#testMonitorContendedEnteredForClassMatch",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitTest#testMonitorWaitForClassExclude",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitTest#testMonitorWaitForClassMatchExact",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitTest#testMonitorWaitForClassMatchFirst",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitTest#testMonitorWaitForClassMatchSecond",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitTest#testMonitorWaitForClassOnly",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitedTest#testMonitorWaitedForClassExclude",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitedTest#testMonitorWaitedForClassMatchExact",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitedTest#testMonitorWaitedForClassMatchFirst",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitedTest#testMonitorWaitedForClassMatchSecond",
-    "org.apache.harmony.jpda.tests.jdwp.Events.MonitorWaitedTest#testMonitorWaitedForClassOnly",
-    "org.apache.harmony.jpda.tests.jdwp.ReferenceType.ClassFileVersionTest#testClassFileVersion001",
-    "org.apache.harmony.jpda.tests.jdwp.ReferenceType.NestedTypesTest#testNestedTypes001",
-    "org.apache.harmony.jpda.tests.jdwp.ThreadReference.StopTest#testStop001",
-    "org.apache.harmony.jpda.tests.jdwp.VirtualMachine.HoldEventsTest#testHoldEvents001",
-    "org.apache.harmony.jpda.tests.jdwp.VirtualMachine.ReleaseEventsTest#testReleaseEvents001"
+    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand_OnthrowDebuggerLaunchTest#testDebuggerLaunch001",
+    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand_OnthrowDebuggerLaunchTest#testDebuggerLaunch002",
+    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand_OnthrowDebuggerLaunchTest#testDebuggerLaunch003",
+    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand_OnthrowDebuggerLaunchTest#testDebuggerLaunch004",
+    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand_OnthrowLaunchDebugger001#testDebugger002",
+    "org.apache.harmony.jpda.tests.jdwp.DebuggerOnDemand_OnthrowLaunchDebugger002#testDebugger",
+    "org.apache.harmony.jpda.tests.jdwp.Events_ClassUnloadTest#testClassUnloadEvent",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorContendedEnterTest#testMonitorContendedEnterForClassMatch",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorContendedEnteredTest#testMonitorContendedEnteredForClassMatch",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitTest#testMonitorWaitForClassExclude",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitTest#testMonitorWaitForClassMatchExact",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitTest#testMonitorWaitForClassMatchFirst",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitTest#testMonitorWaitForClassMatchSecond",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitTest#testMonitorWaitForClassOnly",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitedTest#testMonitorWaitedForClassExclude",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitedTest#testMonitorWaitedForClassMatchExact",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitedTest#testMonitorWaitedForClassMatchFirst",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitedTest#testMonitorWaitedForClassMatchSecond",
+    "org.apache.harmony.jpda.tests.jdwp.Events_MonitorWaitedTest#testMonitorWaitedForClassOnly",
+    "org.apache.harmony.jpda.tests.jdwp.ReferenceType_ClassFileVersionTest#testClassFileVersion001",
+    "org.apache.harmony.jpda.tests.jdwp.ReferenceType_NestedTypesTest#testNestedTypes001",
+    "org.apache.harmony.jpda.tests.jdwp.ThreadReference_StopTest#testStop001",
+    "org.apache.harmony.jpda.tests.jdwp.VirtualMachine_HoldEventsTest#testHoldEvents001",
+    "org.apache.harmony.jpda.tests.jdwp.VirtualMachine_ReleaseEventsTest#testReleaseEvents001"
   ],
   bug: "16720689"
 }
diff --git a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
index 9f545dd..61e1988 100644
--- a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
+++ b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
@@ -52,6 +52,7 @@
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
@@ -441,7 +442,7 @@
                         test = getTestDescription(parts[1]);
                         listener.testStarted(test);
                     } else if (tag.equals(FAILURE)) {
-                        listener.testFailed(test, parts[1]);
+                        listener.testFailed(test, processSerializedValue(parts[1]));
                     } else if (tag.equals(END_TEST)) {
                         listener.testEnded(getTestDescription(parts[1]),
                                 Collections.<String, String>emptyMap());
@@ -451,6 +452,11 @@
                 }
             }
 
+            private String processSerializedValue(String input) {
+                // Opposite of stringify.
+                return input.replace("^~^", "\n");
+            }
+
             private TestDescription getTestDescription(String name) {
                 String[] parts = name.split("#");
                 String className = parts[0];
diff --git a/tests/libcore/luni/Android.mk b/tests/libcore/luni/Android.mk
index 619962b..568602f 100644
--- a/tests/libcore/luni/Android.mk
+++ b/tests/libcore/luni/Android.mk
@@ -51,6 +51,9 @@
 # where applicable.
 LOCAL_MULTILIB := both
 
+# This test requires cts-dalvik-host-test-runner to be built to run via Atest.
+LOCAL_HOST_REQUIRED_MODULES := cts-dalvik-host-test-runner
+
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
diff --git a/tests/libcore/wycheproof-bc/Android.mk b/tests/libcore/wycheproof-bc/Android.mk
index 61dc8c7..095940c 100644
--- a/tests/libcore/wycheproof-bc/Android.mk
+++ b/tests/libcore/wycheproof-bc/Android.mk
@@ -23,8 +23,6 @@
     cts-core-test-runner \
     wycheproof
 
-LOCAL_JAVA_LIBRARIES := bouncycastle
-
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
 
diff --git a/tests/libcore/wycheproof-bc/AndroidTest.xml b/tests/libcore/wycheproof-bc/AndroidTest.xml
index 2e92706..8e455bf 100644
--- a/tests/libcore/wycheproof-bc/AndroidTest.xml
+++ b/tests/libcore/wycheproof-bc/AndroidTest.xml
@@ -30,7 +30,7 @@
         <option name="instrumentation-arg" key="filter"
                 value="com.android.cts.core.runner.ExpectationBasedFilter" />
         <option name="core-expectation" value="/knownfailures.txt" />
-        <option name="runtime-hint" value="10m"/>
-        <option name="test-timeout" value="600000" />
+        <option name="runtime-hint" value="16m"/>
+        <option name="test-timeout" value="3600000" />
     </test>
 </configuration>
diff --git a/tests/libcore/wycheproof/Android.mk b/tests/libcore/wycheproof/Android.mk
index 015b49d..9975712 100644
--- a/tests/libcore/wycheproof/Android.mk
+++ b/tests/libcore/wycheproof/Android.mk
@@ -23,8 +23,6 @@
     cts-core-test-runner \
     wycheproof
 
-LOCAL_JAVA_LIBRARIES := conscrypt
-
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
 
diff --git a/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/QtaguidPermissionTest.java b/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/QtaguidPermissionTest.java
deleted file mode 100644
index 60d2a2a..0000000
--- a/tests/netlegacy22.permission/src/android/net/cts/legacy/api22/permission/QtaguidPermissionTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package android.net.cts.legacy.api22.permission;
-
-import android.content.Context;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.net.TrafficStats;
-import android.support.test.filters.MediumTest;
-import android.test.AndroidTestCase;
-
-import java.io.File;
-import java.net.ServerSocket;
-import java.net.Socket;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-public class QtaguidPermissionTest extends AndroidTestCase {
-
-    private static final String QTAGUID_STATS_FILE = "/proc/net/xt_qtaguid/stats";
-
-    @MediumTest
-    public void testDevQtaguidSane() throws Exception {
-        File f = new File("/dev/xt_qtaguid");
-        assertTrue(f.canRead());
-        assertFalse(f.canWrite());
-        assertFalse(f.canExecute());
-    }
-
-    public void testAccessPrivateTrafficStats() throws IOException {
-
-        final int ownAppUid = getContext().getApplicationInfo().uid;
-        try {
-            BufferedReader qtaguidReader = new BufferedReader(new FileReader(QTAGUID_STATS_FILE));
-            String line;
-            // Skip the header line;
-            qtaguidReader.readLine();
-            while ((line = qtaguidReader.readLine()) != null) {
-                String tokens[] = line.split(" ");
-                // Go through all the entries we find the qtaguid stats and fail if we find a stats
-                // with different uid.
-                if (tokens.length > 3 && !tokens[3].equals(String.valueOf(ownAppUid))) {
-                    fail("Other apps detailed traffic stats leaked, self uid: "
-                         + String.valueOf(ownAppUid) + " find uid: " + tokens[3]);
-                }
-            }
-            qtaguidReader.close();
-        } catch (FileNotFoundException e) {
-            fail("Was not able to access qtaguid/stats: " + e);
-        }
-    }
-
-    private void accessOwnTrafficStats(long expectedTxBytes) throws IOException {
-
-        final int ownAppUid = getContext().getApplicationInfo().uid;
-
-        long totalTxBytes = 0;
-        try {
-            BufferedReader qtaguidReader = new BufferedReader(new FileReader(QTAGUID_STATS_FILE));
-            String line;
-            while ((line = qtaguidReader.readLine()) != null) {
-                String tokens[] = line.split(" ");
-                if (tokens.length > 3 && tokens[3].equals(String.valueOf(ownAppUid))) {
-                    // Check the total stats of this uid is larger then 1MB
-                    if (tokens[2].equals("0x0")) {
-                        totalTxBytes += Integer.parseInt(tokens[7]);
-                    }
-                }
-            }
-            qtaguidReader.close();
-        } catch (FileNotFoundException e) {
-            fail("Was not able to access qtaguid/stats: " + e);
-        }
-        assertTrue(totalTxBytes + " expected to be greater than or equal to"
-            + expectedTxBytes + "bytes", totalTxBytes >= expectedTxBytes);
-    }
-
-    public void testAccessOwnQtaguidTrafficStats() throws IOException {
-
-        // Transfer 1MB of data across an explicitly localhost socket.
-        final int byteCount = 1024;
-        final int packetCount = 1024;
-
-        final ServerSocket server = new ServerSocket(0);
-        new Thread("CreatePrivateDataTest.createTrafficStatsWithTags") {
-            @Override
-            public void run() {
-                try {
-                    Socket socket = new Socket("localhost", server.getLocalPort());
-                    // Make sure that each write()+flush() turns into a packet:
-                    // disable Nagle.
-                    socket.setTcpNoDelay(true);
-                    OutputStream out = socket.getOutputStream();
-                    byte[] buf = new byte[byteCount];
-                    for (int i = 0; i < packetCount; i++) {
-                        TrafficStats.setThreadStatsTag(i % 10);
-                        TrafficStats.tagSocket(socket);
-                        out.write(buf);
-                        out.flush();
-                    }
-                    out.close();
-                    socket.close();
-                } catch (IOException e) {
-                  assertTrue("io exception" + e, false);
-                }
-            }
-        }.start();
-
-        try {
-            Socket socket = server.accept();
-            InputStream in = socket.getInputStream();
-            byte[] buf = new byte[byteCount];
-            int read = 0;
-            while (read < byteCount * packetCount) {
-                int n = in.read(buf);
-                assertTrue("Unexpected EOF", n > 0);
-                read += n;
-            }
-        } finally {
-            server.close();
-        }
-
-        accessOwnTrafficStats(byteCount * packetCount);
-    }
-}
diff --git a/tests/openglperf2/AndroidTest.xml b/tests/openglperf2/AndroidTest.xml
index 4ac0455..c0612be 100644
--- a/tests/openglperf2/AndroidTest.xml
+++ b/tests/openglperf2/AndroidTest.xml
@@ -23,7 +23,5 @@
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.opengl2.cts" />
         <option name="runtime-hint" value="4m" />
-        <!-- test-timeout unit is ms, value = 100 min -->
-        <option name="test-timeout" value="6000000" />
     </test>
 </configuration>
diff --git a/tests/security/Android.mk b/tests/security/Android.mk
index aecc076..5bee990 100755
--- a/tests/security/Android.mk
+++ b/tests/security/Android.mk
@@ -19,7 +19,7 @@
 # Don't include this package in any target.
 LOCAL_MODULE_TAGS := optional
 
-LOCAL_STATIC_JAVA_LIBRARIES := bouncycastle bouncycastle-bcpkix guava
+LOCAL_STATIC_JAVA_LIBRARIES := bouncycastle-unbundled bouncycastle-bcpkix-unbundled guava
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_MODULE := cts-security-test-support-library
 
diff --git a/tests/security/src/android/keystore/cts/Asn1Utils.java b/tests/security/src/android/keystore/cts/Asn1Utils.java
index 5e75fa7..9aa0092 100644
--- a/tests/security/src/android/keystore/cts/Asn1Utils.java
+++ b/tests/security/src/android/keystore/cts/Asn1Utils.java
@@ -18,16 +18,16 @@
 
 import com.google.common.collect.ImmutableSet;
 
-import com.android.org.bouncycastle.asn1.ASN1Boolean;
-import com.android.org.bouncycastle.asn1.ASN1Encodable;
-import com.android.org.bouncycastle.asn1.ASN1Enumerated;
-import com.android.org.bouncycastle.asn1.ASN1InputStream;
-import com.android.org.bouncycastle.asn1.ASN1Integer;
-import com.android.org.bouncycastle.asn1.ASN1OctetString;
-import com.android.org.bouncycastle.asn1.ASN1Primitive;
-import com.android.org.bouncycastle.asn1.ASN1Sequence;
-import com.android.org.bouncycastle.asn1.ASN1Set;
-import com.android.org.bouncycastle.asn1.DEROctetString;
+import org.bouncycastle.asn1.ASN1Boolean;
+import org.bouncycastle.asn1.ASN1Encodable;
+import org.bouncycastle.asn1.ASN1Enumerated;
+import org.bouncycastle.asn1.ASN1InputStream;
+import org.bouncycastle.asn1.ASN1Integer;
+import org.bouncycastle.asn1.ASN1OctetString;
+import org.bouncycastle.asn1.ASN1Primitive;
+import org.bouncycastle.asn1.ASN1Sequence;
+import org.bouncycastle.asn1.ASN1Set;
+import org.bouncycastle.asn1.DEROctetString;
 
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
diff --git a/tests/security/src/android/keystore/cts/Attestation.java b/tests/security/src/android/keystore/cts/Attestation.java
index 3070394..bf344ca 100644
--- a/tests/security/src/android/keystore/cts/Attestation.java
+++ b/tests/security/src/android/keystore/cts/Attestation.java
@@ -19,7 +19,7 @@
 import com.google.common.base.CharMatcher;
 import com.google.common.io.BaseEncoding;
 
-import com.android.org.bouncycastle.asn1.ASN1Sequence;
+import org.bouncycastle.asn1.ASN1Sequence;
 
 import java.security.cert.CertificateParsingException;
 import java.security.cert.X509Certificate;
diff --git a/tests/security/src/android/keystore/cts/AttestationApplicationId.java b/tests/security/src/android/keystore/cts/AttestationApplicationId.java
index 42f8ea7..e228bac 100644
--- a/tests/security/src/android/keystore/cts/AttestationApplicationId.java
+++ b/tests/security/src/android/keystore/cts/AttestationApplicationId.java
@@ -14,9 +14,9 @@
 
 package android.keystore.cts;
 
-import com.android.org.bouncycastle.asn1.ASN1Encodable;
-import com.android.org.bouncycastle.asn1.ASN1Sequence;
-import com.android.org.bouncycastle.asn1.ASN1Set;
+import org.bouncycastle.asn1.ASN1Encodable;
+import org.bouncycastle.asn1.ASN1Sequence;
+import org.bouncycastle.asn1.ASN1Set;
 
 import java.security.cert.CertificateParsingException;
 import java.security.MessageDigest;
diff --git a/tests/security/src/android/keystore/cts/AttestationPackageInfo.java b/tests/security/src/android/keystore/cts/AttestationPackageInfo.java
index 3c3e2bd..b527c8e 100644
--- a/tests/security/src/android/keystore/cts/AttestationPackageInfo.java
+++ b/tests/security/src/android/keystore/cts/AttestationPackageInfo.java
@@ -14,8 +14,8 @@
 
 package android.keystore.cts;
 
-import com.android.org.bouncycastle.asn1.ASN1Encodable;
-import com.android.org.bouncycastle.asn1.ASN1Sequence;
+import org.bouncycastle.asn1.ASN1Encodable;
+import org.bouncycastle.asn1.ASN1Sequence;
 
 import java.security.cert.CertificateParsingException;
 
diff --git a/tests/security/src/android/keystore/cts/AuthorizationList.java b/tests/security/src/android/keystore/cts/AuthorizationList.java
index e4c5eb6..c8bd8ae 100644
--- a/tests/security/src/android/keystore/cts/AuthorizationList.java
+++ b/tests/security/src/android/keystore/cts/AuthorizationList.java
@@ -27,12 +27,12 @@
 import android.security.keystore.KeyProperties;
 import android.util.Log;
 
-import com.android.org.bouncycastle.asn1.ASN1Encodable;
-import com.android.org.bouncycastle.asn1.ASN1Primitive;
-import com.android.org.bouncycastle.asn1.ASN1Sequence;
-import com.android.org.bouncycastle.asn1.ASN1SequenceParser;
-import com.android.org.bouncycastle.asn1.ASN1TaggedObject;
-import com.android.org.bouncycastle.asn1.ASN1InputStream;
+import org.bouncycastle.asn1.ASN1Encodable;
+import org.bouncycastle.asn1.ASN1Primitive;
+import org.bouncycastle.asn1.ASN1Sequence;
+import org.bouncycastle.asn1.ASN1SequenceParser;
+import org.bouncycastle.asn1.ASN1TaggedObject;
+import org.bouncycastle.asn1.ASN1InputStream;
 
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
diff --git a/tests/security/src/android/keystore/cts/CertificateUtils.java b/tests/security/src/android/keystore/cts/CertificateUtils.java
index 68e936e..c32a9cb 100644
--- a/tests/security/src/android/keystore/cts/CertificateUtils.java
+++ b/tests/security/src/android/keystore/cts/CertificateUtils.java
@@ -16,11 +16,11 @@
 
 package android.keystore.cts;
 
-import com.android.org.bouncycastle.asn1.x500.X500Name;
-import com.android.org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
-import com.android.org.bouncycastle.cert.X509CertificateHolder;
-import com.android.org.bouncycastle.cert.X509v3CertificateBuilder;
-import com.android.org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
 import java.io.ByteArrayInputStream;
 import java.math.BigInteger;
 import java.security.KeyPair;
diff --git a/tests/security/src/android/keystore/cts/RootOfTrust.java b/tests/security/src/android/keystore/cts/RootOfTrust.java
index b77b689..99577021 100644
--- a/tests/security/src/android/keystore/cts/RootOfTrust.java
+++ b/tests/security/src/android/keystore/cts/RootOfTrust.java
@@ -18,8 +18,8 @@
 
 import com.google.common.io.BaseEncoding;
 
-import com.android.org.bouncycastle.asn1.ASN1Encodable;
-import com.android.org.bouncycastle.asn1.ASN1Sequence;
+import org.bouncycastle.asn1.ASN1Encodable;
+import org.bouncycastle.asn1.ASN1Sequence;
 
 import java.security.cert.CertificateParsingException;
 
diff --git a/tests/sensor/jni/nativeTestHelper.cpp b/tests/sensor/jni/nativeTestHelper.cpp
index 3c7df9a..69eeba6 100644
--- a/tests/sensor/jni/nativeTestHelper.cpp
+++ b/tests/sensor/jni/nativeTestHelper.cpp
@@ -33,7 +33,11 @@
     jclass exClass;
     const char *className = "java/lang/AssertionError";
     exClass = env->FindClass(className);
-    env->ThrowNew(exClass, msg);
+    jmethodID constructor = env->GetMethodID(exClass, "<init>",
+                                             "(Ljava/lang/String;Ljava/lang/Throwable;)V");
+    jstring msgStr = env->NewStringUTF(msg);
+    jobject exception = env->NewObject(exClass, constructor, msgStr, nullptr);
+    env->Throw(static_cast<jthrowable>(exception));
     free(msg);
 }
 
diff --git a/tests/signature/dex-checker/dex-checker.cpp b/tests/signature/dex-checker/dex-checker.cpp
index 4a80e02..61d9e32 100644
--- a/tests/signature/dex-checker/dex-checker.cpp
+++ b/tests/signature/dex-checker/dex-checker.cpp
@@ -49,7 +49,8 @@
   ScopedUtfChars utf_type(env, type);
   jfieldID fid = env->GetFieldID(klass, utf_name.c_str(), utf_type.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetFieldID could have thrown either NoSuchFieldError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedField(klass, fid, /* static */ false);
@@ -62,7 +63,8 @@
   ScopedUtfChars utf_type(env, type);
   jfieldID fid = env->GetStaticFieldID(klass, utf_name.c_str(), utf_type.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetStaticFieldID could have thrown either NoSuchFieldError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedField(klass, fid, /* static */ true);
@@ -75,7 +77,8 @@
   ScopedUtfChars utf_signature(env, signature);
   jmethodID mid = env->GetMethodID(klass, utf_name.c_str(), utf_signature.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetMethodID could have thrown either NoSuchMethodError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedMethod(klass, mid, /* static */ false);
@@ -88,7 +91,8 @@
   ScopedUtfChars utf_signature(env, signature);
   jmethodID mid = env->GetStaticMethodID(klass, utf_name.c_str(), utf_signature.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetStaticMethodID could have thrown either NoSuchMethodError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedMethod(klass, mid, /* static */ true);
diff --git a/tests/signature/src/android/signature/cts/DexMemberChecker.java b/tests/signature/src/android/signature/cts/DexMemberChecker.java
index 528e868..1efdbad 100644
--- a/tests/signature/src/android/signature/cts/DexMemberChecker.java
+++ b/tests/signature/src/android/signature/cts/DexMemberChecker.java
@@ -16,6 +16,7 @@
 
 package android.signature.cts;
 
+import android.util.Log;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Executable;
 import java.lang.reflect.Field;
@@ -24,6 +25,7 @@
 import java.util.List;
 
 public class DexMemberChecker {
+    public static final String TAG = "DexMemberChecker";
 
     public interface Observer {
         void classAccessible(boolean accessible, DexMember member);
@@ -85,17 +87,39 @@
             observer.fieldAccessibleViaReflection(
                     hasMatchingField_Reflection(klass, field),
                     field);
-            observer.fieldAccessibleViaJni(
-                    hasMatchingField_JNI(klass, field),
-                    field);
+            try {
+                observer.fieldAccessibleViaJni(
+                        hasMatchingField_JNI(klass, field),
+                        field);
+            } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
+                if ((e instanceof NoClassDefFoundError)
+                        && !(e.getCause() instanceof ExceptionInInitializerError)
+                        && !(e.getCause() instanceof UnsatisfiedLinkError)) {
+                    throw e;
+                }
+
+                // Could not initialize the class. Skip JNI test.
+                Log.w(TAG, "JNI failed for " + dexMember.toString(), e);
+            }
         } else if (dexMember instanceof DexMethod) {
             DexMethod method = (DexMethod) dexMember;
             observer.methodAccessibleViaReflection(
                     hasMatchingMethod_Reflection(klass, method),
                     method);
-            observer.methodAccessibleViaJni(
-                    hasMatchingMethod_JNI(klass, method),
-                    method);
+            try {
+                observer.methodAccessibleViaJni(
+                        hasMatchingMethod_JNI(klass, method),
+                        method);
+            } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
+                if ((e instanceof NoClassDefFoundError)
+                        && !(e.getCause() instanceof ExceptionInInitializerError)
+                        && !(e.getCause() instanceof UnsatisfiedLinkError)) {
+                    throw e;
+                }
+
+                // Could not initialize the class. Skip JNI test.
+                Log.w(TAG, "JNI failed for " + dexMember.toString(), e);
+            }
         } else {
             throw new IllegalStateException("Unexpected type of dex member");
         }
@@ -134,10 +158,25 @@
     }
 
     private static boolean hasMatchingField_JNI(Class<?> klass, DexField dexField) {
-        Field ifield = getField_JNI(klass, dexField.getName(), dexField.getDexType());
-        Field sfield = getStaticField_JNI(klass, dexField.getName(), dexField.getDexType());
-        return (ifield != null && ifield.getDeclaringClass() == klass) ||
-               (sfield != null && sfield.getDeclaringClass() == klass);
+        try {
+            Field ifield = getField_JNI(klass, dexField.getName(), dexField.getDexType());
+            if (ifield.getDeclaringClass() == klass) {
+              return true;
+            }
+        } catch (NoSuchFieldError e) {
+            // Not found.
+        }
+
+        try {
+            Field sfield = getStaticField_JNI(klass, dexField.getName(), dexField.getDexType());
+            if (sfield.getDeclaringClass() == klass) {
+              return true;
+            }
+        } catch (NoSuchFieldError e) {
+            // Not found.
+        }
+
+        return false;
     }
 
     private static boolean hasMatchingMethod_Reflection(Class<?> klass, DexMethod dexMethod) {
@@ -163,11 +202,29 @@
     }
 
     private static boolean hasMatchingMethod_JNI(Class<?> klass, DexMethod dexMethod) {
-        Executable imethod = getMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
-        Executable smethod = dexMethod.isConstructor() ? null :
-             getStaticMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
-        return (imethod != null && imethod.getDeclaringClass() == klass) ||
-               (smethod != null && smethod.getDeclaringClass() == klass);
+        try {
+            Executable imethod = getMethod_JNI(
+                klass, dexMethod.getName(), dexMethod.getDexSignature());
+            if (imethod.getDeclaringClass() == klass) {
+                return true;
+            }
+        } catch (NoSuchMethodError e) {
+            // Not found.
+        }
+
+        if (!dexMethod.isConstructor()) {
+            try {
+                Executable smethod =
+                    getStaticMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
+                if (smethod.getDeclaringClass() == klass) {
+                    return true;
+                }
+            } catch (NoSuchMethodError e) {
+                // Not found.
+            }
+        }
+
+        return false;
     }
 
     private static native Field getField_JNI(Class<?> klass, String name, String type);
diff --git a/tests/tests/binder_ndk/Android.mk b/tests/tests/binder_ndk/Android.mk
index 686bc02..4bcf128 100644
--- a/tests/tests/binder_ndk/Android.mk
+++ b/tests/tests/binder_ndk/Android.mk
@@ -30,7 +30,10 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner nativetesthelper
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    ctstestrunner \
+    libbinder_ndk_test_interface-java \
+    nativetesthelper
 
 LOCAL_JNI_SHARED_LIBRARIES := libbinder_ndk_test
 
diff --git a/tests/tests/binder_ndk/AndroidManifest.xml b/tests/tests/binder_ndk/AndroidManifest.xml
index c0efdd8..8876503 100644
--- a/tests/tests/binder_ndk/AndroidManifest.xml
+++ b/tests/tests/binder_ndk/AndroidManifest.xml
@@ -20,6 +20,22 @@
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <application android:debuggable="true">
         <uses-library android:name="android.test.runner" />
+
+        <service
+            android:name="android.binder.cts.JavaService$Local"
+            android:exported="true" />
+        <service
+            android:name="android.binder.cts.NativeService$Local"
+            android:exported="true" />
+
+        <service
+            android:name="android.binder.cts.JavaService$Remote"
+            android:process=":java"
+            android:exported="true" />
+        <service
+            android:name="android.binder.cts.NativeService$Remote"
+            android:process=":native"
+            android:exported="true" />
     </application>
 
     <!-- This is a self-instrumenting test package. -->
@@ -29,4 +45,3 @@
     </instrumentation>
 
 </manifest>
-
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp b/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
index 30b96e7..108f77d 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+aidl_interface {
+    name: "libbinder_ndk_test_interface",
+    srcs: [
+        "test_package/IEmpty.aidl",
+        "test_package/ITest.aidl",
+        "test_package/RegularPolygon.aidl",
+    ],
+}
+
 cc_library_shared {
     name: "libbinder_ndk_test",
 
@@ -21,8 +30,12 @@
     ],
 
     srcs: [
-        "android_binder_cts_ibinder.cpp",
-        "android_binder_cts_parcel.cpp",
+        "android_binder_cts_NativeService.cpp",
+        "test_ibinder.cpp",
+        "test_ibinder_jni.cpp",
+        "test_native_aidl_client.cpp",
+        "test_parcel.cpp",
+        "test_status.cpp",
         "utilities.cpp",
     ],
 
@@ -31,6 +44,9 @@
         "libbinder_ndk",
     ],
     whole_static_libs: ["libnativetesthelper_jni"],
+    static_libs: [
+        "libbinder_ndk_test_interface-ndk",
+    ],
 
     sdk_version: "current",
     stl: "c++_static",
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_NativeService.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_NativeService.cpp
new file mode 100644
index 0000000..ecc04c3
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_NativeService.cpp
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "Cts-NdkBinderTest"
+
+#include <android/binder_ibinder_jni.h>
+
+#include "itest_impl.h"
+
+using ::aidl::test_package::ITest;
+using ::ndk::SharedRefBase;
+using ::ndk::SpAIBinder;
+
+extern "C" JNIEXPORT jobject JNICALL
+Java_android_binder_cts_NativeService_getBinder_1native(JNIEnv* env) {
+  // The ref owns the MyTest, and the binder owns the ref.
+  SpAIBinder binder = SharedRefBase::make<MyTest>()->asBinder();
+
+  // And the Java object owns the binder
+  return AIBinder_toJavaBinder(env, binder.get());
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/itest_impl.h b/tests/tests/binder_ndk/libbinder_ndk_test/itest_impl.h
new file mode 100644
index 0000000..044a2e4
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/itest_impl.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <aidl/test_package/BnTest.h>
+
+#include "utilities.h"
+
+using IEmpty = ::aidl::test_package::IEmpty;
+using RegularPolygon = ::aidl::test_package::RegularPolygon;
+
+class MyTest : public ::aidl::test_package::BnTest,
+               public ThisShouldBeDestroyed {
+ public:
+  ::ndk::ScopedAStatus TestVoidReturn() override {
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus TestOneway() override {
+    // This return code should be ignored since it is oneway.
+    return ::ndk::ScopedAStatus(AStatus_fromStatus(STATUS_UNKNOWN_ERROR));
+  }
+  ::ndk::ScopedAStatus RepeatInt(int32_t in_value,
+                                 int32_t* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatLong(int64_t in_value,
+                                  int64_t* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatFloat(float in_value,
+                                   float* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatDouble(double in_value,
+                                    double* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatBoolean(bool in_value,
+                                     bool* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatChar(char16_t in_value,
+                                  char16_t* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatByte(int8_t in_value,
+                                  int8_t* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatBinder(const ::ndk::SpAIBinder& in_value,
+                                    ::ndk::SpAIBinder* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatInterface(
+      const std::shared_ptr<IEmpty>& in_value,
+      std::shared_ptr<IEmpty>* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatString(const std::string& in_value,
+                                    std::string* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RepeatPolygon(const RegularPolygon& in_value,
+                                     RegularPolygon* _aidl_return) override {
+    *_aidl_return = in_value;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+  ::ndk::ScopedAStatus RenamePolygon(RegularPolygon* value,
+                                     const std::string& newName) override {
+    value->name = newName;
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+};
\ No newline at end of file
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_ibinder.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
similarity index 94%
rename from tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_ibinder.cpp
rename to tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
index f8169b0..aed19eb 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_ibinder.cpp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
@@ -78,6 +78,18 @@
   EXPECT_EQ(data, destroyedPointer);
 }
 
+void onBinderDied(void* /*cookie*/) {}
+
+TEST_F(NdkBinderTest_AIBinder, LinkUnlink) {
+  AIBinder* binder = SampleData::newBinder();
+  AIBinder_DeathRecipient* recipient = AIBinder_DeathRecipient_new(onBinderDied);
+
+  EXPECT_EQ(STATUS_INVALID_OPERATION, AIBinder_linkToDeath(binder, recipient, nullptr));
+
+  AIBinder_DeathRecipient_delete(recipient);
+  AIBinder_decStrong(binder);
+}
+
 TEST_F(NdkBinderTest_AIBinder, DebugRefCount) {
   AIBinder* binder = SampleData::newBinder();
   EXPECT_EQ(1, AIBinder_debugGetRefCount(binder));
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder_jni.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder_jni.cpp
new file mode 100644
index 0000000..228dac3
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder_jni.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "Cts-NdkBinderTest"
+
+#include <android/binder_ibinder.h>
+#include <android/binder_ibinder_jni.h>
+#include <gtest/gtest.h>
+#include <nativetesthelper_jni/utils.h>
+
+#include "utilities.h"
+
+void* NothingClass_onCreate(void* args) { return args; }
+void NothingClass_onDestroy(void* /*userData*/) {}
+binder_status_t NothingClass_onTransact(AIBinder*, transaction_code_t,
+                                        const AParcel*, AParcel*) {
+  return STATUS_UNKNOWN_ERROR;
+}
+
+static AIBinder_Class* kNothingClass =
+    AIBinder_Class_define("nothing", NothingClass_onCreate,
+                          NothingClass_onDestroy, NothingClass_onTransact);
+
+class NdkBinderTest_AIBinder_Jni : public NdkBinderTest {};
+
+TEST_F(NdkBinderTest_AIBinder_Jni, ConvertJni) {
+  JNIEnv* env = GetEnv();
+  ASSERT_NE(nullptr, env);
+
+  AIBinder* binder = AIBinder_new(kNothingClass, nullptr);
+  EXPECT_NE(nullptr, binder);
+
+  jobject object = AIBinder_toJavaBinder(env, binder);
+  EXPECT_NE(nullptr, object);
+
+  AIBinder* fromJavaBinder = AIBinder_fromJavaBinder(env, object);
+  EXPECT_EQ(binder, fromJavaBinder);
+
+  AIBinder_decStrong(binder);
+  AIBinder_decStrong(fromJavaBinder);
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_native_aidl_client.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_native_aidl_client.cpp
new file mode 100644
index 0000000..0638d33
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_native_aidl_client.cpp
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "Cts-NdkBinderTest"
+
+#include <android/binder_ibinder_jni.h>
+#include <gtest/gtest.h>
+#include <aidl/test_package/BnEmpty.h>
+#include <aidl/test_package/BpTest.h>
+#include <aidl/test_package/RegularPolygon.h>
+
+#include "itest_impl.h"
+#include "utilities.h"
+
+using ::aidl::test_package::BpTest;
+using ::aidl::test_package::ITest;
+using ::aidl::test_package::RegularPolygon;
+using ::ndk::ScopedAStatus;
+using ::ndk::SharedRefBase;
+using ::ndk::SpAIBinder;
+
+struct Params {
+  std::shared_ptr<ITest> iface;
+  bool shouldBeRemote;
+};
+
+#define iface GetParam().iface
+#define shouldBeRemote GetParam().shouldBeRemote
+
+class NdkBinderTest_Aidl : public NdkBinderTest,
+                           public ::testing::WithParamInterface<Params> {};
+
+TEST_P(NdkBinderTest_Aidl, GotTest) { ASSERT_NE(nullptr, iface); }
+
+TEST_P(NdkBinderTest_Aidl, Remoteness) {
+  ASSERT_EQ(shouldBeRemote, iface->isRemote());
+}
+
+TEST_P(NdkBinderTest_Aidl, UseBinder) {
+  ASSERT_EQ(STATUS_OK, AIBinder_ping(iface->asBinder().get()));
+}
+
+TEST_P(NdkBinderTest_Aidl, Trivial) {
+  ASSERT_OK(iface->TestVoidReturn());
+  ASSERT_OK(iface->TestOneway());
+}
+
+TEST_P(NdkBinderTest_Aidl, Constants) {
+  ASSERT_EQ(0, ITest::kZero);
+  ASSERT_EQ(1, ITest::kOne);
+  ASSERT_EQ(0xffffffff, ITest::kOnes);
+  ASSERT_EQ(std::string(""), ITest::kEmpty);
+  ASSERT_EQ(std::string("foo"), ITest::kFoo);
+}
+
+TEST_P(NdkBinderTest_Aidl, RepeatPrimitives) {
+  {
+    int32_t out;
+    ASSERT_OK(iface->RepeatInt(3, &out));
+    EXPECT_EQ(3, out);
+  }
+
+  {
+    int64_t out;
+    ASSERT_OK(iface->RepeatLong(3, &out));
+    EXPECT_EQ(3, out);
+  }
+
+  {
+    float out;
+    ASSERT_OK(iface->RepeatFloat(2.0f, &out));
+    EXPECT_EQ(2.0f, out);
+  }
+
+  {
+    double out;
+    ASSERT_OK(iface->RepeatDouble(3.0, &out));
+    EXPECT_EQ(3.0, out);
+  }
+
+  {
+    bool out;
+    ASSERT_OK(iface->RepeatBoolean(true, &out));
+    EXPECT_EQ(true, out);
+  }
+
+  {
+    char16_t out;
+    ASSERT_OK(iface->RepeatChar(L'@', &out));
+    EXPECT_EQ(L'@', out);
+  }
+
+  {
+    int8_t out;
+    ASSERT_OK(iface->RepeatByte(3, &out));
+    EXPECT_EQ(3, out);
+  }
+}
+
+TEST_P(NdkBinderTest_Aidl, RepeatBinder) {
+  SpAIBinder binder = iface->asBinder();
+  SpAIBinder ret;
+
+  ASSERT_OK(iface->RepeatBinder(binder, &ret));
+  EXPECT_EQ(binder.get(), ret.get());
+
+  ASSERT_OK(iface->RepeatBinder(nullptr, &ret));
+  EXPECT_EQ(nullptr, ret.get());
+}
+
+TEST_P(NdkBinderTest_Aidl, RepeatInterface) {
+  class MyEmpty : public ::aidl::test_package::BnEmpty {};
+
+  std::shared_ptr<IEmpty> empty = SharedRefBase::make<MyEmpty>();
+
+  std::shared_ptr<IEmpty> ret;
+  ASSERT_OK(iface->RepeatInterface(empty, &ret));
+  EXPECT_EQ(empty.get(), ret.get());
+
+  ASSERT_OK(iface->RepeatInterface(nullptr, &ret));
+  EXPECT_EQ(nullptr, ret.get());
+}
+
+TEST_P(NdkBinderTest_Aidl, RepeatString) {
+  std::string res;
+
+  EXPECT_OK(iface->RepeatString("", &res));
+  EXPECT_EQ("", res);
+
+  EXPECT_OK(iface->RepeatString("a", &res));
+  EXPECT_EQ("a", res);
+
+  EXPECT_OK(iface->RepeatString("say what?", &res));
+  EXPECT_EQ("say what?", res);
+}
+
+TEST_P(NdkBinderTest_Aidl, ParcelableDefaults) {
+  RegularPolygon polygon;
+
+  EXPECT_EQ("square", polygon.name);
+  EXPECT_EQ(4, polygon.numSides);
+  EXPECT_EQ(1.0f, polygon.sideLength);
+}
+
+TEST_P(NdkBinderTest_Aidl, RepeatPolygon) {
+  RegularPolygon defaultPolygon = {"hexagon", 6, 2.0f};
+  RegularPolygon outputPolygon;
+  ASSERT_OK(iface->RepeatPolygon(defaultPolygon, &outputPolygon));
+  EXPECT_EQ("hexagon", outputPolygon.name);
+  EXPECT_EQ(defaultPolygon.numSides, outputPolygon.numSides);
+  EXPECT_EQ(defaultPolygon.sideLength, outputPolygon.sideLength);
+}
+
+TEST_P(NdkBinderTest_Aidl, InsAndOuts) {
+  RegularPolygon defaultPolygon;
+  ASSERT_OK(iface->RenamePolygon(&defaultPolygon, "Jerry"));
+  EXPECT_EQ("Jerry", defaultPolygon.name);
+}
+
+std::shared_ptr<ITest> getLocalService() {
+  // BpTest -> AIBinder -> test
+  std::shared_ptr<MyTest> test = SharedRefBase::make<MyTest>();
+  return BpTest::associate(test->asBinder());
+}
+
+std::shared_ptr<ITest> getNdkBinderTestJavaService(const std::string& method) {
+  JNIEnv* env = GetEnv();
+  if (env == nullptr) {
+    std::cout << "No environment" << std::endl;
+    return nullptr;
+  }
+
+  jclass cl = env->FindClass("android/binder/cts/NdkBinderTest");
+  if (cl == nullptr) {
+    std::cout << "No class" << std::endl;
+    return nullptr;
+  }
+
+  jmethodID mid =
+      env->GetStaticMethodID(cl, method.c_str(), "()Landroid/os/IBinder;");
+  if (mid == nullptr) {
+    std::cout << "No method id" << std::endl;
+    return nullptr;
+  }
+
+  jobject object = env->CallStaticObjectMethod(cl, mid);
+  if (object == nullptr) {
+    std::cout << "Got null service from Java" << std::endl;
+    return nullptr;
+  }
+
+  SpAIBinder binder = SpAIBinder(AIBinder_fromJavaBinder(env, object));
+
+  return BpTest::associate(binder);
+}
+
+INSTANTIATE_TEST_CASE_P(LocalNative, NdkBinderTest_Aidl,
+                        ::testing::Values(Params{getLocalService(),
+                                                 false /*shouldBeRemote*/}));
+INSTANTIATE_TEST_CASE_P(LocalNativeFromJava, NdkBinderTest_Aidl,
+                        ::testing::Values(Params{getNdkBinderTestJavaService(
+                                                     "getLocalNativeService"),
+                                                 false /*shouldBeRemote*/}));
+INSTANTIATE_TEST_CASE_P(LocalJava, NdkBinderTest_Aidl,
+                        ::testing::Values(Params{
+                            getNdkBinderTestJavaService("getLocalJavaService"),
+                            false /*shouldBeRemote*/}));
+INSTANTIATE_TEST_CASE_P(RemoteNative, NdkBinderTest_Aidl,
+                        ::testing::Values(Params{getNdkBinderTestJavaService(
+                                                     "getRemoteNativeService"),
+                                                 true /*shouldBeRemote*/}));
+INSTANTIATE_TEST_CASE_P(RemoteJava, NdkBinderTest_Aidl,
+                        ::testing::Values(Params{
+                            getNdkBinderTestJavaService("getRemoteJavaService"),
+                            true /*shouldBeRemote*/}));
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/IEmpty.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/IEmpty.aidl
new file mode 100644
index 0000000..50c6cfa
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/IEmpty.aidl
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package test_package;
+
+// What did you expect?
+interface IEmpty {}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/ITest.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/ITest.aidl
new file mode 100644
index 0000000..34f899b
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/ITest.aidl
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package test_package;
+
+import test_package.IEmpty;
+import test_package.RegularPolygon;
+
+// This test interface is used in order to test the all of the things that AIDL can generate which
+// build on top of the NDK.
+//
+// Repeat => return the same value. This is used to keep the clients/tests simple.
+interface ITest {
+    const int kZero = 0;
+    const int kOne = 1;
+    const int kOnes = 0xffffffff;
+    const String kEmpty = "";
+    const String kFoo = "foo";
+
+    void TestVoidReturn();
+    oneway void TestOneway();
+
+    // Sending/receiving primitive types.
+    int RepeatInt(int value);
+    long RepeatLong(long value);
+    float RepeatFloat(float value);
+    double RepeatDouble(double value);
+    boolean RepeatBoolean(boolean value);
+    char RepeatChar(char value);
+    byte RepeatByte(byte value);
+
+    IBinder RepeatBinder(IBinder value);
+    IEmpty RepeatInterface(IEmpty value);
+
+    String RepeatString(String value);
+
+    RegularPolygon RepeatPolygon(in RegularPolygon value);
+
+    // Testing inout
+    void RenamePolygon(inout RegularPolygon value, String newName);
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/RegularPolygon.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/RegularPolygon.aidl
new file mode 100644
index 0000000..d3de6de
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/RegularPolygon.aidl
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package test_package;
+
+parcelable RegularPolygon {
+    String name = "square";
+    int numSides = 4;
+    float sideLength = 1.0f;
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_parcel.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_parcel.cpp
similarity index 61%
rename from tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_parcel.cpp
rename to tests/tests/binder_ndk/libbinder_ndk_test/test_parcel.cpp
index 0b72824..1f779ac 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_parcel.cpp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_parcel.cpp
@@ -26,13 +26,45 @@
 
 class NdkBinderTest_AParcel : public NdkBinderTest {};
 
+template <typename T, typename Enable = void>
+struct WriteFrom {
+  using type = const T;
+};
+template <>
+struct WriteFrom<AStatus*> {
+  // not 'const T' = 'AStatus* const' where T = AStatus*.
+  using type = const AStatus*;
+};
+
+template <typename T>
+bool NdkBinderSenseOfEquality(T a, T b) {
+  return a == b;
+}
+template <>
+bool NdkBinderSenseOfEquality<const AStatus*>(const AStatus* a,
+                                              const AStatus* b) {
+  if (a == b) return true;
+
+  return AStatus_isOk(a) == AStatus_isOk(b) &&
+         AStatus_getExceptionCode(a) == AStatus_getExceptionCode(b) &&
+         AStatus_getServiceSpecificError(a) ==
+             AStatus_getServiceSpecificError(b) &&
+         AStatus_getStatus(a) == AStatus_getStatus(b) &&
+         std::string(AStatus_getMessage(a)) == AStatus_getMessage(b);
+}
+template <>
+bool NdkBinderSenseOfEquality<AStatus*>(AStatus* a, AStatus* b) {
+  return NdkBinderSenseOfEquality<const AStatus*>(a, b);
+}
+
 // These reads and writes an array of possible values all of the same type.
-template <typename T, binder_status_t (*write)(AParcel*, const T),
+template <typename T,
+          binder_status_t (*write)(AParcel*, typename WriteFrom<T>::type),
           binder_status_t (*read)(const AParcel*, T*)>
 void ExpectInOut(std::vector<T> in) {
   AIBinder* binder = SampleData::newBinder(
       [](transaction_code_t, const AParcel* in, AParcel* out) {
-        T readTarget;
+        T readTarget = {};
         EXPECT_OK(read(in, &readTarget));
         EXPECT_OK(write(out, readTarget));
         return STATUS_OK;
@@ -40,23 +72,26 @@
       ExpectLifetimeTransactions(in.size()));
 
   for (const auto& value : in) {
-    EXPECT_OK(SampleData::transact(binder, kCode,
-                                   [&](AParcel* in) {
-                                     EXPECT_OK(write(in, value));
-                                     return STATUS_OK;
-                                   },
-                                   [&](const AParcel* out) {
-                                     T readTarget;
-                                     EXPECT_OK(read(out, &readTarget));
-                                     EXPECT_EQ(value, readTarget);
-                                     return STATUS_OK;
-                                   }));
+    EXPECT_OK(SampleData::transact(
+        binder, kCode,
+        [&](AParcel* in) {
+          EXPECT_OK(write(in, value));
+          return STATUS_OK;
+        },
+        [&](const AParcel* out) {
+          T readTarget = {};
+          EXPECT_OK(read(out, &readTarget));
+          EXPECT_TRUE(NdkBinderSenseOfEquality<T>(value, readTarget))
+              << value << " is not " << readTarget;
+          return STATUS_OK;
+        }));
   }
 
   AIBinder_decStrong(binder);
 }
 
-template <typename T, binder_status_t (*write)(AParcel*, const T),
+template <typename T,
+          binder_status_t (*write)(AParcel*, typename WriteFrom<T>::type),
           binder_status_t (*read)(const AParcel*, T*)>
 void ExpectInOutMinMax() {
   ExpectInOut<T, write, read>(
@@ -107,6 +142,52 @@
   AIBinder_decStrong(binder);
 }
 
+TEST_F(NdkBinderTest_AParcel, StatusesInMustComeOut) {
+  // This does not clean up status objects.
+  ExpectInOut<AStatus*, AParcel_writeStatusHeader, AParcel_readStatusHeader>({
+      AStatus_newOk(),
+      AStatus_fromExceptionCode(EX_ILLEGAL_ARGUMENT),
+      AStatus_fromExceptionCodeWithMessage(EX_ILLEGAL_ARGUMENT,
+                                           "+++++++++[->++++++++<]>.+."),
+      AStatus_fromServiceSpecificError(1776),
+      AStatus_fromServiceSpecificErrorWithMessage(0xBEA, "utiful!"),
+  });
+}
+
+TEST_F(NdkBinderTest_AParcel, LowLevelErrorsHaveNoStatusHeader) {
+  AIBinder* binder =
+      SampleData::newBinder(nullptr, ExpectLifetimeTransactions(0));
+
+  EXPECT_EQ(
+      STATUS_UNKNOWN_ERROR,
+      SampleData::transact(binder, kCode, [&](AParcel* in) {
+        AStatus* status = nullptr;
+
+        status = AStatus_fromExceptionCode(EX_TRANSACTION_FAILED);
+        EXPECT_EQ(STATUS_FAILED_TRANSACTION,
+                  AParcel_writeStatusHeader(in, status));
+        AStatus_delete(status);
+
+        status = AStatus_fromExceptionCodeWithMessage(EX_TRANSACTION_FAILED,
+                                                      "something or other");
+        EXPECT_EQ(STATUS_FAILED_TRANSACTION,
+                  AParcel_writeStatusHeader(in, status));
+        AStatus_delete(status);
+
+        status = AStatus_fromStatus(STATUS_UNKNOWN_ERROR);
+        EXPECT_EQ(STATUS_UNKNOWN_ERROR, AParcel_writeStatusHeader(in, status));
+        AStatus_delete(status);
+
+        status = AStatus_fromStatus(STATUS_BAD_VALUE);
+        EXPECT_EQ(STATUS_BAD_VALUE, AParcel_writeStatusHeader(in, status));
+        AStatus_delete(status);
+
+        return STATUS_UNKNOWN_ERROR;
+      }));
+
+  AIBinder_decStrong(binder);
+}
+
 TEST_F(NdkBinderTest_AParcel, WhatGoesInMustComeOut) {
   ExpectInOut<int32_t, AParcel_writeInt32, AParcel_readInt32>(
       {-7, -1, 0, 1, 45});
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_status.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_status.cpp
new file mode 100644
index 0000000..861a81d
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_status.cpp
@@ -0,0 +1,195 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "Cts-NdkBinderTest"
+
+#include <android/binder_status.h>
+#include <gtest/gtest.h>
+
+#include <set>
+
+// clang-format off
+const static std::set<binder_status_t> kErrorStatuses = {
+  STATUS_UNKNOWN_ERROR,
+  STATUS_NO_MEMORY,
+  STATUS_INVALID_OPERATION,
+  STATUS_BAD_VALUE,
+  STATUS_BAD_TYPE,
+  STATUS_NAME_NOT_FOUND,
+  STATUS_PERMISSION_DENIED,
+  STATUS_NO_INIT,
+  STATUS_ALREADY_EXISTS,
+  STATUS_DEAD_OBJECT,
+  STATUS_FAILED_TRANSACTION,
+  STATUS_BAD_INDEX,
+  STATUS_NOT_ENOUGH_DATA,
+  STATUS_WOULD_BLOCK,
+  STATUS_TIMED_OUT,
+  STATUS_UNKNOWN_TRANSACTION,
+  STATUS_FDS_NOT_ALLOWED,
+  STATUS_UNEXPECTED_NULL
+};
+// Not in the API or above list
+const static std::set<binder_status_t> kUnknownStatuses = { -77, 1, 404, EX_TRANSACTION_FAILED };
+
+const static std::set<binder_exception_t> kErrorExceptions = {
+  EX_SECURITY,
+  EX_BAD_PARCELABLE,
+  EX_ILLEGAL_ARGUMENT,
+  EX_NULL_POINTER,
+  EX_ILLEGAL_STATE,
+  EX_NETWORK_MAIN_THREAD,
+  EX_UNSUPPORTED_OPERATION,
+  EX_SERVICE_SPECIFIC,
+  EX_PARCELABLE,
+  EX_TRANSACTION_FAILED
+};
+// Not in the API or above list
+const static std::set<binder_exception_t> kUnknownExceptions = { -77, 1, 404, STATUS_UNKNOWN_ERROR };
+// clang-format on
+
+// Checks the various attributes expected for an okay status.
+static void checkIsOkay(const AStatus* status) {
+  EXPECT_TRUE(AStatus_isOk(status));
+  EXPECT_EQ(std::string(), AStatus_getMessage(status));
+  EXPECT_EQ(EX_NONE, AStatus_getExceptionCode(status));
+  EXPECT_EQ(0, AStatus_getServiceSpecificError(status));
+  EXPECT_EQ(STATUS_OK, AStatus_getStatus(status));
+}
+static void checkIsErrorException(const AStatus* status,
+                                  binder_exception_t exception,
+                                  const std::string& message) {
+  EXPECT_FALSE(AStatus_isOk(status));
+  EXPECT_EQ(message, AStatus_getMessage(status));
+  EXPECT_EQ(exception, AStatus_getExceptionCode(status));
+  // not a service-specific error, so other errorcodes return the default
+  EXPECT_EQ(0, AStatus_getServiceSpecificError(status));
+  EXPECT_EQ(
+      exception == EX_TRANSACTION_FAILED ? STATUS_FAILED_TRANSACTION : STATUS_OK,
+      AStatus_getStatus(status));
+}
+static void checkIsServiceSpecific(const AStatus* status, int32_t error,
+                                   const std::string& message) {
+  EXPECT_FALSE(AStatus_isOk(status));
+  EXPECT_EQ(message, AStatus_getMessage(status));
+  EXPECT_EQ(EX_SERVICE_SPECIFIC, AStatus_getExceptionCode(status));
+  EXPECT_EQ(error, AStatus_getServiceSpecificError(status));
+  // not a service-specific error, so other errorcodes return the default
+  EXPECT_EQ(STATUS_OK, AStatus_getStatus(status));
+}
+static void checkIsErrorStatus(const AStatus* status, binder_status_t statusT) {
+  EXPECT_FALSE(AStatus_isOk(status));
+  EXPECT_EQ(std::string(), AStatus_getMessage(status));
+  EXPECT_EQ(EX_TRANSACTION_FAILED, AStatus_getExceptionCode(status));
+  EXPECT_EQ(statusT, AStatus_getStatus(status));
+  // not a service-specific error, so other errorcodes return the default
+  EXPECT_EQ(0, AStatus_getServiceSpecificError(status));
+}
+
+TEST(NdkBinderTest_AStatus, OkIsOk) {
+  AStatus* status = AStatus_newOk();
+  checkIsOkay(status);
+  AStatus_delete(status);
+}
+
+TEST(NdkBinderTest_AStatus, NoExceptionIsOkay) {
+  AStatus* status = AStatus_fromExceptionCode(EX_NONE);
+  checkIsOkay(status);
+  AStatus_delete(status);
+}
+
+TEST(NdkBinderTest_AStatus, StatusOkIsOkay) {
+  AStatus* status = AStatus_fromStatus(STATUS_OK);
+  checkIsOkay(status);
+  AStatus_delete(status);
+}
+
+TEST(NdkBinderTest_AStatus, ExceptionIsNotOkay) {
+  for (binder_exception_t exception : kErrorExceptions) {
+    AStatus* status = AStatus_fromExceptionCode(exception);
+    checkIsErrorException(status, exception, "" /*message*/);
+    AStatus_delete(status);
+  }
+}
+
+TEST(NdkBinderTest_AStatus, ExceptionWithMessageIsNotOkay) {
+  const std::string kMessage = "Something arbitrary.";
+  for (binder_exception_t exception : kErrorExceptions) {
+    AStatus* status =
+        AStatus_fromExceptionCodeWithMessage(exception, kMessage.c_str());
+    checkIsErrorException(status, exception, kMessage);
+    AStatus_delete(status);
+  }
+}
+
+TEST(NdkBinderTest_AStatus, ServiceSpecificIsNotOkay) {
+  for (int32_t error : {-404, -1, 0, 1, 23, 918}) {
+    AStatus* status = AStatus_fromServiceSpecificError(error);
+    checkIsServiceSpecific(status, error, "" /*message*/);
+    AStatus_delete(status);
+  }
+}
+
+TEST(NdkBinderTest_AStatus, ServiceSpecificWithMessageIsNotOkay) {
+  const std::string kMessage = "Something also arbitrary.";
+  for (int32_t error : {-404, -1, 0, 1, 23, 918}) {
+    AStatus* status =
+        AStatus_fromServiceSpecificErrorWithMessage(error, kMessage.c_str());
+    checkIsServiceSpecific(status, error, kMessage);
+    AStatus_delete(status);
+  }
+}
+
+TEST(NdkBinderTest_AStatus, StatusIsNotOkay) {
+  for (binder_status_t statusT : kErrorStatuses) {
+    AStatus* status = AStatus_fromStatus(statusT);
+    checkIsErrorStatus(status, statusT);
+    AStatus_delete(status);
+  }
+}
+
+TEST(NdkBinderTest_AStatus, ExceptionsPruned) {
+  for (binder_exception_t exception : kUnknownExceptions) {
+    EXPECT_EQ(kErrorExceptions.find(exception), kErrorExceptions.end())
+        << exception;
+
+    AStatus* status = AStatus_fromExceptionCode(exception);
+    checkIsErrorException(status, EX_TRANSACTION_FAILED, "" /*message*/);
+    AStatus_delete(status);
+  }
+}
+
+TEST(NdkBinderTest_AStatus, ExceptionsPrunedWithMessage) {
+  const std::string kMessage = "Something else arbitrary.";
+  for (binder_exception_t exception : kUnknownExceptions) {
+    EXPECT_EQ(kErrorExceptions.find(exception), kErrorExceptions.end())
+        << exception;
+
+    AStatus* status =
+        AStatus_fromExceptionCodeWithMessage(exception, kMessage.c_str());
+    checkIsErrorException(status, EX_TRANSACTION_FAILED, kMessage);
+    AStatus_delete(status);
+  }
+}
+
+TEST(NdkBinderTest_AStatus, StatusesPruned) {
+  for (binder_status_t statusT : kUnknownStatuses) {
+    EXPECT_EQ(kErrorStatuses.find(statusT), kErrorStatuses.end()) << statusT;
+
+    AStatus* status = AStatus_fromStatus(statusT);
+    checkIsErrorStatus(status, STATUS_UNKNOWN_ERROR);
+    AStatus_delete(status);
+  }
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
index 714d66f..fad9f6f 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
@@ -21,10 +21,11 @@
 #include <android/log.h>
 
 static size_t sNumInstances = 0;
-size_t SampleData::numInstances() { return sNumInstances; }
+size_t ThisShouldBeDestroyed::numInstances() { return sNumInstances; }
+ThisShouldBeDestroyed::ThisShouldBeDestroyed() { sNumInstances++; }
+ThisShouldBeDestroyed::~ThisShouldBeDestroyed() { sNumInstances--; }
 
 void* SampleClassOnCreate(void* args) {
-  sNumInstances++;
   return args;  // SampleData
 }
 
@@ -33,7 +34,6 @@
   if (data->onDestroy != nullptr) {
     data->onDestroy(data);
   }
-  sNumInstances--;
   delete data;
 }
 
@@ -60,3 +60,15 @@
 const AIBinder_Class* SampleData::kAnotherClass =
     AIBinder_Class_define(SampleData::kAnotherDescriptor, SampleClassOnCreate,
                           SampleClassOnDestroy, SampleClassOnTransact);
+
+JNIEnv* GetEnv() {
+  JavaVM* vm = GetJavaVM();
+  if (vm == nullptr) return nullptr;
+
+  JNIEnv* result = nullptr;
+  jint attach = vm->AttachCurrentThread(&result, nullptr);
+
+  EXPECT_EQ(JNI_OK, attach);
+  EXPECT_NE(nullptr, result);
+  return result;
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
index 35fe38f..d254a45 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
@@ -14,15 +14,39 @@
  * limitations under the License.
  */
 
+#pragma once
+
+#include <android/binder_auto_utils.h>
 #include <android/binder_ibinder.h>
 #include <gtest/gtest.h>
+#include <nativetesthelper_jni/utils.h>
 
 #include <functional>
 
 // Helpers for testing
 
-#define EXPECT_OK(THING) EXPECT_EQ(STATUS_OK, (THING))
-#define ASSERT_OK(THING) ASSERT_EQ(STATUS_OK, (THING))
+template <typename T>
+static inline ::testing::AssertionResult isOk(T) = delete;
+
+template <>
+inline ::testing::AssertionResult isOk(::ndk::ScopedAStatus t) {
+  if (AStatus_isOk(t.get())) {
+    return ::testing::AssertionSuccess();
+  } else {
+    return ::testing::AssertionFailure();
+  }
+}
+
+template <>
+inline ::testing::AssertionResult isOk(binder_status_t t) {
+  if (t == STATUS_OK) {
+    return ::testing::AssertionSuccess();
+  }
+  return ::testing::AssertionFailure() << "Status: " << t;
+}
+
+#define EXPECT_OK(THING) EXPECT_TRUE(isOk(THING))
+#define ASSERT_OK(THING) ASSERT_TRUE(isOk(THING))
 
 // placeholder
 constexpr transaction_code_t kCode = +1 + 918;
@@ -47,9 +71,15 @@
   return STATUS_OK;
 }
 
-struct SampleData {
+// There is an assert instances of this class are destroyed in NdkBinderTest
+struct ThisShouldBeDestroyed {
   static size_t numInstances();
 
+  ThisShouldBeDestroyed();
+  virtual ~ThisShouldBeDestroyed();
+};
+
+struct SampleData : ThisShouldBeDestroyed {
   static const char* kDescriptor;
   static const AIBinder_Class* kClass;
 
@@ -118,6 +148,13 @@
 
 class NdkBinderTest : public ::testing::Test {
  public:
-  void SetUp() override { EXPECT_EQ(0, SampleData::numInstances()); }
-  void TearDown() override { EXPECT_EQ(0, SampleData::numInstances()); }
+  void SetUp() override { instances = ThisShouldBeDestroyed::numInstances(); }
+  void TearDown() override {
+    EXPECT_EQ(instances, ThisShouldBeDestroyed::numInstances());
+  }
+
+ private:
+  size_t instances = 0;
 };
+
+JNIEnv* GetEnv();
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/JavaClientTest.java b/tests/tests/binder_ndk/src/android/binder/cts/JavaClientTest.java
new file mode 100644
index 0000000..5838341
--- /dev/null
+++ b/tests/tests/binder_ndk/src/android/binder/cts/JavaClientTest.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.binder.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.os.IBinder;
+import android.os.RemoteException;
+
+import android.support.test.InstrumentationRegistry;
+
+import android.util.Log;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import test_package.IEmpty;
+import test_package.ITest;
+import test_package.RegularPolygon;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.Before;
+import org.junit.Test;
+
+@RunWith(Parameterized.class)
+public class JavaClientTest {
+    private final String TAG = "JavaClientTest";
+
+    private Class mServiceClass;
+    private ITest mInterface;
+
+    public JavaClientTest(Class serviceClass) {
+        mServiceClass = serviceClass;
+    }
+
+    @Parameterized.Parameters( name = "{0}" )
+    public static Collection<Object[]> data() {
+        // For local interfaces, this test will parcel the data locally.
+        // Whenever possible, the desired service should be accessed directly
+        // in order to avoid this additional overhead.
+        return Arrays.asList(new Object[][] {
+                {NativeService.Local.class},
+                {JavaService.Local.class},
+                {NativeService.Remote.class},
+                {JavaService.Remote.class},
+            });
+    }
+
+    @Before
+    public void setUp() {
+        Log.e(TAG, "Setting up");
+
+        SyncTestServiceConnection connection = new SyncTestServiceConnection(
+            InstrumentationRegistry.getTargetContext(), mServiceClass);
+
+        mInterface = connection.get();
+        assertNotEquals(null, mInterface);
+    }
+
+    @Test
+    public void testTrivial() throws RemoteException {
+        mInterface.TestVoidReturn();
+        mInterface.TestOneway();
+    }
+
+    @Test
+    public void testRepeatPrimitives() throws RemoteException {
+        assertEquals(1, mInterface.RepeatInt(1));
+        assertEquals(2, mInterface.RepeatLong(2));
+        assertEquals(1.0f, mInterface.RepeatFloat(1.0f), 0.0f);
+        assertEquals(2.0, mInterface.RepeatDouble(2.0), 0.0);
+        assertEquals(true, mInterface.RepeatBoolean(true));
+        assertEquals('a', mInterface.RepeatChar('a'));
+        assertEquals((byte)3, mInterface.RepeatByte((byte)3));
+    }
+
+    @Test
+    public void testRepeatBinder() throws RemoteException {
+        IBinder binder = mInterface.asBinder();
+
+        assertEquals(binder, mInterface.RepeatBinder(binder));
+
+        assertEquals(null, mInterface.RepeatBinder(null));
+    }
+
+    private static class Empty extends IEmpty.Stub {}
+
+    @Test
+    public void testRepeatInterface() throws RemoteException {
+        IEmpty empty = new Empty();
+
+        assertEquals(empty, mInterface.RepeatInterface(empty));
+
+        assertEquals(null, mInterface.RepeatInterface(null));
+    }
+
+    @Test
+    public void testRepeatString() throws RemoteException {
+        IEmpty empty = new Empty();
+
+        assertEquals("", mInterface.RepeatString(""));
+        assertEquals("a", mInterface.RepeatString("a"));
+        assertEquals("foo", mInterface.RepeatString("foo"));
+    }
+
+    @Test
+    public void testRepeatPolygon() throws RemoteException {
+        RegularPolygon polygon = new RegularPolygon();
+        polygon.name = "hexagon";
+        polygon.numSides = 6;
+        polygon.sideLength = 1.0f;
+
+        RegularPolygon result = mInterface.RepeatPolygon(polygon);
+
+        assertEquals(polygon.name, result.name);
+        assertEquals(polygon.numSides, result.numSides);
+        assertEquals(polygon.sideLength, result.sideLength, 0.0f);
+    }
+
+    @Test
+    public void testInsAndOuts() throws RemoteException {
+        RegularPolygon polygon = new RegularPolygon();
+        mInterface.RenamePolygon(polygon, "Jerry");
+        assertEquals("Jerry", polygon.name);
+    }
+}
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/JavaService.java b/tests/tests/binder_ndk/src/android/binder/cts/JavaService.java
new file mode 100644
index 0000000..5f971f7
--- /dev/null
+++ b/tests/tests/binder_ndk/src/android/binder/cts/JavaService.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.binder.cts;
+
+import android.app.Service;
+
+import android.content.Intent;
+
+import android.os.IBinder;
+
+import android.util.Log;
+
+public class JavaService extends Service {
+    private final String TAG = "JavaService";
+
+    // the configuration of these services is done in AndroidManifest.xml
+    public static class Local extends NativeService {}
+    public static class Remote extends NativeService {}
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        Log.i(TAG, "Binding service");
+        return mBinder;
+    }
+
+    private final TestImpl mBinder = new TestImpl();
+}
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/NativeService.java b/tests/tests/binder_ndk/src/android/binder/cts/NativeService.java
new file mode 100644
index 0000000..6b8b9eb
--- /dev/null
+++ b/tests/tests/binder_ndk/src/android/binder/cts/NativeService.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.binder.cts;
+
+import android.app.Service;
+
+import android.content.Intent;
+
+import android.os.IBinder;
+
+import android.util.Log;
+
+public class NativeService extends Service {
+    private final String TAG = "NativeService";
+
+    // the configuration of these services is done in AndroidManifest.xml
+    public static class Local extends NativeService {}
+    public static class Remote extends NativeService {}
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        Log.i(TAG, "Binding service");
+        return mBinder;
+    }
+
+    private IBinder getBinder() {
+        System.loadLibrary("binder_ndk_test");
+        return getBinder_native();
+    }
+    private native IBinder getBinder_native();
+
+    private final IBinder mBinder = getBinder();
+}
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/NdkBinderTest.java b/tests/tests/binder_ndk/src/android/binder/cts/NdkBinderTest.java
index d2e416f..13c75d2 100644
--- a/tests/tests/binder_ndk/src/android/binder/cts/NdkBinderTest.java
+++ b/tests/tests/binder_ndk/src/android/binder/cts/NdkBinderTest.java
@@ -16,10 +16,41 @@
 
 package android.binder.cts;
 
-import org.junit.runner.RunWith;
+import android.os.IBinder;
+
+import android.support.test.InstrumentationRegistry;
+
 import com.android.gtestrunner.GtestRunner;
 import com.android.gtestrunner.TargetLibrary;
 
+import test_package.ITest;
+
+import org.junit.runner.RunWith;
+
+/**
+ * This test runs gtests for testing libbinder_ndk directly and it also runs client tests for native code.
+ */
 @RunWith(GtestRunner.class)
 @TargetLibrary("binder_ndk_test")
-public class NdkBinderTest {}
+public class NdkBinderTest {
+    static IBinder getLocalNativeService() {
+        return new SyncTestServiceConnection(
+            InstrumentationRegistry.getTargetContext(), NativeService.Local.class)
+        .get().asBinder();
+    }
+    static IBinder getLocalJavaService() {
+        return new SyncTestServiceConnection(
+            InstrumentationRegistry.getTargetContext(), JavaService.Local.class)
+        .get().asBinder();
+    }
+    static IBinder getRemoteNativeService() {
+        return new SyncTestServiceConnection(
+            InstrumentationRegistry.getTargetContext(), NativeService.Remote.class)
+        .get().asBinder();
+    }
+    static IBinder getRemoteJavaService() {
+        return new SyncTestServiceConnection(
+            InstrumentationRegistry.getTargetContext(), JavaService.Remote.class)
+        .get().asBinder();
+    }
+}
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/SyncTestServiceConnection.java b/tests/tests/binder_ndk/src/android/binder/cts/SyncTestServiceConnection.java
new file mode 100644
index 0000000..c9ab544
--- /dev/null
+++ b/tests/tests/binder_ndk/src/android/binder/cts/SyncTestServiceConnection.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.binder.cts;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+
+import android.os.IBinder;
+
+import android.util.Log;
+
+import test_package.ITest;
+
+/**
+ * This enables connecting to a service synchronously easily for testing purposes.
+ */
+public class SyncTestServiceConnection implements ServiceConnection {
+    private final String TAG = "SyncServiceConnection";
+
+    private Class mServiceProviderClass;
+    private Context mContext;
+
+    private ITest mInterface;
+    private boolean mInvalid = false;  // if the service has disconnected abrubtly
+
+    public SyncTestServiceConnection(Context context, Class serviceClass) {
+        mContext = context;
+        mServiceProviderClass = serviceClass;
+    }
+
+    public void onServiceConnected(ComponentName className, IBinder service) {
+        Log.e(TAG, "Service has connected.");
+        synchronized (this) {
+            mInterface = ITest.Stub.asInterface(service);
+            this.notify();
+        }
+    }
+
+    public void onServiceDisconnected(ComponentName className) {
+        Log.e(TAG, "Service has disconnected.");
+        synchronized (this) {
+            mInterface = null;
+            mInvalid = true;
+            this.notify();
+        }
+    }
+
+    ITest get() {
+        synchronized(this) {
+            if (!mInvalid && mInterface == null) {
+                Intent intent = new Intent(mContext, mServiceProviderClass);
+                intent.setAction(ITest.class.getName());
+                mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
+
+                try {
+                    this.wait(5000);
+                } catch (InterruptedException e) {}
+            }
+        }
+        return mInterface;
+    }
+}
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/TestImpl.java b/tests/tests/binder_ndk/src/android/binder/cts/TestImpl.java
new file mode 100644
index 0000000..1aa1c10
--- /dev/null
+++ b/tests/tests/binder_ndk/src/android/binder/cts/TestImpl.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.binder.cts;
+
+import android.os.IBinder;
+
+import test_package.IEmpty;
+import test_package.ITest;
+import test_package.RegularPolygon;
+
+public class TestImpl extends ITest.Stub {
+  @Override
+  public void TestVoidReturn() {}
+
+  @Override
+  public void TestOneway() {}
+
+  @Override
+  public int RepeatInt(int in_value) {
+      return in_value;
+  }
+
+  @Override
+  public long RepeatLong(long in_value) {
+      return in_value;
+  }
+
+  @Override
+  public float RepeatFloat(float in_value) {
+      return in_value;
+  }
+
+  @Override
+  public double RepeatDouble(double in_value) {
+      return in_value;
+  }
+
+  @Override
+  public boolean RepeatBoolean(boolean in_value) {
+      return in_value;
+  }
+
+  @Override
+  public char RepeatChar(char in_value) {
+      return in_value;
+  }
+
+  @Override
+  public byte RepeatByte(byte in_value) {
+      return in_value;
+  }
+
+  @Override
+  public IBinder RepeatBinder(IBinder in_value) {
+      return in_value;
+  }
+
+  @Override
+  public IEmpty RepeatInterface(IEmpty in_value) {
+      return in_value;
+  }
+
+  @Override
+  public String RepeatString(String in_value) {
+      return in_value;
+  }
+
+  @Override
+  public RegularPolygon RepeatPolygon(RegularPolygon in_value) {
+      return in_value;
+  }
+
+  @Override
+  public void RenamePolygon(RegularPolygon value, String name) {
+      value.name = name;
+  }
+}
diff --git a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
index 77d2f82..9d7bc93 100644
--- a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
+++ b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
@@ -178,8 +178,6 @@
             Log.d(TAG, "onError: " + String.valueOf(error));
             mNetworkScanStatus = EVENT_NETWORK_SCAN_ERROR;
             mErrorCode = error;
-            Log.d(TAG, "Stop the network scan");
-            mNetworkScan.stopScan();
             setReady(true);
         }
     }
diff --git a/tests/tests/content/src/android/content/cts/ContextWrapperTest.java b/tests/tests/content/src/android/content/cts/ContextWrapperTest.java
index 408855d..a01e9e0 100644
--- a/tests/tests/content/src/android/content/cts/ContextWrapperTest.java
+++ b/tests/tests/content/src/android/content/cts/ContextWrapperTest.java
@@ -340,7 +340,6 @@
 
         // Test databaseList()
         List<String> list = Arrays.asList(mContextWrapper.databaseList());
-        assertEquals(2, list.size());
         assertTrue("1) database list: " + list, list.contains(DATABASE_NAME1));
         assertTrue("2) database list: " + list, list.contains(DATABASE_NAME2));
 
diff --git a/tests/tests/dpi2/Android.mk b/tests/tests/dpi2/Android.mk
index de8f65a..f366781 100644
--- a/tests/tests/dpi2/Android.mk
+++ b/tests/tests/dpi2/Android.mk
@@ -33,6 +33,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
index 0194044..32cb757 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformCtsActivity.java
@@ -57,18 +57,15 @@
             return;
         }
 
-        if (((WindowManager) getSystemService(Context.WINDOW_SERVICE))
-                        .getDefaultDisplay()
-                        .getRotation()
-                != Surface.ROTATION_0) {
-            throw new RuntimeException("Display not in natural orientation");
+        if (getRotation() == Surface.ROTATION_0) {
+            if (getResources().getConfiguration().orientation
+                    == Configuration.ORIENTATION_LANDSCAPE) {
+                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+            } else {
+                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+            }
         }
 
-        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
-            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
-        } else {
-            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
-        }
         sOrientationRequested = true;
     }
 
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
index 898cc11..7918d58 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
@@ -44,7 +44,7 @@
 /*
  * testVulkanPreTransformSetToMatchCurrentTransform()
  *
- *   For devices rotating 90 degree CW when orientation changes.
+ *   For devices rotating 90 degrees.
  *
  *      Buffer          Screen
  *      ---------       ---------
@@ -53,7 +53,16 @@
  *      | B | Y |       | R | B |
  *      ---------       ---------
  *
- *   For devices rotating 90 degree CCW when orientation changes.
+ *   For devices rotating 180 degrees.
+ *
+ *      Buffer          Screen
+ *      ---------       ---------
+ *      | R | G |       | Y | B |
+ *      ---------       ---------
+ *      | B | Y |       | G | R |
+ *      ---------       ---------
+ *
+ *   For devices rotating 270 degrees.
  *
  *      Buffer          Screen
  *      ---------       ---------
@@ -62,6 +71,15 @@
  *      | B | Y |       | Y | G |
  *      ---------       ---------
  *
+ *   For devices not rotating.
+ *
+ *      Buffer          Screen
+ *      ---------       ---------
+ *      | R | G |       | R | G |
+ *      ---------       ---------
+ *      | B | Y |       | B | Y |
+ *      ---------       ---------
+ *
  * testVulkanPreTransformNotSetToMatchCurrentTransform()
  *
  *      Buffer          Screen
@@ -155,23 +173,26 @@
         int width = bitmap.getWidth();
         int height = bitmap.getHeight();
         int diff = 0;
-        if (!setPreTransform) {
+        if (!setPreTransform || sActivity.getRotation() == Surface.ROTATION_0) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 255, 255, 0);
-        } else if (sActivity.getRotation() == Surface.ROTATION_270) {
-            // For devices rotating 90 degree CCW when orientation changes.
-            diff += pixelDiff(bitmap.getPixel(0, 0), 0, 0, 255);
-            diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 0, 0);
-            diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 255, 0);
-            diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 255, 0);
-        } else {
-            // For devices rotating 90 degree CW when orientation changes.
+        } else if (sActivity.getRotation() == Surface.ROTATION_90) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 0, 255);
+        } else if (sActivity.getRotation() == Surface.ROTATION_180) {
+            diff += pixelDiff(bitmap.getPixel(0, 0), 255, 255, 0);
+            diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 0, 255);
+            diff += pixelDiff(bitmap.getPixel(0, height - 1), 0, 255, 0);
+            diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 255, 0, 0);
+        } else {
+            diff += pixelDiff(bitmap.getPixel(0, 0), 0, 0, 255);
+            diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 0, 0);
+            diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 255, 0);
+            diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 255, 0);
         }
 
         return diff < 10;
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
index 2992eaf..bdbafa3 100644
--- a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -42,8 +42,6 @@
     private final static String SYSTEM_CONFIG_FILE = PUBLIC_CONFIG_DIR + "public.libraries.txt";
     private final static Pattern EXTENSION_CONFIG_FILE_PATTERN = Pattern.compile(
             "public\\.libraries-([A-Za-z0-9\\-_.]+)\\.txt");
-    private final static Pattern EXTENSION_LIBRARY_FILE_PATTERN = Pattern.compile(
-            "lib[^.]+\\.([A-Za-z0-9\\-_.]+)\\.so");
     private final static String VENDOR_CONFIG_FILE = "/vendor/etc/public.libraries.txt";
     private final static String[] PUBLIC_SYSTEM_LIBRARIES = {
         "libaaudio.so",
@@ -128,8 +126,12 @@
                 // libFoo.acme.so
                 List<String> libNames = readPublicLibrariesFile(configFile);
                 for (String lib : libNames) {
-                    Matcher libMatcher = EXTENSION_LIBRARY_FILE_PATTERN.matcher(lib);
-                    if (libMatcher.matches() && libMatcher.group(1).equals(companyName)) {
+                    int space = lib.lastIndexOf(' ');
+                    if (space != -1) {
+                      // Drop 64 or 32 from 'libFoo.so 64'
+                      lib = lib.substring(0, space);
+                    }
+                    if (lib.endsWith("." + companyName + ".so")) {
                         libs.add(lib);
                     } else {
                         return "Library \"" + lib + "\" in " + configFile.toString()
diff --git a/tests/tests/keystore/Android.mk b/tests/tests/keystore/Android.mk
index a7d84d6..9814939 100644
--- a/tests/tests/keystore/Android.mk
+++ b/tests/tests/keystore/Android.mk
@@ -23,7 +23,7 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_JAVA_LIBRARIES := bouncycastle
+LOCAL_JAVA_LIBRARIES := bouncycastle-unbundled
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
         android-support-test \
diff --git a/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java b/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java
index c9d2e2b..eeb16b6 100644
--- a/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/ImportWrappedKeyTest.java
@@ -36,14 +36,14 @@
 import android.security.keystore.WrappedKeyEntry;
 import android.test.AndroidTestCase;
 
-import com.android.org.bouncycastle.asn1.ASN1Encoding;
-import com.android.org.bouncycastle.asn1.DEREncodableVector;
-import com.android.org.bouncycastle.asn1.DERInteger;
-import com.android.org.bouncycastle.asn1.DERNull;
-import com.android.org.bouncycastle.asn1.DEROctetString;
-import com.android.org.bouncycastle.asn1.DERSequence;
-import com.android.org.bouncycastle.asn1.DERSet;
-import com.android.org.bouncycastle.asn1.DERTaggedObject;
+import org.bouncycastle.asn1.ASN1Encoding;
+import org.bouncycastle.asn1.DEREncodableVector;
+import org.bouncycastle.asn1.DERInteger;
+import org.bouncycastle.asn1.DERNull;
+import org.bouncycastle.asn1.DEROctetString;
+import org.bouncycastle.asn1.DERSequence;
+import org.bouncycastle.asn1.DERSet;
+import org.bouncycastle.asn1.DERTaggedObject;
 
 import java.security.Key;
 import java.security.KeyPair;
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index 6b925d4..bb2bb1b 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -62,8 +62,8 @@
 import android.test.AndroidTestCase;
 import android.util.ArraySet;
 
-import com.android.org.bouncycastle.asn1.x500.X500Name;
-import com.android.org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
 
 import java.security.GeneralSecurityException;
 import java.security.InvalidAlgorithmParameterException;
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
index eeadf46..9d75e9c 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
@@ -19,6 +19,7 @@
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyInfo;
 import android.security.keystore.KeyProperties;
+import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 
 import com.google.common.collect.ObjectArrays;
@@ -45,7 +46,8 @@
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
 
-public class KeyGeneratorTest extends TestCase {
+
+public class KeyGeneratorTest extends AndroidTestCase {
     private static final String EXPECTED_PROVIDER_NAME = TestUtils.EXPECTED_PROVIDER_NAME;
 
     static String[] EXPECTED_ALGORITHMS = {
@@ -57,6 +59,11 @@
         "HmacSHA512",
     };
 
+    static String[] EXPECTED_STRONGBOX_ALGORITHMS = {
+        "AES",
+        "HmacSHA256",
+    };
+
     {
         if (TestUtils.supports3DES()) {
             EXPECTED_ALGORITHMS = ObjectArrays.concat(EXPECTED_ALGORITHMS, "DESede");
@@ -179,10 +186,22 @@
 
     public void testInitWithAlgParamsAndNullSecureRandom()
             throws Exception {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testInitWithAlgParamsAndNullSecureRandomHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testInitWithAlgParamsAndNullSecureRandomHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testInitWithAlgParamsAndNullSecureRandomHelper(boolean useStrongbox)
+            throws Exception {
+        for (String algorithm :
+            (useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS)) {
             try {
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
-                keyGenerator.init(getWorkingSpec().build(), (SecureRandom) null);
+                keyGenerator.init(getWorkingSpec()
+                    .setIsStrongBoxBacked(useStrongbox)
+                    .build(),
+                    (SecureRandom) null);
                 // Check that generateKey doesn't fail either, just in case null SecureRandom
                 // causes trouble there.
                 keyGenerator.generateKey();
@@ -208,7 +227,15 @@
     }
 
     public void testDefaultKeySize() throws Exception {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testDefaultKeySize(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testDefaultKeySize(true /* useStrongbox */);
+        }
+    }
+
+    private void testDefaultKeySize(boolean useStrongbox) throws Exception {
+        for (String algorithm :
+            (useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS)) {
             try {
                 int expectedSizeBits = DEFAULT_KEY_SIZES.get(algorithm);
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
@@ -222,6 +249,13 @@
     }
 
     public void testAesKeySupportedSizes() throws Exception {
+        testAesKeySupportedSizesHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testAesKeySupportedSizesHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testAesKeySupportedSizesHelper(boolean useStrongbox) throws Exception {
         KeyGenerator keyGenerator = getKeyGenerator("AES");
         KeyGenParameterSpec.Builder goodSpec = getWorkingSpec();
         CountingSecureRandom rng = new CountingSecureRandom();
@@ -230,10 +264,12 @@
                 rng.resetCounters();
                 KeyGenParameterSpec spec;
                 if (i >= 0) {
-                    spec = TestUtils.buildUpon(goodSpec.setKeySize(i)).build();
+                    spec = TestUtils.buildUpon(
+                        goodSpec.setKeySize(i)).setIsStrongBoxBacked(useStrongbox).build();
                 } else {
                     try {
-                        spec = TestUtils.buildUpon(goodSpec.setKeySize(i)).build();
+                        spec = TestUtils.buildUpon(
+                            goodSpec.setKeySize(i)).setIsStrongBoxBacked(useStrongbox).build();
                         fail();
                     } catch (IllegalArgumentException expected) {
                         continue;
@@ -259,8 +295,16 @@
     }
 
     public void testHmacKeySupportedSizes() throws Exception {
+        testHmacKeySupportedSizesHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testHmacKeySupportedSizesHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testHmacKeySupportedSizesHelper(boolean useStrongbox) throws Exception {
         CountingSecureRandom rng = new CountingSecureRandom();
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             if (!TestUtils.isHmacAlgorithm(algorithm)) {
                 continue;
             }
@@ -271,15 +315,30 @@
                     KeyGenerator keyGenerator = getKeyGenerator(algorithm);
                     KeyGenParameterSpec spec;
                     if (i >= 0) {
-                        spec = getWorkingSpec().setKeySize(i).build();
+                        spec = getWorkingSpec()
+                            .setKeySize(i)
+                            .setIsStrongBoxBacked(useStrongbox)
+                            .build();
                     } else {
                         try {
-                            spec = getWorkingSpec().setKeySize(i).build();
+                            spec = getWorkingSpec()
+                                .setKeySize(i)
+                                .setIsStrongBoxBacked(useStrongbox)
+                                .build();
                             fail();
                         } catch (IllegalArgumentException expected) {
                             continue;
                         }
                     }
+                    // Strongbox must not support keys larger than 512 bits
+                    // TODO: This test currently fails, will be fixed on resolution of b/113525261
+                    if (useStrongbox && i > 512) {
+                        try {
+                            keyGenerator.init(spec, rng);
+                            fail();
+                        } catch (InvalidAlgorithmParameterException expected) {}
+                        assertEquals(0, rng.getOutputSizeBytes());
+                    }
                     if ((i >= 64) && ((i % 8 ) == 0)) {
                         keyGenerator.init(spec, rng);
                         SecretKey key = keyGenerator.generateKey();
@@ -301,7 +360,16 @@
     }
 
     public void testHmacKeyOnlyOneDigestCanBeAuthorized() throws Exception {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testHmacKeyOnlyOneDigestCanBeAuthorizedHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testHmacKeyOnlyOneDigestCanBeAuthorizedHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testHmacKeyOnlyOneDigestCanBeAuthorizedHelper(boolean useStrongbox)
+        throws Exception {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             if (!TestUtils.isHmacAlgorithm(algorithm)) {
                 continue;
             }
@@ -316,21 +384,30 @@
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
 
                 // Digests authorization not specified in algorithm parameters
-                assertFalse(goodSpec.build().isDigestsSpecified());
-                keyGenerator.init(goodSpec.build());
+                assertFalse(goodSpec
+                    .setIsStrongBoxBacked(useStrongbox)
+                    .build()
+                    .isDigestsSpecified());
+                keyGenerator.init(goodSpec.setIsStrongBoxBacked(useStrongbox).build());
                 SecretKey key = keyGenerator.generateKey();
                 TestUtils.assertContentsInAnyOrder(
                         Arrays.asList(TestUtils.getKeyInfo(key).getDigests()), digest);
 
                 // The same digest is specified in algorithm parameters
-                keyGenerator.init(TestUtils.buildUpon(goodSpec).setDigests(digest).build());
+                keyGenerator.init(TestUtils.buildUpon(goodSpec)
+                    .setDigests(digest)
+                    .setIsStrongBoxBacked(useStrongbox)
+                    .build());
                 key = keyGenerator.generateKey();
                 TestUtils.assertContentsInAnyOrder(
                         Arrays.asList(TestUtils.getKeyInfo(key).getDigests()), digest);
 
                 // No digests specified in algorithm parameters
                 try {
-                    keyGenerator.init(TestUtils.buildUpon(goodSpec).setDigests().build());
+                    keyGenerator.init(TestUtils.buildUpon(goodSpec)
+                        .setDigests()
+                        .setIsStrongBoxBacked(useStrongbox)
+                        .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
 
@@ -339,12 +416,14 @@
                 try {
                     keyGenerator.init(TestUtils.buildUpon(goodSpec)
                             .setDigests(anotherDigest)
+                            .setIsStrongBoxBacked(useStrongbox)
                             .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
                 try {
                     keyGenerator.init(TestUtils.buildUpon(goodSpec)
                             .setDigests(digest, anotherDigest)
+                            .setIsStrongBoxBacked(useStrongbox)
                             .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
@@ -355,11 +434,23 @@
     }
 
     public void testInitWithUnknownBlockModeFails() {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testInitWithUnknownBlockModeFailsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testInitWithUnknownBlockModeFailsHelper(true /* useStrongbox */);
+        }
+    }
+
+    public void testInitWithUnknownBlockModeFailsHelper(boolean useStrongbox) {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
                 try {
-                    keyGenerator.init(getWorkingSpec().setBlockModes("weird").build());
+                    keyGenerator.init(
+                        getWorkingSpec()
+                        .setBlockModes("weird")
+                        .setIsStrongBoxBacked(useStrongbox)
+                        .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
             } catch (Throwable e) {
@@ -369,11 +460,23 @@
     }
 
     public void testInitWithUnknownEncryptionPaddingFails() {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testInitWithUnknownEncryptionPaddingFailsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testInitWithUnknownEncryptionPaddingFailsHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testInitWithUnknownEncryptionPaddingFailsHelper(boolean useStrongbox) {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
                 try {
-                    keyGenerator.init(getWorkingSpec().setEncryptionPaddings("weird").build());
+                    keyGenerator.init(
+                        getWorkingSpec()
+                        .setEncryptionPaddings("weird")
+                        .setIsStrongBoxBacked(useStrongbox)
+                        .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
             } catch (Throwable e) {
@@ -383,12 +486,21 @@
     }
 
     public void testInitWithSignaturePaddingFails() {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testInitWithSignaturePaddingFailsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testInitWithSignaturePaddingFailsHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testInitWithSignaturePaddingFailsHelper(boolean useStrongbox) {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
                 try {
                     keyGenerator.init(getWorkingSpec()
                             .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
+                            .setIsStrongBoxBacked(useStrongbox)
                             .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
@@ -399,7 +511,15 @@
     }
 
     public void testInitWithUnknownDigestFails() {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testInitWithUnknownDigestFailsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testInitWithUnknownDigestFailsHelper(true /* useStrongbox */);
+        }
+    }
+
+    public void testInitWithUnknownDigestFailsHelper(boolean useStrongbox) {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
                 try {
@@ -411,7 +531,11 @@
                     } else {
                         digests = new String[] {"weird"};
                     }
-                    keyGenerator.init(getWorkingSpec().setDigests(digests).build());
+                    keyGenerator.init(
+                        getWorkingSpec()
+                        .setDigests(digests)
+                        .setIsStrongBoxBacked(useStrongbox)
+                        .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
             } catch (Throwable e) {
@@ -421,7 +545,17 @@
     }
 
     public void testInitWithKeyAlgorithmDigestMissingFromAuthorizedDigestFails() {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testInitWithKeyAlgorithmDigestMissingFromAuthorizedDigestFailsHelper(
+            false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testInitWithKeyAlgorithmDigestMissingFromAuthorizedDigestFailsHelper(
+                true /* useStrongbox */);
+        }
+    }
+
+    private void testInitWithKeyAlgorithmDigestMissingFromAuthorizedDigestFailsHelper(boolean useStrongbox) {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             if (!TestUtils.isHmacAlgorithm(algorithm)) {
                 continue;
             }
@@ -433,13 +567,21 @@
                     String digest = TestUtils.getHmacAlgorithmDigest(algorithm);
                     String anotherDigest = KeyProperties.DIGEST_SHA256.equalsIgnoreCase(digest)
                             ? KeyProperties.DIGEST_SHA512 : KeyProperties.DIGEST_SHA256;
-                    keyGenerator.init(getWorkingSpec().setDigests(anotherDigest).build());
+                    keyGenerator.init(
+                        getWorkingSpec()
+                        .setDigests(anotherDigest)
+                        .setIsStrongBoxBacked(useStrongbox)
+                        .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
 
                 // Authorized for empty set of digests
                 try {
-                    keyGenerator.init(getWorkingSpec().setDigests().build());
+                    keyGenerator.init(
+                        getWorkingSpec()
+                        .setDigests()
+                        .setIsStrongBoxBacked(useStrongbox)
+                        .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
             } catch (Throwable e) {
@@ -449,13 +591,23 @@
     }
 
     public void testInitRandomizedEncryptionRequiredButViolatedFails() throws Exception {
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        testInitRandomizedEncryptionRequiredButViolatedFailsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testInitRandomizedEncryptionRequiredButViolatedFailsHelper(true /* useStrongbox */);
+        }
+    }
+
+    public void testInitRandomizedEncryptionRequiredButViolatedFailsHelper(boolean useStrongbox)
+        throws Exception {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
                 KeyGenerator keyGenerator = getKeyGenerator(algorithm);
                 try {
                     keyGenerator.init(getWorkingSpec(
                             KeyProperties.PURPOSE_ENCRYPT)
                             .setBlockModes(KeyProperties.BLOCK_MODE_ECB)
+                            .setIsStrongBoxBacked(useStrongbox)
                             .build());
                     fail();
                 } catch (InvalidAlgorithmParameterException expected) {}
@@ -466,12 +618,21 @@
     }
 
     public void testGenerateHonorsRequestedAuthorizations() throws Exception {
+        testGenerateHonorsRequestedAuthorizationsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerateHonorsRequestedAuthorizationsHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerateHonorsRequestedAuthorizationsHelper(boolean useStrongbox)
+        throws Exception {
         Date keyValidityStart = new Date(System.currentTimeMillis() - TestUtils.DAY_IN_MILLIS);
         Date keyValidityForOriginationEnd =
                 new Date(System.currentTimeMillis() + TestUtils.DAY_IN_MILLIS);
         Date keyValidityForConsumptionEnd =
                 new Date(System.currentTimeMillis() + 3 * TestUtils.DAY_IN_MILLIS);
-        for (String algorithm : EXPECTED_ALGORITHMS) {
+        for (String algorithm :
+            useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS) {
             try {
                 String[] blockModes =
                         new String[] {KeyProperties.BLOCK_MODE_GCM, KeyProperties.BLOCK_MODE_CBC};
@@ -497,6 +658,7 @@
                         .setKeyValidityStart(keyValidityStart)
                         .setKeyValidityForOriginationEnd(keyValidityForOriginationEnd)
                         .setKeyValidityForConsumptionEnd(keyValidityForConsumptionEnd)
+                        .setIsStrongBoxBacked(useStrongbox)
                         .build());
                 SecretKey key = keyGenerator.generateKey();
                 assertEquals(algorithm, key.getAlgorithm());
diff --git a/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp b/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp
index c098f5f..bf7aacc 100644
--- a/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp
+++ b/tests/tests/media/libimagereaderjni/AImageReaderCts.cpp
@@ -348,7 +348,7 @@
             // Verity that outFenceFd's value will be changed by
             // AImageReader_acquireNextImageAsync.
             ret = AImageReader_acquireNextImageAsync(reader, &outImage, &outFenceFd);
-            if (ret != AMEDIA_OK || outImage == nullptr || outFenceFd != kDummyFenceFd) {
+            if (ret != AMEDIA_OK || outImage == nullptr || outFenceFd == 0) {
                 ALOGE("Failed to acquire image, ret=%d, outIamge=%p, outFenceFd=%d.", ret, outImage,
                       outFenceFd);
                 return;
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackTest.java b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
index 2baf410..47a3a31 100644
--- a/tests/tests/media/src/android/media/cts/AudioTrackTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
@@ -1483,7 +1483,7 @@
         final double TEST_SWEEP = 100;
         final int TEST_LOOPS = 1;
         final double TEST_FREQUENCY = 400;
-        final long WAIT_TIME_MS = 50; // compensate for cold start when run in isolation.
+        final long WAIT_TIME_MS = 150; // compensate for cold start when run in isolation.
         final double TEST_LOOP_DURATION = 0.25;
 
         playOnceStaticData(TEST_NAME, TEST_MODE, TEST_STREAM_TYPE, TEST_SWEEP,
diff --git a/tests/tests/media/src/android/media/cts/DecoderConformanceTest.java b/tests/tests/media/src/android/media/cts/DecoderConformanceTest.java
index f1f16a8..58293f9 100644
--- a/tests/tests/media/src/android/media/cts/DecoderConformanceTest.java
+++ b/tests/tests/media/src/android/media/cts/DecoderConformanceTest.java
@@ -138,6 +138,7 @@
         mExtractor.setDataSource(testFd.getFileDescriptor(), testFd.getStartOffset(), testFd.getLength());
         mExtractor.selectTrack(0);
 
+        mDecoder = MediaCodec.createByCodecName(decoderName);
         MediaCodecInfo codecInfo = mDecoder.getCodecInfo();
         MediaCodecInfo.CodecCapabilities caps = codecInfo.getCapabilitiesForType(mime);
         if (!caps.isFormatSupported(mExtractor.getTrackFormat(0))) {
@@ -153,7 +154,6 @@
         }
 
         try {
-            mDecoder = MediaCodec.createByCodecName(decoderName);
             if (MediaUtils.verifyDecoder(mDecoder, mExtractor, frameMD5Sums)) {
                 return Status.PASS;
             }
diff --git a/tests/tests/media/src/android/media/cts/EqualizerTest.java b/tests/tests/media/src/android/media/cts/EqualizerTest.java
index a8bd98a..7c405a5 100644
--- a/tests/tests/media/src/android/media/cts/EqualizerTest.java
+++ b/tests/tests/media/src/android/media/cts/EqualizerTest.java
@@ -27,7 +27,7 @@
 public class EqualizerTest extends PostProcTestBase {
 
     private String TAG = "EqualizerTest";
-    private final static int MIN_NUMBER_OF_BANDS = 4;
+    private final static int MIN_NUMBER_OF_BANDS = 2;
     private final static int MAX_LEVEL_RANGE_LOW = 0;             // 0dB
     private final static int MIN_LEVEL_RANGE_HIGH = 0;            // 0dB
     private final static int TEST_FREQUENCY_MILLIHERTZ = 1000000; // 1kHz
diff --git a/tests/tests/media/src/android/media/cts/MediaExtractorTest.java b/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
index 2718c3b..7dc9130 100644
--- a/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
@@ -126,6 +126,7 @@
     }
 
     public void testGetAudioPresentations() throws Exception {
+        TestMediaDataSource dataSource = setDataSource(R.raw.testvideo);
         List<AudioPresentation> presentations = mExtractor.getAudioPresentations(0 /*trackIndex*/);
         assertNotNull(presentations);
         assertTrue(presentations.isEmpty());
diff --git a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
index 36f1b8a..9578468 100644
--- a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
+++ b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
@@ -998,6 +998,7 @@
                     internal_format = GL_DEPTH_STENCIL_OES;
                     format = GL_DEPTH_STENCIL;
                     type = GL_UNSIGNED_INT_24_8;
+                    break;
                 default:
                     FAIL() << "Unrecognized GL format"; break;
             }
diff --git a/tests/tests/net/Android.mk b/tests/tests/net/Android.mk
index 1430071..6967adb 100644
--- a/tests/tests/net/Android.mk
+++ b/tests/tests/net/Android.mk
@@ -26,7 +26,6 @@
 
 LOCAL_JAVA_LIBRARIES := \
     voip-common \
-    conscrypt \
     org.apache.http.legacy \
     android.test.base.stubs \
 
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index 441bee3..6e4f34e 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -107,17 +107,6 @@
             "Host: " + TEST_HOST + "\r\n" +
             "Connection: keep-alive\r\n\r\n";
 
-    // Base path for IPv6 sysctls
-    private static final String IPV6_SYSCTL_DIR = "/proc/sys/net/ipv6/conf";
-
-    // Expected values for MIN|MAX_PLEN.
-    private static final int IPV6_WIFI_ACCEPT_RA_RT_INFO_MIN_PLEN = 48;
-    private static final int IPV6_WIFI_ACCEPT_RA_RT_INFO_MAX_PLEN = 64;
-
-    // Expected values for RFC 7559 router soliciations.
-    // Maximum number of router solicitations to send. -1 means no limit.
-    private static final int IPV6_WIFI_ROUTER_SOLICITATIONS = -1;
-
     // Action sent to ConnectivityActionReceiver when a network callback is sent via PendingIntent.
     private static final String NETWORK_CALLBACK_ACTION =
             "ConnectivityManagerTest.NetworkCallbackAction";
@@ -908,60 +897,6 @@
         } catch (SecurityException expected) {}
     }
 
-    private Scanner makeWifiSysctlScanner(String key) throws FileNotFoundException {
-        Network network = ensureWifiConnected();
-        String iface = mCm.getLinkProperties(network).getInterfaceName();
-        String path = IPV6_SYSCTL_DIR + "/" + iface + "/" + key;
-        return new Scanner(new File(path));
-    }
-
-    /** Verify that accept_ra_rt_info_min_plen exists and is set to the expected value */
-    public void testAcceptRaRtInfoMinPlen() throws Exception {
-        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) {
-            Log.i(TAG, "testConnectivityChanged_manifestRequestOnlyPreN_shouldReceiveIntent cannot execute unless device supports WiFi");
-            return;
-        }
-        Scanner s = makeWifiSysctlScanner("accept_ra_rt_info_min_plen");
-        assertEquals(IPV6_WIFI_ACCEPT_RA_RT_INFO_MIN_PLEN, s.nextInt());
-    }
-
-    /** Verify that accept_ra_rt_info_max_plen exists and is set to the expected value */
-    public void testAcceptRaRtInfoMaxPlen() throws Exception {
-        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) {
-            Log.i(TAG, "testConnectivityChanged_manifestRequestOnlyPreN_shouldReceiveIntent cannot execute unless device supports WiFi");
-            return;
-        }
-        Scanner s = makeWifiSysctlScanner("accept_ra_rt_info_max_plen");
-        assertEquals(IPV6_WIFI_ACCEPT_RA_RT_INFO_MAX_PLEN, s.nextInt());
-    }
-
-    /** Verify that router_solicitations exists and is set to the expected value */
-    public void testRouterSolicitations() throws Exception {
-        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) {
-            Log.i(TAG, "testConnectivityChanged_manifestRequestOnlyPreN_shouldReceiveIntent cannot execute unless device supports WiFi");
-            return;
-        }
-        Scanner s = makeWifiSysctlScanner("router_solicitations");
-        assertEquals(IPV6_WIFI_ROUTER_SOLICITATIONS, s.nextInt());
-    }
-
-    /** Verify that router_solicitation_max_interval exists and is in an acceptable interval */
-    public void testRouterSolicitationMaxInterval() throws Exception {
-        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) {
-            Log.i(TAG, "testConnectivityChanged_manifestRequestOnlyPreN_shouldReceiveIntent cannot execute unless device supports WiFi");
-            return;
-        }
-        Scanner s = makeWifiSysctlScanner("router_solicitation_max_interval");
-        int interval = s.nextInt();
-        // Verify we're in the interval [15 minutes, 60 minutes]. Lower values may adversely
-        // impact battery life and higher values can decrease the probability of detecting
-        // network changes.
-        final int lowerBoundSec = 15 * 60;
-        final int upperBoundSec = 60 * 60;
-        assertTrue(lowerBoundSec <= interval);
-        assertTrue(interval <= upperBoundSec);
-    }
-
     // Returns "true", "false" or "none"
     private String getWifiMeteredStatus(String ssid) throws Exception {
         // Interestingly giving the SSID as an argument to list wifi-networks
diff --git a/tests/tests/net/src/android/net/cts/IpSecSysctlTest.java b/tests/tests/net/src/android/net/cts/IpSecSysctlTest.java
deleted file mode 100644
index b362282c..0000000
--- a/tests/tests/net/src/android/net/cts/IpSecSysctlTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net.cts;
-
-import android.system.ErrnoException;
-import android.system.Os;
-import android.system.OsConstants;
-import android.system.StructStat;
-import android.test.AndroidTestCase;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.IOException;
-
-/**
- * Tests for multinetwork sysctl functionality.
- */
-public class IpSecSysctlTest extends SysctlBaseTest {
-
-    // SPI expiration sysctls. Must be present and set greater than 1h.
-    private static final String SPI_TIMEOUT_SYSCTL = "/proc/sys/net/core/xfrm_acq_expires";
-    private static final int MIN_ACQ_EXPIRES = 3600;
-
-    /**
-     * Checks that SPI default timeouts are overridden, and set to a reasonable length of time
-     */
-    public void testProcFiles() throws ErrnoException, IOException, NumberFormatException {
-        int value = getIntValue(SPI_TIMEOUT_SYSCTL);
-        assertAtLeast(SPI_TIMEOUT_SYSCTL, value, MIN_ACQ_EXPIRES);
-    }
-}
diff --git a/tests/tests/net/src/android/net/cts/MultinetworkSysctlTest.java b/tests/tests/net/src/android/net/cts/MultinetworkSysctlTest.java
deleted file mode 100644
index 1d0c111..0000000
--- a/tests/tests/net/src/android/net/cts/MultinetworkSysctlTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net.cts;
-
-import android.system.ErrnoException;
-import android.system.Os;
-import android.system.OsConstants;
-import android.system.StructStat;
-import android.test.AndroidTestCase;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.IOException;
-
-/**
- * Tests for multinetwork sysctl functionality.
- */
-public class MultinetworkSysctlTest extends SysctlBaseTest {
-
-    // Global sysctls. Must be present and set to 1.
-    private static final String[] GLOBAL_SYSCTLS = {
-        "/proc/sys/net/ipv4/fwmark_reflect",
-        "/proc/sys/net/ipv6/fwmark_reflect",
-        "/proc/sys/net/ipv4/tcp_fwmark_accept",
-    };
-
-    // Per-interface IPv6 autoconf sysctls.
-    private static final String IPV6_SYSCTL_DIR = "/proc/sys/net/ipv6/conf";
-    private static final String AUTOCONF_SYSCTL = "accept_ra_rt_table";
-
-    /**
-     * Checks that the sysctls for multinetwork kernel features are present and
-     * enabled. The necessary kernel commits are:
-     *
-     * Mainline Linux:
-     *   e110861 net: add a sysctl to reflect the fwmark on replies
-     *   1b3c61d net: Use fwmark reflection in PMTU discovery.
-     *   84f39b0 net: support marking accepting TCP sockets
-     *
-     * Common Android tree (e.g., 3.10):
-     *   a03f539 net: ipv6: autoconf routes into per-device tables
-     */
-     public void testProcFiles() throws ErrnoException, IOException, NumberFormatException {
-         for (String sysctl : GLOBAL_SYSCTLS) {
-             int value = getIntValue(sysctl);
-             assertEquals(sysctl, 1, value);
-         }
-
-         File[] interfaceDirs = new File(IPV6_SYSCTL_DIR).listFiles();
-         for (File interfaceDir : interfaceDirs) {
-             if (interfaceDir.getName().equals("all") || interfaceDir.getName().equals("lo")) {
-                 continue;
-             }
-             String sysctl = new File(interfaceDir, AUTOCONF_SYSCTL).getAbsolutePath();
-             int value = getIntValue(sysctl);
-             assertLess(sysctl, value, 0);
-         }
-     }
-}
diff --git a/tests/tests/net/src/android/net/cts/SysctlBaseTest.java b/tests/tests/net/src/android/net/cts/SysctlBaseTest.java
deleted file mode 100644
index a5966d4..0000000
--- a/tests/tests/net/src/android/net/cts/SysctlBaseTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net.cts;
-
-import android.system.ErrnoException;
-import android.system.Os;
-import android.system.OsConstants;
-import android.system.StructStat;
-import android.test.AndroidTestCase;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.IOException;
-
-/**
- * Tests for multinetwork sysctl functionality.
- */
-public class SysctlBaseTest extends AndroidTestCase {
-
-    // Expected mode, UID, and GID of sysctl files.
-    private static final int SYSCTL_MODE = 0100644;
-    private static final int SYSCTL_UID = 0;
-    private static final int SYSCTL_GID = 0;
-
-    private void checkSysctlPermissions(String fileName) throws ErrnoException {
-        StructStat stat = Os.stat(fileName);
-        assertEquals("mode of " + fileName + ":", SYSCTL_MODE, stat.st_mode);
-        assertEquals("UID of " + fileName + ":", SYSCTL_UID, stat.st_uid);
-        assertEquals("GID of " + fileName + ":", SYSCTL_GID, stat.st_gid);
-    }
-
-    protected void assertLess(String sysctl, int a, int b) {
-        assertTrue("value of " + sysctl + ": expected < " + b + " but was: " + a, a < b);
-    }
-
-    protected void assertAtLeast(String sysctl, int a, int b) {
-        assertTrue("value of " + sysctl + ": expected >= " + b + " but was: " + a, a >= b);
-    }
-
-    private String readFile(String fileName) throws ErrnoException, IOException {
-        byte[] buf = new byte[1024];
-        FileDescriptor fd = Os.open(fileName, 0, OsConstants.O_RDONLY);
-        int bytesRead = Os.read(fd, buf, 0, buf.length);
-        assertLess("length of " + fileName + ":", bytesRead, buf.length);
-        return new String(buf);
-    }
-
-    /*
-     * Checks permissions and retrieves the sysctl's value. Retrieval of value should always use
-     * this method
-     */
-    protected int getIntValue(String filename) throws ErrnoException, IOException {
-        checkSysctlPermissions(filename);
-        return Integer.parseInt(readFile(filename).trim());
-    }
-}
diff --git a/tests/tests/os/Android.mk b/tests/tests/os/Android.mk
index 8f12610..5ab51d8 100644
--- a/tests/tests/os/Android.mk
+++ b/tests/tests/os/Android.mk
@@ -57,10 +57,6 @@
 LOCAL_AAPT_FLAGS := -0 .policy
 
 LOCAL_USE_AAPT2 := true
-# Disable AAPT2 manifest checks to fix:
-# cts/tests/tests/os/AndroidManifest.xml:25: error: unexpected element <meta-data> found in <manifest><permission>.
-# TODO(b/79755007): Remove when AAPT2 recognizes the manifest elements.
-LOCAL_AAPT_FLAGS += --warn-manifest-validation
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/os/src/android/os/cts/BuildTest.java b/tests/tests/os/src/android/os/cts/BuildTest.java
index 7336fc0..b371ad1 100644
--- a/tests/tests/os/src/android/os/cts/BuildTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildTest.java
@@ -43,7 +43,7 @@
     /** Tests that check the values of {@link Build#CPU_ABI} and {@link Build#CPU_ABI2}. */
     public void testCpuAbi() throws Exception {
         runTestCpuAbiCommon();
-        if (VMRuntime.getRuntime().is64Bit()) {
+        if (android.os.Process.is64Bit()) {
             runTestCpuAbi64();
         } else {
             runTestCpuAbi32();
diff --git a/tests/tests/print/printTestUtilLib/Android.mk b/tests/tests/permission/sdk28/Android.mk
similarity index 66%
rename from tests/tests/print/printTestUtilLib/Android.mk
rename to tests/tests/permission/sdk28/Android.mk
index 358861b..f968393 100644
--- a/tests/tests/print/printTestUtilLib/Android.mk
+++ b/tests/tests/permission/sdk28/Android.mk
@@ -1,4 +1,5 @@
-# Copyright (C) 2017 The Android Open Source Project
+#
+# Copyright (C) 2018 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -11,19 +12,24 @@
 # WITHOUT 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 := CtsPermissionTestCasesSdk28
+
 LOCAL_MODULE_TAGS := tests
 
+LOCAL_SDK_VERSION := 28
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_MODULE := print-test-util-lib
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
 
-LOCAL_STATIC_JAVA_LIBRARIES := mockito-target-minus-junit4 ctstestrunner ub-uiautomator compatibility-device-util android-support-test
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_SDK_VERSION := test_current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
\ No newline at end of file
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/permission/sdk28/AndroidManifest.xml b/tests/tests/permission/sdk28/AndroidManifest.xml
new file mode 100644
index 0000000..76b8754
--- /dev/null
+++ b/tests/tests/permission/sdk28/AndroidManifest.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.permission.cts.sdk28">
+
+    <uses-sdk android:minSdkVersion="3"
+        android:targetSdkVersion="28"
+        android:maxSdkVersion="28" />
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+        <activity android:name="android.permission.cts.PermissionStubActivity"
+                  android:label="PermissionStubActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"/>
+            </intent-filter>
+        </activity>
+    </application>
+
+    <!--
+        The CTS stubs package cannot be used as the target application here,
+        since that requires many permissions to be set. Instead, specify this
+        package itself as the target and include any stub activities needed.
+
+        This test package uses the default InstrumentationTestRunner, because
+        the InstrumentationCtsTestRunner is only available in the stubs
+        package. That runner cannot be added to this package either, since it
+        relies on hidden APIs.
+    -->
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.permission.cts.sdk28"
+                     android:label="CTS tests of legacy android permissions as of API 28">
+        <meta-data android:name="listener"
+            android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>
+
+</manifest>
+
diff --git a/tests/tests/permission/sdk28/AndroidTest.xml b/tests/tests/permission/sdk28/AndroidTest.xml
new file mode 100644
index 0000000..a4775d6
--- /dev/null
+++ b/tests/tests/permission/sdk28/AndroidTest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for CTS Permission test cases for TargetSdk 28">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsPermissionTestCasesSdk28.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.permission.cts.sdk28" />
+        <option name="runtime-hint" value="1m" />
+    </test>
+</configuration>
diff --git a/tests/tests/permission/sdk28/res/values/strings.xml b/tests/tests/permission/sdk28/res/values/strings.xml
new file mode 100644
index 0000000..9cc70f9
--- /dev/null
+++ b/tests/tests/permission/sdk28/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="sdk28">SDK Level 28</string>
+</resources>
diff --git a/tests/tests/permission/sdk28/src/android/permission/cts/sdk28/RequestLocation.java b/tests/tests/permission/sdk28/src/android/permission/cts/sdk28/RequestLocation.java
new file mode 100644
index 0000000..3e96806
--- /dev/null
+++ b/tests/tests/permission/sdk28/src/android/permission/cts/sdk28/RequestLocation.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.permission.cts.sdk28;
+
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNotNull;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+import android.telephony.TelephonyManager;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class RequestLocation {
+
+    private TelephonyManager mTelephonyManager;
+    private boolean mHasTelephony;
+
+    @Before
+    public void setUp() throws Exception {
+        mHasTelephony = getContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_TELEPHONY);
+        mTelephonyManager = (TelephonyManager) getContext().getSystemService(
+                Context.TELEPHONY_SERVICE);
+        assertNotNull(mTelephonyManager);
+    }
+
+    /**
+     * Verify that a SecurityException is thrown when an app targeting SDK 28
+     * lacks the coarse location permission.
+     */
+    @Test
+    public void testGetNeighboringCellInfo() {
+        if (!mHasTelephony) return;
+        try {
+            mTelephonyManager.getNeighboringCellInfo();
+            fail("No Exception thrown for getNeighboringCellInfo without permission!");
+        } catch (SecurityException expected) {
+        }
+    }
+
+    private static Context getContext() {
+        return InstrumentationRegistry.getContext();
+    }
+}
diff --git a/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java
index 8fd4a59..47055ec 100644
--- a/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java
@@ -110,13 +110,6 @@
         PhoneStateListener phoneStateListener = new PhoneStateListener();
 
         try {
-            telephonyManager.getNeighboringCellInfo();
-            fail("TelephonyManager.getNeighbouringCellInfo did not throw SecurityException as expected");
-        } catch (SecurityException e) {
-            // expected
-        }
-
-        try {
             telephonyManager.getAllCellInfo();
             fail("TelephonyManager.getAllCellInfo did not throw SecurityException as expected");
         } catch (SecurityException e) {
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index b20bd67..040bdbd 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -138,7 +138,6 @@
     <protected-broadcast android:name="android.bluetooth.device.action.MAS_INSTANCE" />
     <protected-broadcast android:name="android.bluetooth.device.action.ALIAS_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.device.action.FOUND" />
-    <protected-broadcast android:name="android.bluetooth.device.action.DISAPPEARED" />
     <protected-broadcast android:name="android.bluetooth.device.action.CLASS_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.device.action.ACL_CONNECTED" />
     <protected-broadcast android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
diff --git a/tests/tests/print/printTestUtilLib/Android.bp b/tests/tests/print/printTestUtilLib/Android.bp
new file mode 100644
index 0000000..b661a91
--- /dev/null
+++ b/tests/tests/print/printTestUtilLib/Android.bp
@@ -0,0 +1,29 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "print-test-util-lib",
+
+    srcs: ["src/**/*.java"],
+
+    static_libs: [
+        "mockito-target-minus-junit4",
+        "ctstestrunner",
+        "ub-uiautomator",
+        "compatibility-device-util",
+        "android-support-test",
+    ],
+
+    sdk_version: "test_current",
+}
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java b/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
index b54a5e5..6ce81a0 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
@@ -16,12 +16,19 @@
 
 package android.provider.cts;
 
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+import static android.Manifest.permission.CAMERA;
+import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
+import static android.Manifest.permission.RECORD_AUDIO;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+
 import android.app.Activity;
-import android.app.UiAutomation;
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.UriPermission;
+import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.media.ExifInterface;
@@ -41,7 +48,6 @@
 import android.support.test.uiautomator.UiObject2;
 import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
-import androidx.core.content.FileProvider;
 import android.test.InstrumentationTestCase;
 import android.text.format.DateUtils;
 import android.util.Log;
@@ -53,9 +59,14 @@
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
+import androidx.core.content.FileProvider;
+
 public class MediaStoreUiTest extends InstrumentationTestCase {
     private static final String TAG = "MediaStoreUiTest";
 
@@ -141,6 +152,13 @@
         try { mDevice.findObject(sel).click(); } catch (Throwable ignored) { }
     }
 
+    private void maybeGrantRuntimePermission(String pkg, Set<String> requested, String permission) {
+        if (requested.contains(permission)) {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .grantRuntimePermission(pkg, permission);
+        }
+    }
+
     /**
      * Verify that whoever handles {@link MediaStore#ACTION_IMAGE_CAPTURE} can
      * correctly write the contents into a passed {@code content://} Uri.
@@ -167,14 +185,18 @@
         final String pkg = ri.activityInfo.packageName;
         Log.d(TAG, "We're probably launching " + ri);
 
+        final PackageInfo pi = context.getPackageManager().getPackageInfo(pkg,
+                PackageManager.GET_PERMISSIONS);
+        final Set<String> req = new HashSet<>();
+        req.addAll(Arrays.asList(pi.requestedPermissions));
+
         // Grant them all the permissions they might want
-        final UiAutomation ui = InstrumentationRegistry.getInstrumentation().getUiAutomation();
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.CAMERA);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.ACCESS_COARSE_LOCATION);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.ACCESS_FINE_LOCATION);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.RECORD_AUDIO);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.READ_EXTERNAL_STORAGE);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
+        maybeGrantRuntimePermission(pkg, req, CAMERA);
+        maybeGrantRuntimePermission(pkg, req, ACCESS_COARSE_LOCATION);
+        maybeGrantRuntimePermission(pkg, req, ACCESS_FINE_LOCATION);
+        maybeGrantRuntimePermission(pkg, req, RECORD_AUDIO);
+        maybeGrantRuntimePermission(pkg, req, READ_EXTERNAL_STORAGE);
+        maybeGrantRuntimePermission(pkg, req, WRITE_EXTERNAL_STORAGE);
         SystemClock.sleep(DateUtils.SECOND_IN_MILLIS);
 
         mActivity.startActivityForResult(intent, REQUEST_CODE);
diff --git a/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java b/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java
index badc88e..bbdf714 100644
--- a/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java
+++ b/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java
@@ -149,6 +149,11 @@
             c.close();
 
             // restore the fontScale
+            try {
+                // Delay helps ActivityManager in completing its previous font-change processing.
+                Thread.sleep(1000);
+            } catch (Exception e){}
+
             cfg.fontScale = store;
             assertTrue(System.putConfiguration(cr, cfg));
         }
diff --git a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
index 438857d..991111b 100644
--- a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
+++ b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
@@ -18,6 +18,7 @@
 
 package android.omapi.cts;
 
+import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.*;
 import static org.junit.Assume.assumeTrue;
 
@@ -301,43 +302,51 @@
     /** Tests Select API */
     @Test
     public void testSelectableAid() {
-        testSelectableAid(SELECTABLE_AID);
+        try {
+            waitForConnection();
+            Reader[] readers = seService.getReaders();
+            for (Reader reader : readers) {
+                testSelectableAid(reader, SELECTABLE_AID);
+            }
+        } catch (Exception e) {
+            fail("unexpected exception " + e);
+        }
     }
 
     @Test
     public void testLongSelectResponse() {
-        byte[] selectResponse = testSelectableAid(LONG_SELECT_RESPONSE_AID);
-        if (selectResponse == null) {
-            return;
-        }
-        assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
-    }
-
-
-    private byte[] testSelectableAid(byte[] aid) {
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                Session session = reader.openSession();
-                assertNotNull("Null Session", session);
-                Channel channel = session.openLogicalChannel(aid, (byte)0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertGreaterOrEqual(selectResponse.length, 2);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                channel.close();
-                session.close();
-                return selectResponse;
+                byte[] selectResponse = testSelectableAid(reader, LONG_SELECT_RESPONSE_AID);
+                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
             }
         } catch (Exception e) {
-            fail("Unexpected Exception " + e);
+            fail("unexpected exception " + e);
         }
-        return null;
+    }
+
+    private byte[] testSelectableAid(Reader reader, byte[] aid) throws IOException {
+        byte[] selectResponse = null;
+        Session session = null;
+        Channel channel = null;
+        try {
+            assertTrue(reader.isSecureElementPresent());
+            session = reader.openSession();
+            assertNotNull("Null Session", session);
+            channel = session.openLogicalChannel(aid, (byte) 0x00);
+            assertNotNull("Null Channel", channel);
+            selectResponse = channel.getSelectResponse();
+        } finally {
+            if (channel != null) channel.close();
+            if (session != null) session.close();
+        }
+        assertNotNull("Null Select Response", selectResponse);
+        assertGreaterOrEqual(selectResponse.length, 2);
+        assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+        assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+        return selectResponse;
     }
 
     /** Tests if NoSuchElementException in Select */
@@ -505,7 +514,8 @@
                     byte[] response = internalTransmitApdu(reader, apdu);
                     assertGreaterOrEqual(response.length, apdu.length + 2);
                     byte[] responseSubstring = Arrays.copyOfRange(response, 0, apdu.length);
-                    apdu[0] = 0x01;
+                    // We should not care about which channel number is actually assigned.
+                    responseSubstring[0] = apdu[0];
                     assertTrue(Arrays.equals(responseSubstring, apdu));
                     byte[] SW = SW_62xx[i];
                     assertEquals(response[response.length - 1], SW[1]);
diff --git a/tests/tests/secure_element/sample_applet/Google-eSE-test.cap b/tests/tests/secure_element/sample_applet/Google-eSE-test.cap
new file mode 100644
index 0000000..448cadb
--- /dev/null
+++ b/tests/tests/secure_element/sample_applet/Google-eSE-test.cap
Binary files differ
diff --git a/tests/tests/secure_element/sample_applet/src/com/android/cts/omapi/test/CtsAndroidOmapiTestApplet.java b/tests/tests/secure_element/sample_applet/src/com/android/cts/omapi/test/CtsAndroidOmapiTestApplet.java
index c74d49b..ff12921 100644
--- a/tests/tests/secure_element/sample_applet/src/com/android/cts/omapi/test/CtsAndroidOmapiTestApplet.java
+++ b/tests/tests/secure_element/sample_applet/src/com/android/cts/omapi/test/CtsAndroidOmapiTestApplet.java
@@ -1,267 +1,319 @@
-package com.android.cts.omapi.test;

-

-import javacard.framework.APDU;

-import javacard.framework.ISO7816;

-import javacard.framework.Applet;

-import javacard.framework.ISOException;

-import javacard.framework.Util;

-

-public class CtsAndroidOmapiTestApplet extends Applet {

-

-	final private static byte NO_DATA_INS_1 = (byte) 0x06;

-	final private static byte NO_DATA_INS_2 = (byte) 0x0A;

-

-	final private static byte DATA_INS_1 = (byte) 0x08;

-	final private static byte DATA_INS_2 = (byte) 0xC0;

-

-	final private static byte SW_62xx_APDU_INS = (byte) 0xF3;

-	final private static byte SW_62xx_DATA_APDU_P2 = (byte) 0x08;

-	final private static byte SW_62xx_VALIDATE_DATA_P2 = (byte) 0x0C;

-	private final static byte[] SW_62xx_VALIDATE_DATA_RESP =

-            new byte[]{0x01, (byte) 0xF3, 0x00, 0x0C, 0x01, (byte) 0xAA, 0x00};

-	private final static short[] SW_62xx_resp = new short[]{

-			(short)0x6200, (short)0x6281, (short)0x6282, (short)0x6283,

-			(short)0x6285, (short)0x62F1, (short)0x62F2, (short)0x63F1,

-			(short)0x63F2, (short)0x63C2, (short)0x6202, (short)0x6280,

-			(short)0x6284, (short)0x6286, (short)0x6300, (short)0x6381,

-	};

-

-	final public static byte SEGMENTED_RESP_INS_1 = (byte) 0xC2;

-	final public static byte SEGMENTED_RESP_INS_2 = (byte) 0xC4;

-	final public static byte SEGMENTED_RESP_INS_3 = (byte) 0xC6;

-	final public static byte SEGMENTED_RESP_INS_4 = (byte) 0xC8;

-	final public static byte SEGMENTED_RESP_INS_5 = (byte) 0xCF;

-

-	final private static byte CHECK_SELECT_P2_APDU = (byte)0xF4;

-	final public static byte GET_RESPONSE_INS = (byte) 0xC0;

-

-	final private static byte BER_TLV_TYPE = (byte) 0x1F;

-	final private static short SELECT_RESPONSE_DATA_LENGTH = (short)252;

-

-	private byte[] respBuf;

-	private short respBuffOffset = 0;

-

-	public static void install(byte[] bArray, short bOffset, byte bLength) {

-		// GP-compliant JavaCard applet registration

-		new com.android.cts.omapi.test.CtsAndroidOmapiTestApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);

-	}

-

-	public void process(APDU apdu) {

-		byte[] buf = apdu.getBuffer();

-		short le, lc;

-		short sendLen;

-		byte p1 = buf[ISO7816.OFFSET_P1];

-		byte p2 = buf[ISO7816.OFFSET_P2];

-

-		if (selectingApplet()) {

-			lc = buf[ISO7816.OFFSET_LC];

-			if (buf[(short)(lc + ISO7816.OFFSET_CDATA - 1)]  == 0x31) {

-				//AID: A000000476416E64726F696443545331

-				ISOException.throwIt(ISO7816.SW_NO_ERROR);

-			} else {

-				//A000000476416E64726F696443545332

-				sendLen = fillBerTLVBytes(SELECT_RESPONSE_DATA_LENGTH);

-				le = apdu.setOutgoing();

-				apdu.setOutgoingLength((short) sendLen);

-				Util.arrayCopy(respBuf, (short) 0, buf, (short) 0,

-				        (short) respBuf.length);

-				apdu.sendBytesLong(buf, respBuffOffset, sendLen);

-				return;

-			}

-		}

-		switch (buf[ISO7816.OFFSET_INS]) {

-		case NO_DATA_INS_1:

-		case NO_DATA_INS_2:

-			ISOException.throwIt(ISO7816.SW_NO_ERROR);

-			break;

-		case DATA_INS_2:

-			apdu.setIncomingAndReceive();

-	        lc = apdu.getIncomingLength();

-			//conflict with ISO Get Response command

-			if (lc > 0) {

-				//if case 3 APDU, return 256 bytes data

-				sendLen = fillBytes((short)256);

-				le = apdu.setOutgoing();

-				apdu.setOutgoingLength((short) sendLen);

-				Util.arrayCopy(respBuf, (short) 0, buf, (short) 0,

-				        (short) respBuf.length);

-				apdu.sendBytesLong(buf, respBuffOffset, sendLen);

-			} else {

-				//ISO GET_RESPONSE command

-				if (respBuf == null) {

-					ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);

-				} else {

-					le = apdu.setOutgoing();

-					sendLen = (short) (respBuf.length - respBuffOffset);

-					sendLen = le > sendLen ? sendLen : le;

-					apdu.setOutgoingLength(sendLen);

-					apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);

-					respBuffOffset += sendLen;

-					sendLen = (short) (respBuf.length - respBuffOffset);

-					if (sendLen > 0) {

-						if (sendLen > 256) sendLen = 0x00;

-						ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | sendLen));

-					} else {

-						respBuf = null;

-					}

-				}

-			}

-			break;

-

-		case DATA_INS_1:

-			// return 256 bytes data

-			sendLen = fillBytes((short)256);

-			le = apdu.setOutgoing();

-			apdu.setOutgoingLength((short) sendLen);

-			Util.arrayCopy(respBuf, (short) 0, buf, (short) 0,

-			        (short) respBuf.length);

-			apdu.sendBytesLong(buf, respBuffOffset, sendLen);

-			break;

-		case SW_62xx_APDU_INS:

-			if (p1 > 16 || p1 < 1) {

-				ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);

-			} else if (p2 == SW_62xx_DATA_APDU_P2){

-				sendLen = fillBytes((short)3);

-				le = apdu.setOutgoing();

-				apdu.setOutgoingLength((short) sendLen);

-				Util.arrayCopy(respBuf, (short) 0, buf, (short) 0,

-				        (short) respBuf.length);

-				apdu.sendBytesLong(buf, respBuffOffset, sendLen);

-				ISOException.throwIt(SW_62xx_resp[p1 -1]);

-			} else if (p2 == SW_62xx_VALIDATE_DATA_P2){

-				le = apdu.setOutgoing();

-				apdu.setOutgoingLength((short) (SW_62xx_VALIDATE_DATA_RESP.length));

-				Util.arrayCopy(SW_62xx_VALIDATE_DATA_RESP, (short) 0, buf, (short) 0,

-				        (short) SW_62xx_VALIDATE_DATA_RESP.length);

-				buf[ISO7816.OFFSET_P1] = p1;

-				apdu.sendBytesLong(buf, (short)0, (short) SW_62xx_VALIDATE_DATA_RESP.length);

-				ISOException.throwIt(SW_62xx_resp[p1 -1]);

-			} else {

-				ISOException.throwIt(SW_62xx_resp[p1 -1]);

-			}

-			break;

-		case SEGMENTED_RESP_INS_1:

-		case SEGMENTED_RESP_INS_2:

-			le = (short)((short)((p1 & 0xFF)<< 8) | (short)(p2 & 0xFF));

-			sendLen = fillBytes(le);

-			le = apdu.setOutgoing();

-			sendLen = le > sendLen ? sendLen : le;

-			if (sendLen > 0xFF) sendLen = 0xFF;

-			apdu.setOutgoingLength(sendLen);

-			apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);

-			respBuffOffset += sendLen;

-			sendLen = (short) (respBuf.length - respBuffOffset);

-			if (sendLen > 0) {

-				if (sendLen > 256) sendLen = 0x00;

-				ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | sendLen));

-			}

-			break;

-		case SEGMENTED_RESP_INS_3:

-		case SEGMENTED_RESP_INS_4:

-			le = (short)((short)((p1 & 0xFF)<< 8) | (short)(p2 & 0xFF));

-			sendLen = fillBytes(le);

-			le = apdu.setOutgoing();

-			sendLen = le > sendLen ? sendLen : le;

-			apdu.setOutgoingLength(sendLen);

-			apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);

-			respBuffOffset += sendLen;

-			sendLen = (short) (respBuf.length - respBuffOffset);

-			if (sendLen > 0) {

-				if (sendLen > 256) sendLen = 0x00;

-				ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | sendLen));

-			}

-			break;

-

-		case SEGMENTED_RESP_INS_5:

-			le = apdu.setOutgoing();

-			if (le != 0xFF) {

-				short buffer_len = (short)((short)((p1 & 0xFF)<< 8) | (short)(p2 & 0xFF));

-				sendLen = fillBytes(buffer_len);

-				sendLen = le > sendLen ? sendLen : le;

-				apdu.setOutgoingLength(sendLen);

-				apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);

-				respBuffOffset += sendLen;

-				sendLen = (short) (respBuf.length - respBuffOffset);

-				if (sendLen > 0) {

-					if (sendLen > 256) sendLen = 0x00;

-					ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | sendLen));

-				}

-			} else {

-				ISOException.throwIt((short) (ISO7816.SW_CORRECT_LENGTH_00 | 0xFF));

-			}

-			break;

-		case CHECK_SELECT_P2_APDU:

-			byte[] p2_00 = new byte[] {0x00};

-			le = apdu.setOutgoing();

-			apdu.setOutgoingLength((short) p2_00.length);

-			Util.arrayCopy(p2_00, (short) 0, buf, (short) 0,

-			        (short) p2_00.length);

-			apdu.sendBytesLong(buf, (short)0, (short)p2_00.length);

-			break;

-		default:

-			// Case is not known.

-			ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);

-		}

-	}

-

-	/**

-	 * Fills APDU buffer with a pattern.

-	 *

-	 * @param le - length of outgoing data.

-	 */

-	public short fillBerTLVBytes(short le) {

-		//support length from 0x00 - 0x7FFF

-		short total_len;

-		short le_len = 1;

-		if (le < (short)0x80) {

-			le_len = 1;

-		} else if (le < (short)0x100) {

-			le_len = 2;

-		} else {

-			le_len = 3;

-		}

-		total_len = (short)(le + 2 + le_len);

-		short i = 0;

-		respBuf = new byte[total_len];

-		respBuf[(short)i] = BER_TLV_TYPE;

-		i = (short)(i + 1);

-		respBuf[(short)i] = 0x00; //second byte of Type

-		i = (short)(i + 1);

-		if (le < (short)0x80) {

-			respBuf[(short)i] = (byte)le;

-			i = (short)(i + 1);

-		} else if (le < (short)0x100) {

-			respBuf[(short)i] = (byte)0x81;

-			i = (short)(i + 1);

-			respBuf[(short)i] = (byte)le;

-			i = (short)(i + 1);

-		} else {

-			respBuf[(short)i] = (byte)0x82;

-			i = (short)(i + 1);

-			respBuf[(short)i] = (byte)(le >> 8);

-			i = (short)(i + 1);

-			respBuf[(short)i] = (byte)(le & 0xFF);

-			i = (short)(i + 1);

-		}

-		while (i < total_len) {

-			respBuf[i] = (byte)((i - 2 - le_len) & 0xFF);

-			i = (short)(i + 1);

-		}

-		respBuf[(short)(respBuf.length - 1)] = (byte)0xFF;

-		respBuffOffset = (short) 0;

-		return total_len;

-	}

-

-	public short fillBytes(short total_len) {

-		short i = 0;

-		respBuf = new byte[total_len];

-		while (i < total_len) {

-			respBuf[i] = (byte)(i & 0xFF);

-			i = (short)(i + 1);

-		}

-		respBuffOffset = (short) 0;

-		//set the last byte to 0xFF for CTS validation

-		respBuf[(short)(respBuf.length - 1)] = (byte)0xFF;

-		return total_len;

-	}

-}

+package com.android.cts.omapi.test;
+
+import javacard.framework.APDU;
+import javacard.framework.ISO7816;
+import javacard.framework.Applet;
+import javacard.framework.ISOException;
+import javacard.framework.Util;
+
+public class CtsAndroidOmapiTestApplet extends Applet {
+
+  final private static byte NO_DATA_INS_1 = (byte) 0x06;
+  final private static byte NO_DATA_INS_2 = (byte) 0x0A;
+
+  final private static byte DATA_INS_1 = (byte) 0x08;
+  final private static byte DATA_INS_2 = (byte) 0x0C;
+
+  final private static byte SW_62xx_APDU_INS = (byte) 0xF3;
+  final private static byte SW_62xx_DATA_APDU_P2 = (byte) 0x08;
+  final private static byte SW_62xx_VALIDATE_DATA_P2 = (byte) 0x0C;
+  private final static byte[] SW_62xx_VALIDATE_DATA_RESP =
+            new byte[]{0x01, (byte) 0xF3, 0x00, 0x0C, 0x01, (byte) 0xAA, 0x00};
+  private final static short[] SW_62xx_resp = new short[]{
+      (short)0x6200, (short)0x6281, (short)0x6282, (short)0x6283,
+      (short)0x6285, (short)0x62F1, (short)0x62F2, (short)0x63F1,
+      (short)0x63F2, (short)0x63C2, (short)0x6202, (short)0x6280,
+      (short)0x6284, (short)0x6286, (short)0x6300, (short)0x6381,
+  };
+
+  final public static byte SEGMENTED_RESP_INS_1 = (byte) 0xC2;
+  final public static byte SEGMENTED_RESP_INS_2 = (byte) 0xC4;
+  final public static byte SEGMENTED_RESP_INS_3 = (byte) 0xC6;
+  final public static byte SEGMENTED_RESP_INS_4 = (byte) 0xC8;
+  final public static byte SEGMENTED_RESP_INS_5 = (byte) 0xCF;
+
+  final private static byte CHECK_SELECT_P2_APDU = (byte)0xF4;
+  final public static byte GET_RESPONSE_INS = (byte) 0xC0;
+
+  final private static byte BER_TLV_TYPE = (byte) 0x1F;
+  final private static short SELECT_RESPONSE_DATA_LENGTH = (short)252;
+
+  private byte[] respBuf;
+  private short respBuffOffset = 0;
+
+  final private static short LENGTH_256 = (short) 0x0100;
+  private final static byte[] resp_bytes256 = new byte[]{
+    (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05,
+    (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, (byte)0x0A, (byte)0x0B,
+    (byte)0x0C, (byte)0x0D, (byte)0x0E, (byte)0x0F,
+    (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15,
+    (byte)0x16, (byte)0x17, (byte)0x18, (byte)0x19, (byte)0x1A, (byte)0x1B,
+    (byte)0x1C, (byte)0x1D, (byte)0x1E, (byte)0x1F,
+    (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25,
+    (byte)0x26, (byte)0x27, (byte)0x28, (byte)0x29, (byte)0x2A, (byte)0x2B,
+    (byte)0x2C, (byte)0x2D, (byte)0x2E, (byte)0x2F,
+    (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35,
+    (byte)0x36, (byte)0x37, (byte)0x38, (byte)0x39, (byte)0x3A, (byte)0x3B,
+    (byte)0x3C, (byte)0x3D, (byte)0x3E, (byte)0x3F,
+    (byte)0x40, (byte)0x41, (byte)0x42, (byte)0x43, (byte)0x44, (byte)0x45,
+    (byte)0x46, (byte)0x47, (byte)0x48, (byte)0x49, (byte)0x4A, (byte)0x4B,
+    (byte)0x4C, (byte)0x4D, (byte)0x4E, (byte)0x4F,
+    (byte)0x50, (byte)0x51, (byte)0x52, (byte)0x53, (byte)0x54, (byte)0x55,
+    (byte)0x56, (byte)0x57, (byte)0x58, (byte)0x59, (byte)0x5A, (byte)0x5B,
+    (byte)0x5C, (byte)0x5D, (byte)0x5E, (byte)0x5F,
+    (byte)0x60, (byte)0x61, (byte)0x62, (byte)0x63, (byte)0x64, (byte)0x65,
+    (byte)0x66, (byte)0x67, (byte)0x68, (byte)0x69, (byte)0x6A, (byte)0x6B,
+    (byte)0x6C, (byte)0x6D, (byte)0x6E, (byte)0x6F,
+    (byte)0x70, (byte)0x71, (byte)0x72, (byte)0x73, (byte)0x74, (byte)0x75,
+    (byte)0x76, (byte)0x77, (byte)0x78, (byte)0x79, (byte)0x7A, (byte)0x7B,
+    (byte)0x7C, (byte)0x7D, (byte)0x7E, (byte)0x7F,
+    (byte)0x80, (byte)0x81, (byte)0x82, (byte)0x83, (byte)0x84, (byte)0x85,
+    (byte)0x86, (byte)0x87, (byte)0x88, (byte)0x89, (byte)0x8A, (byte)0x8B,
+    (byte)0x8C, (byte)0x8D, (byte)0x8E, (byte)0x8F,
+    (byte)0x90, (byte)0x91, (byte)0x92, (byte)0x93, (byte)0x94, (byte)0x95,
+    (byte)0x96, (byte)0x97, (byte)0x98, (byte)0x99, (byte)0x9A, (byte)0x9B,
+    (byte)0x9C, (byte)0x9D, (byte)0x9E, (byte)0x9F,
+    (byte)0xA0, (byte)0xA1, (byte)0xA2, (byte)0xA3, (byte)0xA4, (byte)0xA5,
+    (byte)0xA6, (byte)0xA7, (byte)0xA8, (byte)0xA9, (byte)0xAA, (byte)0xAB,
+    (byte)0xAC, (byte)0xAD, (byte)0xAE, (byte)0xAF,
+    (byte)0xB0, (byte)0xB1, (byte)0xB2, (byte)0xB3, (byte)0xB4, (byte)0xB5,
+    (byte)0xB6, (byte)0xB7, (byte)0xB8, (byte)0xB9, (byte)0xBA, (byte)0xBB,
+    (byte)0xBC, (byte)0xBD, (byte)0xBE, (byte)0xBF,
+    (byte)0xC0, (byte)0xC1, (byte)0xC2, (byte)0xC3, (byte)0xC4, (byte)0xC5,
+    (byte)0xC6, (byte)0xC7, (byte)0xC8, (byte)0xC9, (byte)0xCA, (byte)0xCB,
+    (byte)0xCC, (byte)0xCD, (byte)0xCE, (byte)0xCF,
+    (byte)0xD0, (byte)0xD1, (byte)0xD2, (byte)0xD3, (byte)0xD4, (byte)0xD5,
+    (byte)0xD6, (byte)0xD7, (byte)0xD8, (byte)0xD9, (byte)0xDA, (byte)0xDB,
+    (byte)0xDC, (byte)0xDD, (byte)0xDE, (byte)0xDF,
+    (byte)0xE0, (byte)0xE1, (byte)0xE2, (byte)0xE3, (byte)0xE4, (byte)0xE5,
+    (byte)0xE6, (byte)0xE7, (byte)0xE8, (byte)0xE9, (byte)0xEA, (byte)0xEB,
+    (byte)0xEC, (byte)0xED, (byte)0xEE, (byte)0xEF,
+    (byte)0xF0, (byte)0xF1, (byte)0xF2, (byte)0xF3, (byte)0xF4, (byte)0xF5,
+    (byte)0xF6, (byte)0xF7, (byte)0xF8, (byte)0xF9, (byte)0xFA, (byte)0xFB,
+    (byte)0xFC, (byte)0xFD, (byte)0xFE, (byte)0xFF
+  };
+
+  public static void install(byte[] bArray, short bOffset, byte bLength) {
+    // GP-compliant JavaCard applet registration
+    new com.android.cts.omapi.test.CtsAndroidOmapiTestApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
+  }
+
+  public void process(APDU apdu) {
+    byte[] buf = apdu.getBuffer();
+    short le, lc;
+    short sendLen;
+    byte p1 = buf[ISO7816.OFFSET_P1];
+    byte p2 = buf[ISO7816.OFFSET_P2];
+
+    if (selectingApplet()) {
+      lc = buf[ISO7816.OFFSET_LC];
+      if (buf[(short)(lc + ISO7816.OFFSET_CDATA - 1)]  == 0x31) {
+        //AID: A000000476416E64726F696443545331
+        ISOException.throwIt(ISO7816.SW_NO_ERROR);
+      } else {
+        //A000000476416E64726F696443545332
+        sendLen = fillBerTLVBytes(SELECT_RESPONSE_DATA_LENGTH);
+        le = apdu.setOutgoing();
+        apdu.setOutgoingLength((short)sendLen);
+        Util.arrayCopy(respBuf, (short)0, buf, (short)0, (short)respBuf.length);
+        apdu.sendBytesLong(buf, respBuffOffset, sendLen);
+        return;
+      }
+    }
+    switch (buf[ISO7816.OFFSET_INS]) {
+    case NO_DATA_INS_1:
+    case NO_DATA_INS_2:
+      ISOException.throwIt(ISO7816.SW_NO_ERROR);
+      break;
+    case DATA_INS_2:
+      apdu.setIncomingAndReceive();
+      //case 3 APDU, return 256 bytes data
+      sendLen = fillBytes((short)256);
+      le = apdu.setOutgoing();
+      apdu.setOutgoingLength((short)sendLen);
+      Util.arrayCopy(respBuf, (short)0, buf, (short)0, (short)respBuf.length);
+      apdu.sendBytesLong(buf, respBuffOffset, sendLen);
+      break;   
+    case GET_RESPONSE_INS:
+      apdu.setIncomingAndReceive();
+        //ISO GET_RESPONSE command
+        if (respBuf == null) {
+          ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
+        } else {
+          le = apdu.setOutgoing();
+          sendLen = (short) (respBuf.length - respBuffOffset);
+          sendLen = le > sendLen ? sendLen : le;
+          apdu.setOutgoingLength(sendLen);
+          apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);
+          respBuffOffset += sendLen;
+          sendLen = (short) (respBuf.length - respBuffOffset);
+          if (sendLen > 0) {
+            if (sendLen > 256) sendLen = 0x00;
+            ISOException.throwIt((short)(ISO7816.SW_BYTES_REMAINING_00 | sendLen));
+          } else {
+            respBuf = null;
+          }
+        }
+      break;
+    case DATA_INS_1:
+      // return 256 bytes data
+      sendLen = fillBytes((short)256);
+      le = apdu.setOutgoing();
+      apdu.setOutgoingLength((short) sendLen);
+      Util.arrayCopy(respBuf, (short)0, buf, (short)0, (short)respBuf.length);
+      apdu.sendBytesLong(buf, respBuffOffset, sendLen);
+      break;
+    case SW_62xx_APDU_INS:
+      if (p1 > 16 || p1 < 1) {
+        ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
+      } else if (p2 == SW_62xx_DATA_APDU_P2){
+        sendLen = fillBytes((short)3);
+        le = apdu.setOutgoing();
+        apdu.setOutgoingLength((short)sendLen);
+        Util.arrayCopy(respBuf, (short)0, buf, (short)0, (short) respBuf.length);
+        apdu.sendBytesLong(buf, respBuffOffset, sendLen);
+        ISOException.throwIt(SW_62xx_resp[p1 -1]);
+      } else if (p2 == SW_62xx_VALIDATE_DATA_P2){
+        le = apdu.setOutgoing();
+        apdu.setOutgoingLength((short) (SW_62xx_VALIDATE_DATA_RESP.length));
+        Util.arrayCopy(SW_62xx_VALIDATE_DATA_RESP, (short) 0, buf, (short) 0,
+          (short) SW_62xx_VALIDATE_DATA_RESP.length);
+        buf[ISO7816.OFFSET_P1] = p1;
+        apdu.sendBytesLong(buf, (short)0, (short) SW_62xx_VALIDATE_DATA_RESP.length);
+        ISOException.throwIt(SW_62xx_resp[p1 -1]);
+      } else {
+        ISOException.throwIt(SW_62xx_resp[p1 -1]);
+      }
+      break;
+    case SEGMENTED_RESP_INS_1:
+    case SEGMENTED_RESP_INS_2:
+      le = (short)((short)((p1 & 0xFF)<< 8) | (short)(p2 & 0xFF));
+      sendLen = fillBytes(le);
+      le = apdu.setOutgoing();
+      sendLen = le > sendLen ? sendLen : le;
+      if (sendLen > 0xFF) sendLen = 0xFF;
+      apdu.setOutgoingLength(sendLen);
+      apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);
+      respBuffOffset += sendLen;
+      sendLen = (short) (respBuf.length - respBuffOffset);
+      if (sendLen > 0) {
+        if (sendLen > 256) sendLen = 0x00;
+        ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | sendLen));
+      }
+      break;
+    case SEGMENTED_RESP_INS_3:
+    case SEGMENTED_RESP_INS_4:
+      le = (short)((short)((p1 & 0xFF)<< 8) | (short)(p2 & 0xFF));
+      sendLen = fillBytes(le);
+      le = apdu.setOutgoing();
+      sendLen = le > sendLen ? sendLen : le;
+      apdu.setOutgoingLength(sendLen);
+      apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);
+      respBuffOffset += sendLen;
+      sendLen = (short) (respBuf.length - respBuffOffset);
+      if (sendLen > 0) {
+        if (sendLen > 256) sendLen = 0x00;
+        ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | sendLen));
+      }
+      break;
+
+    case SEGMENTED_RESP_INS_5:
+      le = apdu.setOutgoing();
+      if (le != 0xFF) {
+        short buffer_len = (short)((short)((p1 & 0xFF)<< 8) | (short)(p2 & 0xFF));
+        sendLen = fillBytes(buffer_len);
+        sendLen = le > sendLen ? sendLen : le;
+        apdu.setOutgoingLength(sendLen);
+        apdu.sendBytesLong(respBuf, respBuffOffset, sendLen);
+        respBuffOffset += sendLen;
+        sendLen = (short) (respBuf.length - respBuffOffset);
+        if (sendLen > 0) {
+          if (sendLen > 256) sendLen = 0x00;
+          ISOException.throwIt((short)(ISO7816.SW_BYTES_REMAINING_00 | sendLen));
+        }
+      } else {
+        ISOException.throwIt((short)(ISO7816.SW_CORRECT_LENGTH_00 | 0xFF));
+      }
+      break;
+    case CHECK_SELECT_P2_APDU:
+      byte[] p2_00 = new byte[] {0x00};
+      le = apdu.setOutgoing();
+      apdu.setOutgoingLength((short) p2_00.length);
+      Util.arrayCopy(p2_00, (short) 0, buf, (short) 0, (short) p2_00.length);
+      apdu.sendBytesLong(buf, (short)0, (short)p2_00.length);
+      break;
+    default:
+      // Case is not known.
+      ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
+    }
+  }
+
+  /**
+   * Fills APDU buffer with a pattern.
+   *
+   * @param le - length of outgoing data.
+   */
+  public short fillBerTLVBytes(short le) {
+    //support length from 0x00 - 0x7FFF
+    short total_len;
+    short le_len = 1;
+    if (le < (short)0x80) {
+      le_len = 1;
+    } else if (le < (short)0x100) {
+      le_len = 2;
+    } else {
+      le_len = 3;
+    }
+    total_len = (short)(le + 2 + le_len);
+    short i = 0;
+    respBuf = new byte[total_len];
+    respBuf[(short)i] = BER_TLV_TYPE;
+    i = (short)(i + 1);
+    respBuf[(short)i] = 0x00; //second byte of Type
+    i = (short)(i + 1);
+    if (le < (short)0x80) {
+      respBuf[(short)i] = (byte)le;
+      i = (short)(i + 1);
+    } else if (le < (short)0x100) {
+      respBuf[(short)i] = (byte)0x81;
+      i = (short)(i + 1);
+      respBuf[(short)i] = (byte)le;
+      i = (short)(i + 1);
+    } else {
+      respBuf[(short)i] = (byte)0x82;
+      i = (short)(i + 1);
+      respBuf[(short)i] = (byte)(le >> 8);
+      i = (short)(i + 1);
+      respBuf[(short)i] = (byte)(le & 0xFF);
+      i = (short)(i + 1);
+    }
+    while (i < total_len) {
+      respBuf[i] = (byte)((i - 2 - le_len) & 0xFF);
+      i = (short)(i + 1);
+    }
+    respBuf[(short)(respBuf.length - 1)] = (byte)0xFF;
+    respBuffOffset = (short) 0;
+    return total_len;
+  }
+
+  public short fillBytes(short total_len) {
+    short i = 0;
+    short len = total_len;
+    respBuf = new byte[total_len];
+    while (i < total_len) {
+      if (len >= LENGTH_256) {
+        Util.arrayCopyNonAtomic(resp_bytes256, (short)0, respBuf,
+          (short)i, LENGTH_256);
+        i = (short)(i + LENGTH_256);
+        len = (short)(len - LENGTH_256);
+      } else {
+        respBuf[i] = (byte)(i & 0xFF);
+        i = (short)(i + 1);
+      }
+    }
+    respBuffOffset = (short) 0;
+    //set the last byte to 0xFF for CTS validation
+    respBuf[(short)(respBuf.length - 1)] = (byte)0xFF;
+    return total_len;
+  }
+}
diff --git a/tests/tests/secure_element/sample_applet/test.cap b/tests/tests/secure_element/sample_applet/test.cap
deleted file mode 100644
index d4ce916..0000000
--- a/tests/tests/secure_element/sample_applet/test.cap
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/ListeningPortsTest.java b/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
index 6d7c5e2..0e3c72b5 100644
--- a/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
+++ b/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
@@ -19,7 +19,6 @@
 import android.content.pm.PackageManager;
 import android.os.Process;
 import android.os.UserHandle;
-import android.platform.test.annotations.SecurityTest;
 import android.test.AndroidTestCase;
 import android.util.Log;
 import com.android.compatibility.common.util.FeatureUtil;
@@ -43,7 +42,6 @@
  * into computer systems remotely, and minimizing the number of open ports
  * is considered a security best practice.
  */
-@SecurityTest
 public class ListeningPortsTest extends AndroidTestCase {
     private static final String TAG = "ListeningPortsTest";
 
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
index dde2ce1..a56ab29 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
@@ -26,10 +26,11 @@
 import android.content.pm.PackageManager;
 import android.content.res.Configuration;
 import android.graphics.Bitmap;
+import android.graphics.Rect;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.rule.ActivityTestRule;
 import android.util.Log;
-import android.view.KeyEvent;
+import android.view.DisplayCutout;
 import android.view.WindowInsets;
 
 import java.io.File;
@@ -37,6 +38,8 @@
 import java.io.IOException;
 import java.nio.file.FileSystems;
 import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Locale;
 
 public class LightBarTestBase {
 
@@ -45,6 +48,8 @@
     public static final Path DUMP_PATH = FileSystems.getDefault()
             .getPath("/sdcard/LightBarTestBase/");
 
+    private ArrayList<Rect> mCutouts;
+
     protected Bitmap takeStatusBarScreenshot(LightBarBaseActivity activity) {
         Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
         return Bitmap.createBitmap(fullBitmap, 0, 0, activity.getWidth(), activity.getTop());
@@ -144,18 +149,30 @@
         int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
         bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
 
+        loadCutout(activity);
         int backgroundColorPixelCount = 0;
+        int shiftY = activity.getBottom();
         for (int i = 0; i < pixels.length; i++) {
-            if (pixels[i] == backgroundColor) {
+            int x = i % bitmap.getWidth();
+            int y = i / bitmap.getWidth();
+
+            if (pixels[i] == backgroundColor
+                    || isInsideCutout(x, shiftY + y)) {
                 backgroundColorPixelCount++;
             }
         }
         assumeNavigationBarChangesColor(backgroundColorPixelCount, pixels.length);
 
         for (int col = 0; col < bitmap.getWidth(); col++) {
+            if (isInsideCutout(col, shiftY)) {
+                continue;
+            }
+
             if (dividerColor != pixels[col]) {
                 dumpBitmap(bitmap, methodName);
-                fail("Invalid color exptected=" + dividerColor + " actual=" + pixels[col]);
+                fail(String.format(Locale.ENGLISH,
+                        "Invalid color expected= 0x%08x, actual= 0x%08x",
+                        dividerColor, pixels[col]));
             }
         }
     }
@@ -164,4 +181,25 @@
         assumeTrue("Not enough background pixels. The navigation bar may not be able to change "
                 + "color.", backgroundColorPixelCount > 0.3f * totalPixel);
     }
+
+    protected ArrayList loadCutout(LightBarBaseActivity activity) {
+        mCutouts = new ArrayList<>();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(()-> {
+            WindowInsets windowInsets = activity.getRootWindowInsets();
+            DisplayCutout displayCutout = windowInsets.getDisplayCutout();
+            if (displayCutout != null) {
+                mCutouts.addAll(displayCutout.getBoundingRects());
+            }
+        });
+        return mCutouts;
+    }
+
+    protected boolean isInsideCutout(int x, int y) {
+        for (Rect cutout : mCutouts) {
+            if (cutout.contains(x, y)) {
+                return true;
+            }
+        }
+        return false;
+    }
 }
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
index 724bca0..5566a0d 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
@@ -20,13 +20,11 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import android.app.ActivityManager;
 import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.app.UiAutomation;
 import android.content.Context;
-import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.graphics.Color;
 import android.os.SystemClock;
@@ -96,7 +94,7 @@
         Thread.sleep(WAIT_TIME);
 
         Bitmap bitmap = takeStatusBarScreenshot(mActivityRule.getActivity());
-        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
+        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */, 0);
         assertLightStats(bitmap, s);
 
         mNm.cancelAll();
@@ -116,8 +114,9 @@
         injectCanceledTap(x, y);
         Thread.sleep(WAIT_TIME);
 
-        Bitmap bitmap = takeNavigationBarScreenshot(mActivityRule.getActivity());
-        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
+        LightBarActivity activity = mActivityRule.getActivity();
+        Bitmap bitmap = takeNavigationBarScreenshot(activity);
+        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */, activity.getBottom());
         assertLightStats(bitmap, s);
     }
 
@@ -225,7 +224,7 @@
         }
     }
 
-    private Stats evaluateLightBarBitmap(Bitmap bitmap, int background) {
+    private Stats evaluateLightBarBitmap(Bitmap bitmap, int background, int shiftY) {
         int iconColor = 0x99000000;
         int iconPartialColor = 0x3d000000;
 
@@ -247,8 +246,17 @@
         Stats s = new Stats();
         float eps = 0.005f;
 
+        loadCutout(mActivityRule.getActivity());
         float [] hsvPixel = new float[3];
+        int i = 0;
         for (int c : pixels) {
+            int x = i % bitmap.getWidth();
+            int y = i / bitmap.getWidth();
+            i++;
+            if (isInsideCutout(x, shiftY + y)) {
+                continue;
+            }
+
             if (isColorSame(c, background)) {
                 s.backgroundPixels++;
                 continue;
diff --git a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
index 2a6fbe6..a78ef29 100644
--- a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
@@ -576,6 +576,20 @@
 
     private void verifyAudioMode() {
         AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
-        assertEquals(MODE_IN_COMMUNICATION, am.getMode());
+        waitUntilConditionIsTrueOrTimeout(
+                new Condition() {
+                    @Override
+                    public Object expected() {
+                        return MODE_IN_COMMUNICATION;
+                    }
+
+                    @Override
+                    public Object actual() {
+                        return am.getMode();
+                    }
+                },
+                WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                "Expected audio mode to be " + MODE_IN_COMMUNICATION
+        );
     }
 }
diff --git a/tests/tests/telephony/AndroidManifest.xml b/tests/tests/telephony/AndroidManifest.xml
index b6840a3..764daf5 100644
--- a/tests/tests/telephony/AndroidManifest.xml
+++ b/tests/tests/telephony/AndroidManifest.xml
@@ -155,6 +155,8 @@
                    android:value="android.telephony.cts.embmstestapp/.CtsStreamingService"/>
         <meta-data android:name="mbms-download-service-override"
                    android:value="android.telephony.cts.embmstestapp/.CtsDownloadService"/>
+        <meta-data android:name="mbms-group-call-service-override"
+                   android:value="android.telephony.cts.embmstestapp/.CtsGroupCallService"/>
         <meta-data
             android:name="mbms-file-provider-authority"
             android:value="android.telephony.mbms.cts"/>
diff --git a/tests/tests/telephony/EmbmsMiddlewareTestApp/AndroidManifest.xml b/tests/tests/telephony/EmbmsMiddlewareTestApp/AndroidManifest.xml
index 0ea1be2..880faf6 100644
--- a/tests/tests/telephony/EmbmsMiddlewareTestApp/AndroidManifest.xml
+++ b/tests/tests/telephony/EmbmsMiddlewareTestApp/AndroidManifest.xml
@@ -30,6 +30,13 @@
         <action android:name="android.telephony.cts.embmstestapp.ACTION_CONTROL_MIDDLEWARE" />
       </intent-filter>
     </service>
+    <service android:name="android.telephony.cts.embmstestapp.CtsGroupCallService"
+             android:launchMode="singleInstance">
+      <intent-filter>
+        <action android:name="android.telephony.action.EmbmsGroupCall" />
+        <action android:name="android.telephony.cts.embmstestapp.ACTION_CONTROL_MIDDLEWARE" />
+      </intent-filter>
+    </service>
     <service android:name="android.telephony.cts.embmstestapp.CtsDownloadService"
              android:launchMode="singleInstance">
       <intent-filter>
diff --git a/tests/tests/telephony/EmbmsMiddlewareTestApp/aidl/android/telephony/cts/embmstestapp/ICtsGroupCallMiddlewareControl.aidl b/tests/tests/telephony/EmbmsMiddlewareTestApp/aidl/android/telephony/cts/embmstestapp/ICtsGroupCallMiddlewareControl.aidl
new file mode 100644
index 0000000..7f3bac7
--- /dev/null
+++ b/tests/tests/telephony/EmbmsMiddlewareTestApp/aidl/android/telephony/cts/embmstestapp/ICtsGroupCallMiddlewareControl.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.telephony.cts.embmstestapp;
+
+import android.os.Parcel;
+
+interface ICtsGroupCallMiddlewareControl {
+    // Resets the state of the CTS middleware
+    void reset();
+    // Get a list of calls made to the middleware binder.
+    // Looks like List<List<Object>>, where the first Object is always a String corresponding to
+    // the method name.
+    List getGroupCallSessionCalls();
+    // Force all methods that can return an error to return this error.
+    void forceErrorCode(int error);
+    // Fire the error callback on the current active call
+    void fireErrorOnGroupCall(int errorCode, String message);
+    // Fire the error callback on the group call session
+    void fireErrorOnSession(int errorCode, String message);
+    // The following fire callbacks on the active group call, using the provided arguments
+    void fireGroupCallStateChanged(int state, int reason);
+    void fireBroadcastSignalStrengthUpdated(int signalStrength);
+    // The following fire callbacks on the group call session.
+    void fireAvailableSaisUpdated(in List currentSais, in List availableSais);
+    void fireServiceInterfaceAvailable(String interfaceName, int index);
+}
\ No newline at end of file
diff --git a/tests/tests/telephony/EmbmsMiddlewareTestApp/src/android/telephony/cts/embmstestapp/CtsGroupCallService.java b/tests/tests/telephony/EmbmsMiddlewareTestApp/src/android/telephony/cts/embmstestapp/CtsGroupCallService.java
new file mode 100644
index 0000000..fade9fc
--- /dev/null
+++ b/tests/tests/telephony/EmbmsMiddlewareTestApp/src/android/telephony/cts/embmstestapp/CtsGroupCallService.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.telephony.cts.embmstestapp;
+
+import android.app.Service;
+import android.content.ComponentName;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.telephony.mbms.GroupCall;
+import android.telephony.mbms.MbmsErrors;
+import android.telephony.mbms.MbmsGroupCallSessionCallback;
+import android.telephony.mbms.GroupCallCallback;
+import android.telephony.mbms.vendor.MbmsGroupCallServiceBase;
+import android.util.Log;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+public class CtsGroupCallService extends MbmsGroupCallServiceBase {
+    private static final Set<String> ALLOWED_PACKAGES = new HashSet<String>() {{
+        add("android.telephony.cts");
+    }};
+    private static final String TAG = "EmbmsTestGroupCall";
+
+    public static final String METHOD_INITIALIZE = "initialize";
+    public static final String METHOD_START_GROUP_CALL = "startGroupCall";
+    public static final String METHOD_UPDATE_GROUP_CALL = "updateGroupCall";
+    public static final String METHOD_STOP_GROUP_CALL = "stopGroupCall";
+    public static final String METHOD_CLOSE = "close";
+
+    public static final String CONTROL_INTERFACE_ACTION =
+            "android.telephony.cts.embmstestapp.ACTION_CONTROL_MIDDLEWARE";
+    public static final ComponentName CONTROL_INTERFACE_COMPONENT =
+            ComponentName.unflattenFromString(
+                    "android.telephony.cts.embmstestapp/.CtsGroupCallService");
+
+    private MbmsGroupCallSessionCallback mAppCallback;
+    private GroupCallCallback mGroupCallCallback;
+
+    private HandlerThread mHandlerThread;
+    private Handler mHandler;
+    private List<List> mReceivedCalls = new LinkedList<>();
+    private int mErrorCodeOverride = MbmsErrors.SUCCESS;
+
+    @Override
+    public int initialize(MbmsGroupCallSessionCallback callback, int subId) {
+        mReceivedCalls.add(Arrays.asList(METHOD_INITIALIZE, subId));
+        if (mErrorCodeOverride != MbmsErrors.SUCCESS) {
+            return mErrorCodeOverride;
+        }
+
+        int packageUid = Binder.getCallingUid();
+        String[] packageNames = getPackageManager().getPackagesForUid(packageUid);
+        if (packageNames == null) {
+            return MbmsErrors.InitializationErrors.ERROR_APP_PERMISSIONS_NOT_GRANTED;
+        }
+        boolean isUidAllowed = Arrays.stream(packageNames).anyMatch(ALLOWED_PACKAGES::contains);
+        if (!isUidAllowed) {
+            return MbmsErrors.InitializationErrors.ERROR_APP_PERMISSIONS_NOT_GRANTED;
+        }
+
+        mHandler.post(() -> {
+            if (mAppCallback == null) {
+                mAppCallback = callback;
+            } else {
+                callback.onError(
+                        MbmsErrors.InitializationErrors.ERROR_DUPLICATE_INITIALIZE, "");
+                return;
+            }
+            callback.onMiddlewareReady();
+        });
+        return MbmsErrors.SUCCESS;
+    }
+
+    @Override
+    public int startGroupCall(final int subscriptionId, final long tmgi, final int[] saiArray,
+                final int[] frequencyArray, final GroupCallCallback callback) {
+        mReceivedCalls.add(Arrays.asList(METHOD_START_GROUP_CALL, subscriptionId, tmgi, saiArray,
+                frequencyArray));
+        if (mErrorCodeOverride != MbmsErrors.SUCCESS) {
+            return mErrorCodeOverride;
+        }
+
+        mGroupCallCallback = callback;
+        mHandler.post(() -> callback.onGroupCallStateChanged(GroupCall.STATE_STARTED,
+                GroupCall.REASON_BY_USER_REQUEST));
+        return MbmsErrors.SUCCESS;
+    }
+
+    @Override
+    public void updateGroupCall(int subscriptionId, long tmgi,
+            int[] saiArray, int[] frequencyArray) {
+        mReceivedCalls.add(Arrays.asList(METHOD_UPDATE_GROUP_CALL,
+                subscriptionId, tmgi, saiArray, frequencyArray));
+    }
+
+    @Override
+    public void stopGroupCall(int subscriptionId, long tmgi) {
+        mReceivedCalls.add(Arrays.asList(METHOD_STOP_GROUP_CALL, subscriptionId, tmgi));
+    }
+
+    @Override
+    public void dispose(int subscriptionId) {
+        mReceivedCalls.add(Arrays.asList(METHOD_CLOSE, subscriptionId));
+    }
+
+    @Override
+    public void onAppCallbackDied(int uid, int subscriptionId) {
+        mAppCallback = null;
+    }
+
+    private final IBinder mControlInterface = new ICtsGroupCallMiddlewareControl.Stub() {
+        @Override
+        public void reset() {
+            mReceivedCalls.clear();
+            mHandler.removeCallbacksAndMessages(null);
+            mAppCallback = null;
+            mErrorCodeOverride = MbmsErrors.SUCCESS;
+        }
+
+        @Override
+        public List getGroupCallSessionCalls() {
+            return mReceivedCalls;
+        }
+
+        @Override
+        public void forceErrorCode(int error) {
+            mErrorCodeOverride = error;
+        }
+
+        @Override
+        public void fireErrorOnGroupCall(int errorCode, String message) {
+            mHandler.post(() -> mGroupCallCallback.onError(errorCode, message));
+        }
+
+        @Override
+        public void fireErrorOnSession(int errorCode, String message) {
+            mHandler.post(() -> mAppCallback.onError(errorCode, message));
+        }
+
+        @Override
+        public void fireGroupCallStateChanged(int state, int reason) {
+            mHandler.post(() -> mGroupCallCallback.onGroupCallStateChanged(state, reason));
+        }
+
+        @Override
+        public void fireBroadcastSignalStrengthUpdated(int signalStrength) {
+            mHandler.post(
+                    () -> mGroupCallCallback.onBroadcastSignalStrengthUpdated(signalStrength));
+        }
+
+        @Override
+        public void fireAvailableSaisUpdated(List currentSais, List availableSais) {
+            mHandler.post(() -> mAppCallback.onAvailableSaisUpdated(currentSais, availableSais));
+        }
+
+        @Override
+        public void fireServiceInterfaceAvailable(String interfaceName, int index) {
+            mHandler.post(() -> mAppCallback.onServiceInterfaceAvailable(interfaceName, index));
+        }
+    };
+
+    @Override
+    public void onDestroy() {
+        mHandlerThread.quitSafely();
+        logd("CtsGroupCallService onDestroy");
+        super.onDestroy();
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        logd("CtsGroupCallService onBind");
+        if (CONTROL_INTERFACE_ACTION.equals(intent.getAction())) {
+            logd("CtsGroupCallService control interface bind");
+            return mControlInterface;
+        }
+        IBinder binder = super.onBind(intent);
+
+        if (mHandlerThread != null && mHandlerThread.isAlive()) {
+            return binder;
+        }
+
+        mHandlerThread = new HandlerThread("CtsGroupCallServiceWorker");
+        mHandlerThread.start();
+        mHandler = new Handler(mHandlerThread.getLooper());
+        return binder;
+    }
+
+    private static void logd(String s) {
+        Log.d(TAG, s);
+    }
+
+    private void checkInitialized() {
+        if (mAppCallback == null) {
+            throw new IllegalStateException("Not yet initialized");
+        }
+    }
+}
diff --git a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
index 264d393..e5d0bd0 100644
--- a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
@@ -258,6 +258,37 @@
         assertEquals(cdma, newCss);
     }
 
+    private static void verifyPlmnInfo(String mccStr, String mncStr, int mcc, int mnc) {
+        // If either int value is invalid, all values must be invalid
+        if (mcc == Integer.MAX_VALUE) {
+            assertTrue("MNC and MNC must always be reported together.",
+                    mnc == Integer.MAX_VALUE && mccStr == null && mncStr == null);
+            return;
+        }
+
+        assertTrue("getMcc() out of range [0, 999], mcc=" + mcc, (mcc >= 0 && mcc <= 999));
+        assertTrue("getMnc() out of range [0, 999], mnc=" + mnc, (mnc >= 0 && mnc <= 999));
+        assertTrue("MCC and MNC Strings must always be reported together.",
+                (mccStr == null) == (mncStr == null));
+
+        // For legacy compatibility, it's possible to have int values without valid string values
+        // but not the other way around.
+        // mccStr is set as NULL if empty, unknown or invalid.
+        assertTrue("getMccString() out of range [0, 999], mcc=" + mccStr,
+                mccStr == null || mccStr.matches("^[0-9]{3}$"));
+        // mccStr must either be null or match mcc integer.
+        assertTrue("MccString must match Mcc Integer, str=" + mccStr + " int=" + mcc,
+                mccStr == null || mcc == Integer.parseInt(mccStr));
+
+        // mncStr is set as NULL if empty, unknown or invalid.
+        assertTrue("getMncString() out of range [0, 999], mnc=" + mncStr,
+                mncStr == null || mncStr.matches("^[0-9]{2,3}$"));
+        // mncStr must either be null or match mnc integer.
+        assertTrue("MncString must match Mnc Integer, str=" + mncStr + " int=" + mnc,
+                mncStr == null || mnc == Integer.parseInt(mncStr));
+
+    }
+
     // Verify lte cell information is within correct range.
     private void verifyLteInfo(CellInfoLte lte) {
         verifyCellConnectionStatus(lte.getCellConnectionStatus());
@@ -278,17 +309,8 @@
         assertEquals("hashCode() did not get right hasdCode", lte.hashCode(), newCi.hashCode());
     }
 
-
     private void verifyCellIdentityLte(CellIdentityLte lte) {
-        int mcc = lte.getMcc();
-        // getMcc() returns Integer.MAX_VALUE if mccStr is null.
-        assertTrue("getMcc() out of range [0, 999], mcc=" + mcc,
-                (mcc >= 0 && mcc <= 999) || mcc == Integer.MAX_VALUE);
-
-        int mnc = lte.getMnc();
-        // getMnc() returns Integer.MAX_VALUE if mccStr is null.
-        assertTrue("getMnc() out of range [0, 999], mnc=" + mnc,
-                (mnc >= 0 && mnc <= 999) || mnc == Integer.MAX_VALUE);
+        verifyPlmnInfo(lte.getMccString(), lte.getMncString(), lte.getMcc(), lte.getMnc());
 
         // Cell identity ranges from 0 to 268435456.
         int ci = lte.getCi();
@@ -334,16 +356,6 @@
                 "getEarfcn() out of range [" + minEarfcn + "," + maxEarfcn + "], earfcn=" + earfcn,
                 earfcn == Integer.MAX_VALUE || (earfcn >= minEarfcn && earfcn <= maxEarfcn));
 
-        String mccStr = lte.getMccString();
-        // mccStr is set as NULL if empty, unknown or invalid.
-        assertTrue("getMccString() out of range [0, 999], mcc=" + mccStr,
-                mccStr == null || mccStr.matches("^[0-9]{3}$"));
-
-        String mncStr = lte.getMncString();
-        // mncStr is set as NULL if empty, unknown or invalid.
-        assertTrue("getMncString() out of range [0, 999], mnc=" + mncStr,
-                mncStr == null || mncStr.matches("^[0-9]{2,3}$"));
-
         String mobileNetworkOperator = lte.getMobileNetworkOperator();
         assertTrue("getMobileNetworkOperator() out of range [0, 999999], mobileNetworkOperator="
                         + mobileNetworkOperator,
@@ -433,15 +445,7 @@
     }
 
     private void verifyCellIdentityWcdma(CellIdentityWcdma wcdma) {
-        int mcc = wcdma.getMcc();
-        // getMcc() returns Integer.MAX_VALUE if mccStr is null.
-        assertTrue("getMcc() out of range [0, 999], mcc=" + mcc,
-                (mcc >= 0 && mcc <= 999) || mcc == Integer.MAX_VALUE);
-
-        int mnc = wcdma.getMnc();
-        // getMnc() returns Integer.MAX_VALUE if mccStr is null.
-        assertTrue("getMnc() out of range [0, 999], mnc=" + mnc,
-                (mnc >= 0 && mnc <= 999) || mnc == Integer.MAX_VALUE);
+        verifyPlmnInfo(wcdma.getMccString(), wcdma.getMncString(), wcdma.getMcc(), wcdma.getMnc());
 
         int lac = wcdma.getLac();
         assertTrue("getLac() out of range [0, 65535], lac=" + lac,
@@ -457,16 +461,6 @@
         assertTrue("getPsc() out of range [0, 511], psc=" + psc,
                 (psc >= 0 && psc <= PSC) || psc == Integer.MAX_VALUE);
 
-        String mccStr = wcdma.getMccString();
-        // mccStr is set as NULL if empty, unknown or invalid.
-        assertTrue("getMccString() out of range [0, 999], mcc=" + mccStr,
-                mccStr == null || mccStr.matches("^[0-9]{3}$"));
-
-        String mncStr = wcdma.getMncString();
-        // mncStr is set as NULL if empty, unknown or invalid.
-        assertTrue("getMncString() out of range [0, 999], mnc=" + mncStr,
-                mncStr == null || mncStr.matches("^[0-9]{2,3}$"));
-
         String mobileNetworkOperator = wcdma.getMobileNetworkOperator();
         assertTrue("getMobileNetworkOperator() out of range [0, 999999], mobileNetworkOperator="
                         + mobileNetworkOperator,
@@ -541,6 +535,8 @@
     }
 
     private void verifyCellIdentityGsm(CellIdentityGsm gsm) {
+        verifyPlmnInfo(gsm.getMccString(), gsm.getMncString(), gsm.getMcc(), gsm.getMnc());
+
         // Local area code and cellid should be with [0, 65535].
         int lac = gsm.getLac();
         assertTrue("getLac() out of range [0, 65535], lac=" + lac,
@@ -560,30 +556,12 @@
         String alphaShort = (String) gsm.getOperatorAlphaShort();
         assertNotNull("getOperatorAlphaShort() returns NULL!", alphaShort);
 
-        String mccStr = gsm.getMccString();
-        // mccStr is set as NULL if empty, unknown or invalid.
-        assertTrue("getMccString() out of range [0, 999], mcc=" + mccStr,
-                mccStr == null || mccStr.matches("^[0-9]{3}$"));
-        String mncStr = gsm.getMncString();
-        // mncStr is set as NULL if empty, unknown or invalid.
-        assertTrue("getMncString() out of range [0, 999], mnc=" + mncStr,
-                mncStr == null || mncStr.matches("^[0-9]{2,3}$"));
-
         String mobileNetworkOperator = gsm.getMobileNetworkOperator();
         assertTrue("getMobileNetworkOperator() out of range [0, 999999], mobileNetworkOperator="
                         + mobileNetworkOperator,
                 mobileNetworkOperator == null
                         || mobileNetworkOperator.matches("^[0-9]{5,6}$"));
 
-        int mcc = gsm.getMcc();
-        // getMcc() returns Integer.MAX_VALUE if mccStr is null.
-        assertTrue("getMcc() out of range [0, 999], mcc=" + mcc,
-                (mcc >= 0 && mcc <= 999) || mcc == Integer.MAX_VALUE);
-        int mnc = gsm.getMnc();
-        // getMnc() returns Integer.MAX_VALUE if mccStr is null.
-        assertTrue("getMnc() out of range [0, 999], mnc=" + mnc,
-                (mnc >= 0 && mnc <= 999) || mnc == Integer.MAX_VALUE);
-
         int bsic = gsm.getBsic();
         // TODO(b/32774471) - Bsic should always be valid
         //assertTrue("getBsic() out of range [0,63]", bsic >= 0 && bsic <=63);
diff --git a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
index 6bb1e06..d101899 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -207,13 +207,6 @@
         mTelephonyManager.getNetworkOperator();
         mTelephonyManager.getSimCountryIso();
         mTelephonyManager.getVoiceMailAlphaTag();
-        try {
-            mTelephonyManager.getNeighboringCellInfo();
-        } catch (SecurityException expectedForQ) {
-            // FIXME(nharold): This API will always throw a SecurityException for SDK level Q+.
-            // For earlier API levels this check should ensure that no exception is thrown.
-        }
-
         mTelephonyManager.isNetworkRoaming();
         mTelephonyManager.getDeviceId();
         mTelephonyManager.getDeviceId(mTelephonyManager.getSlotIndex());
diff --git a/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallSessionTest.java b/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallSessionTest.java
new file mode 100644
index 0000000..becebdb
--- /dev/null
+++ b/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallSessionTest.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.telephony.embms.cts;
+
+import android.telephony.MbmsGroupCallSession;
+import android.telephony.cts.embmstestapp.CtsGroupCallService;
+import android.telephony.mbms.GroupCallCallback;
+import android.telephony.mbms.MbmsErrors;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class MbmsGroupCallSessionTest extends MbmsGroupCallTestBase {
+    public void testDuplicateSession() throws Exception {
+        try {
+            MbmsGroupCallSession failure = MbmsGroupCallSession.create(
+                    mContext, mCallbackExecutor, mCallback);
+            fail("Duplicate create should've thrown an exception");
+        } catch (IllegalStateException e) {
+            // Succeed
+        }
+    }
+
+    public void testClose() throws Exception {
+        mGroupCallSession.close();
+
+        // Make sure we can't use it anymore
+        try {
+            mGroupCallSession.startGroupCall(mCallbackExecutor, 0, new int[1], new int[1],
+                    new GroupCallCallback());
+            fail("GroupCall session should not be usable after close");
+        } catch (IllegalStateException e) {
+            // Succeed
+        }
+
+        // Make sure that the middleware got the call to close
+        List<List<Object>> closeCalls = getMiddlewareCalls(CtsGroupCallService.METHOD_CLOSE);
+        assertEquals(1, closeCalls.size());
+    }
+
+    public void testErrorDelivery() throws Exception {
+        mMiddlewareControl.forceErrorCode(
+                MbmsErrors.GeneralErrors.ERROR_MIDDLEWARE_TEMPORARILY_UNAVAILABLE);
+        mGroupCallSession.startGroupCall(mCallbackExecutor, 0, new int[1], new int[1],
+                new GroupCallCallback());
+        assertEquals(MbmsErrors.GeneralErrors.ERROR_MIDDLEWARE_TEMPORARILY_UNAVAILABLE,
+                mCallback.waitOnError().arg1);
+    }
+
+    public void testCallbacks() throws Exception {
+        List<Integer> expectCurrentSais = Arrays.asList(10, 14, 17);
+        List<List<Integer>> expectAvailableSais = new ArrayList<List<Integer>>() {{
+            add(expectCurrentSais);
+            add(Arrays.asList(11, 15, 17));
+        }};
+        mMiddlewareControl.fireAvailableSaisUpdated(expectCurrentSais, expectAvailableSais);
+        SomeArgs callbackResult = mCallback.waitOnAvailableSaisUpdatedCalls();
+        assertEquals(callbackResult.arg1, expectCurrentSais);
+        assertEquals(callbackResult.arg2, expectAvailableSais);
+
+        String interfaceName = "TEST";
+        int index = 10;
+        mMiddlewareControl.fireServiceInterfaceAvailable(interfaceName, index);
+        callbackResult = mCallback.waitOnServiceInterfaceAvailableCalls();
+        assertEquals(interfaceName, callbackResult.arg1);
+        assertEquals(index, callbackResult.arg2);
+    }
+}
diff --git a/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallTest.java b/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallTest.java
new file mode 100644
index 0000000..7c5ac45
--- /dev/null
+++ b/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallTest.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.telephony.embms.cts;
+
+import android.annotation.Nullable;
+import android.telephony.cts.embmstestapp.CtsGroupCallService;
+import android.telephony.mbms.GroupCallCallback;
+import android.telephony.mbms.MbmsErrors;
+import android.telephony.mbms.GroupCall;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+public class MbmsGroupCallTest extends MbmsGroupCallTestBase {
+    private class TestGroupCallCallback extends GroupCallCallback {
+        private final BlockingQueue<SomeArgs> mErrorCalls = new LinkedBlockingQueue<>();
+        private final BlockingQueue<SomeArgs> mGroupCallStateChangedCalls=
+                new LinkedBlockingQueue<>();
+        private final BlockingQueue<SomeArgs> mBroadcastSignalStrengthUpdatedCalls =
+                new LinkedBlockingQueue<>();
+
+        @Override
+        public void onError(int errorCode, @Nullable String message) {
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = errorCode;
+            args.arg2 = message;
+            mErrorCalls.add(args);
+        }
+
+        @Override
+        public void onGroupCallStateChanged(int state, int reason) {
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = state;
+            args.arg2 = reason;
+            mGroupCallStateChangedCalls.add(args);
+        }
+
+        @Override
+        public void onBroadcastSignalStrengthUpdated(int signalStrength) {
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = signalStrength;
+            mBroadcastSignalStrengthUpdatedCalls.add(args);
+        }
+
+        public SomeArgs waitOnError() {
+            try {
+                return mErrorCalls.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                return null;
+            }
+        }
+
+        public SomeArgs waitOnGroupCallStateChanged() {
+            try {
+                return mGroupCallStateChangedCalls.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                return null;
+            }
+        }
+
+        public SomeArgs waitOnBroadcastSignalStrengthUpdated() {
+            try {
+                return mBroadcastSignalStrengthUpdatedCalls.poll(
+                        ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                return null;
+            }
+        }
+    }
+
+    private static final long TMGI = 568734963245L;
+    private static final int[] SAI_ARRAY = new int[]{16, 24, 46, 76};
+    private static final int[] FREQUENCY_ARRAY = new int[]{2075, 2050, 1865};
+
+    private TestGroupCallCallback mGroupCallCallback =
+            new TestGroupCallCallback();
+
+    public void testStartGroupCall() throws Exception {
+        GroupCall groupCall = mGroupCallSession.startGroupCall(mCallbackExecutor,
+                TMGI, SAI_ARRAY, FREQUENCY_ARRAY, mGroupCallCallback);
+        assertNotNull(groupCall);
+        assertEquals(TMGI, groupCall.getTmgi());
+
+        SomeArgs args = mGroupCallCallback.waitOnGroupCallStateChanged();
+        assertEquals(GroupCall.STATE_STARTED, args.arg1);
+        assertEquals(GroupCall.REASON_BY_USER_REQUEST, args.arg2);
+
+        List<List<Object>> startGroupCallCalls =
+                getMiddlewareCalls(CtsGroupCallService.METHOD_START_GROUP_CALL);
+        assertEquals(1, startGroupCallCalls.size());
+        List<Object> startGroupCallCall = startGroupCallCalls.get(0);
+        assertEquals(TMGI, startGroupCallCall.get(2));
+        assertArrayEquals(SAI_ARRAY, (int[]) startGroupCallCall.get(3));
+        assertArrayEquals(FREQUENCY_ARRAY, (int[]) startGroupCallCall.get(4));
+    }
+
+    public void testUpdateGroupCall() throws Exception {
+        GroupCall groupCall = mGroupCallSession.startGroupCall(mCallbackExecutor,
+                TMGI, SAI_ARRAY, FREQUENCY_ARRAY, mGroupCallCallback);
+        int[] newSais = new int[]{16};
+        int[] newFreqs = new int[]{2075};
+        groupCall.updateGroupCall(newSais, newFreqs);
+
+        List<List<Object>> updateGroupCallCalls =
+                getMiddlewareCalls(CtsGroupCallService.METHOD_UPDATE_GROUP_CALL);
+        assertEquals(1, updateGroupCallCalls.size());
+        List<Object> updateGroupCallCall = updateGroupCallCalls.get(0);
+        assertEquals(TMGI, updateGroupCallCall.get(2));
+        assertArrayEquals(newSais, (int[]) updateGroupCallCall.get(3));
+        assertArrayEquals(newFreqs, (int[]) updateGroupCallCall.get(4));
+    }
+
+    public void testStopGroupCall() throws Exception {
+        GroupCall groupCall = mGroupCallSession.startGroupCall(mCallbackExecutor,
+                TMGI, SAI_ARRAY, FREQUENCY_ARRAY, mGroupCallCallback);
+        groupCall.close();
+        List<List<Object>> stopGroupCallCalls =
+                getMiddlewareCalls(CtsGroupCallService.METHOD_STOP_GROUP_CALL);
+        assertEquals(1, stopGroupCallCalls.size());
+        assertEquals(TMGI, stopGroupCallCalls.get(0).get(2));
+    }
+
+    public void testGroupCallCallbacks() throws Exception {
+        mGroupCallSession.startGroupCall(mCallbackExecutor,
+                TMGI, SAI_ARRAY, FREQUENCY_ARRAY, mGroupCallCallback);
+        mMiddlewareControl.fireErrorOnGroupCall(MbmsErrors.GeneralErrors.ERROR_IN_E911,
+                MbmsGroupCallTest.class.getSimpleName());
+        SomeArgs groupCallErrorArgs = mGroupCallCallback.waitOnError();
+        assertEquals(MbmsErrors.GeneralErrors.ERROR_IN_E911, groupCallErrorArgs.arg1);
+        assertEquals(MbmsGroupCallTest.class.getSimpleName(), groupCallErrorArgs.arg2);
+
+        int broadcastSignalStrength = 3;
+        mMiddlewareControl.fireBroadcastSignalStrengthUpdated(broadcastSignalStrength);
+        assertEquals(broadcastSignalStrength,
+                mGroupCallCallback.waitOnBroadcastSignalStrengthUpdated().arg1);
+    }
+
+    public void testStartGroupCallFailure() throws Exception {
+        mMiddlewareControl.forceErrorCode(
+                MbmsErrors.GeneralErrors.ERROR_MIDDLEWARE_TEMPORARILY_UNAVAILABLE);
+        mGroupCallSession.startGroupCall(mCallbackExecutor,
+                TMGI, SAI_ARRAY, FREQUENCY_ARRAY, mGroupCallCallback);
+        assertEquals(MbmsErrors.GeneralErrors.ERROR_MIDDLEWARE_TEMPORARILY_UNAVAILABLE,
+                mCallback.waitOnError().arg1);
+    }
+
+    private void assertArrayEquals(int[] expected, int[] actual) {
+        assertEquals(expected.length, actual.length);
+        for (int i = 0; i < expected.length; i++) {
+            if (expected[i] != actual[i]) {
+                throw new AssertionError("Arrays differ at element " + i
+                        + " -- expected: " + Arrays.toString(expected) + "; actual: "
+                        + Arrays.toString(actual));
+            }
+        }
+    }
+}
diff --git a/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallTestBase.java b/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallTestBase.java
new file mode 100644
index 0000000..ba51e56
--- /dev/null
+++ b/tests/tests/telephony/src/android/telephony/embms/cts/MbmsGroupCallTestBase.java
@@ -0,0 +1,169 @@
+package android.telephony.embms.cts;
+
+import android.annotation.Nullable;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.telephony.MbmsGroupCallSession;
+import android.telephony.cts.embmstestapp.CtsGroupCallService;
+import android.telephony.cts.embmstestapp.ICtsGroupCallMiddlewareControl;
+import android.telephony.mbms.MbmsGroupCallSessionCallback;
+import android.test.InstrumentationTestCase;
+
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+public class MbmsGroupCallTestBase extends InstrumentationTestCase {
+    protected static final int ASYNC_TIMEOUT = 10000;
+
+    protected static class TestCallback extends MbmsGroupCallSessionCallback {
+        private final BlockingQueue<SomeArgs> mErrorCalls = new LinkedBlockingQueue<>();
+        private final BlockingQueue<SomeArgs> mOnAvailableSaisUpdatedCalls =
+                new LinkedBlockingQueue<>();
+        private final BlockingQueue<SomeArgs> mOnServiceInterfaceAvailableCalls =
+                new LinkedBlockingQueue<>();
+        private final BlockingQueue<SomeArgs> mMiddlewareReadyCalls = new LinkedBlockingQueue<>();
+        private int mNumErrorCalls = 0;
+
+        @Override
+        public void onError(int errorCode, @Nullable String message) {
+            mNumErrorCalls += 1;
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = errorCode;
+            args.arg2 = message;
+            mErrorCalls.add(args);
+        }
+
+        @Override
+        public void onMiddlewareReady() {
+            mMiddlewareReadyCalls.add(SomeArgs.obtain());
+        }
+
+        @Override
+        public void onAvailableSaisUpdated(List<Integer> currentSais,
+                List<List<Integer>> availableSais) {
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = currentSais;
+            args.arg2 = availableSais;
+            mOnAvailableSaisUpdatedCalls.add(args);
+        }
+
+        @Override
+        public void onServiceInterfaceAvailable(String interfaceName, int index) {
+            SomeArgs args = SomeArgs.obtain();
+            args.arg1 = interfaceName;
+            args.arg2 = index;
+            mOnServiceInterfaceAvailableCalls.add(args);
+        }
+
+        public SomeArgs waitOnError() {
+            try {
+                return mErrorCalls.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                return null;
+            }
+        }
+
+        public SomeArgs waitOnAvailableSaisUpdatedCalls() {
+            try {
+                return mOnAvailableSaisUpdatedCalls.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                return null;
+            }
+        }
+
+        public SomeArgs waitOnServiceInterfaceAvailableCalls() {
+            try {
+                return mOnServiceInterfaceAvailableCalls.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                return null;
+            }
+        }
+
+        public boolean waitOnMiddlewareReady() {
+            try {
+                return mMiddlewareReadyCalls.poll(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS) != null;
+            } catch (InterruptedException e) {
+                return false;
+            }
+        }
+
+        public int getNumErrorCalls() {
+            return mNumErrorCalls;
+        }
+    }
+
+    Context mContext;
+    HandlerThread mHandlerThread;
+    Executor mCallbackExecutor;
+    ICtsGroupCallMiddlewareControl mMiddlewareControl;
+    MbmsGroupCallSession mGroupCallSession;
+    TestCallback mCallback = new TestCallback();
+
+    @Override
+    public void setUp() throws Exception {
+        mContext = getInstrumentation().getContext();
+        mHandlerThread = new HandlerThread("EmbmsCtsTestWorker");
+        mHandlerThread.start();
+        mCallbackExecutor = (new Handler(mHandlerThread.getLooper()))::post;
+        mCallback = new TestCallback();
+        getControlBinder();
+        setupGroupCallSession();
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        mHandlerThread.quit();
+        mGroupCallSession.close();
+        mMiddlewareControl.reset();
+    }
+
+    private void setupGroupCallSession() throws Exception {
+        mGroupCallSession = MbmsGroupCallSession.create(
+                mContext, mCallbackExecutor, mCallback);
+        assertNotNull(mGroupCallSession);
+        assertTrue(mCallback.waitOnMiddlewareReady());
+        assertEquals(0, mCallback.getNumErrorCalls());
+        List initializeCall = (List) mMiddlewareControl.getGroupCallSessionCalls().get(0);
+        assertEquals(CtsGroupCallService.METHOD_INITIALIZE, initializeCall.get(0));
+    }
+
+    private void getControlBinder() throws InterruptedException {
+        Intent bindIntent = new Intent(CtsGroupCallService.CONTROL_INTERFACE_ACTION);
+        bindIntent.setComponent(CtsGroupCallService.CONTROL_INTERFACE_COMPONENT);
+        final CountDownLatch bindLatch = new CountDownLatch(1);
+
+        boolean success = mContext.bindService(bindIntent, new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                mMiddlewareControl = ICtsGroupCallMiddlewareControl.Stub.asInterface(service);
+                bindLatch.countDown();
+            }
+
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                mMiddlewareControl = null;
+            }
+        }, Context.BIND_AUTO_CREATE);
+        if (!success) {
+            fail("Failed to get control interface -- bind error");
+        }
+        bindLatch.await(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS);
+    }
+
+    protected List<List<Object>> getMiddlewareCalls(String methodName) throws RemoteException {
+        return ((List<List<Object>>) mMiddlewareControl.getGroupCallSessionCalls()).stream()
+                .filter((elem) -> elem.get(0).equals(methodName))
+                .collect(Collectors.toList());
+    }
+}
\ No newline at end of file
diff --git a/tests/tests/util/src/android/util/cts/StrictJarFileTest.java b/tests/tests/util/src/android/util/cts/StrictJarFileTest.java
index 3c18df7..2bf9b1f 100644
--- a/tests/tests/util/src/android/util/cts/StrictJarFileTest.java
+++ b/tests/tests/util/src/android/util/cts/StrictJarFileTest.java
@@ -25,22 +25,22 @@
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
+import android.system.ErrnoException;
+import android.system.Os;
 import android.system.OsConstants;
 import android.util.jar.StrictJarFile;
 
-import libcore.io.IoBridge;
-import libcore.io.Streams;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileDescriptor;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.zip.ZipEntry;
@@ -91,8 +91,8 @@
     @Test
     public void testConstructor_FD() throws Exception {
         copyFile(JAR_1);
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, JAR_1).getAbsolutePath(), OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, JAR_1).getAbsolutePath());
         StrictJarFile jarFile = new StrictJarFile(fd);
         jarFile.close();
     }
@@ -108,8 +108,8 @@
     @Test
     public void testIteration_FD() throws Exception {
         copyFile(JAR_1);
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, JAR_1).getAbsolutePath(), OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, JAR_1).getAbsolutePath());
         StrictJarFile jarFile = new StrictJarFile(fd);
         checkIteration(jarFile);
     }
@@ -136,8 +136,7 @@
         assertEquals(4, ze.getSize());
         assertEquals(ZipEntry.DEFLATED, ze.getMethod());
         assertEquals(6, ze.getCompressedSize());
-        assertEquals("Blah", new String(Streams.readFully(jarFile.getInputStream(ze)),
-                Charset.forName("UTF-8")));
+        assertEquals("Blah", readUtf8String(jarFile.getInputStream(ze)));
 
         assertTrue(entries.containsKey("foo/"));
         assertTrue(entries.containsKey("foo/bar/"));
@@ -159,8 +158,8 @@
     @Test
     public void testFindEntry_FD() throws Exception {
         copyFile(JAR_1);
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, JAR_1).getAbsolutePath(), OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, JAR_1).getAbsolutePath());
         StrictJarFile jarFile = new StrictJarFile(fd);
         checkFindEntry(jarFile);
     }
@@ -173,8 +172,7 @@
         assertEquals(4, ze.getSize());
         assertEquals(ZipEntry.DEFLATED, ze.getMethod());
         assertEquals(6, ze.getCompressedSize());
-        assertEquals("Blah", new String(Streams.readFully(jarFile.getInputStream(ze)),
-                Charset.forName("UTF-8")));
+        assertEquals("Blah", readUtf8String(jarFile.getInputStream(ze)));
     }
 
     @Test
@@ -188,8 +186,8 @@
     @Test
     public void testGetManifest_FD() throws Exception {
         copyFile(JAR_1);
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, JAR_1).getAbsolutePath(), OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, JAR_1).getAbsolutePath());
         StrictJarFile jarFile = new StrictJarFile(fd);
         checkGetManifest(jarFile);
     }
@@ -211,9 +209,8 @@
     @Test
     public void testJarSigning_wellFormed_FD() throws IOException {
         copyFile("Integrate.jar");
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, "Integrate.jar").getAbsolutePath(),
-                        OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, "Integrate.jar").getAbsolutePath());
         StrictJarFile jarFile = new StrictJarFile(fd);
         checkJarSigning_wellFormed(jarFile);
     }
@@ -241,9 +238,8 @@
     @Test
     public void testJarSigning_fudgedEntry_FD() throws IOException {
         copyFile("Integrate.jar");
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, "Integrate.jar").getAbsolutePath(),
-                        OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, "Integrate.jar").getAbsolutePath());
         StrictJarFile jarFile = new StrictJarFile(fd);
         checkJarSigning_fudgedEntry(jarFile);
     }
@@ -272,9 +268,8 @@
     @Test
     public void testJarSigning_modifiedClass_FD() throws IOException {
         copyFile("Modified_Class.jar");
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, "Modified_Class.jar").getAbsolutePath(),
-                        OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, "Modified_Class.jar").getAbsolutePath());
         StrictJarFile jarFile = new StrictJarFile(fd);
         checkJarSigning_modifiedClass(jarFile);
     }
@@ -340,9 +335,8 @@
 
     private void verifyThrowsOnInitFD(String name) throws Exception {
         copyFile(name);
-        FileDescriptor fd = IoBridge.open(
-                new File(mResourcesFile, name).getAbsolutePath(),
-                        OsConstants.O_RDONLY);
+        FileDescriptor fd = createReadOnlyFileDescriptor(
+                new File(mResourcesFile, name).getAbsolutePath());
         try {
             new StrictJarFile(fd);
             fail();
@@ -350,6 +344,25 @@
         }
     }
 
+    private static FileDescriptor createReadOnlyFileDescriptor(String path) throws IOException {
+        final int mode = 0;
+        try {
+            return Os.open(path, OsConstants.O_RDONLY, mode);
+        } catch (ErrnoException e) {
+            throw new IOException(e);
+        }
+    }
+
+    private static String readUtf8String(InputStream inputStream) throws IOException {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream(128);
+        byte[] readBuffer = new byte[128];
+        int byteCount;
+        while ((byteCount = inputStream.read(readBuffer)) != -1) {
+            baos.write(readBuffer, 0, byteCount);
+        }
+        return new String(baos.toByteArray(), StandardCharsets.UTF_8);
+    }
+
     private File copyFile(String file) {
         File dest = new File(mResourcesFile.toString() + "/" + file);
 
diff --git a/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java b/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
index 68d944b..2996c76 100644
--- a/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
+++ b/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
@@ -69,6 +69,7 @@
     public static final String STOP_LOADING_URL = "webkit/test_stop_loading.html";
     public static final String BLANK_TAG_URL = "webkit/blank_tag.html";
     public static final String PAGE_WITH_LINK_URL = "webkit/page_with_link.html";
+    public static final String URL_IN_PAGE_WITH_LINK = "http://foo.com/";
     // Not a real page, just triggers a 404 response.
     public static final String NON_EXISTENT_PAGE_URL = "webkit/generate_404.html";
     public static final String BAD_IMAGE_PAGE_URL = "webkit/test_bad_image_url.html";
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 58e59e5..ef96a70 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -137,6 +137,7 @@
 
         final WebView childWebView = mOnUiThread.createWebView();
 
+        WebViewOnUiThread childWebViewOnUiThread = new WebViewOnUiThread(this, childWebView);
         mOnUiThread.setWebChromeClient(new WebChromeClient() {
             @Override
             public boolean onCreateWindow(
@@ -152,21 +153,26 @@
                 return true;
             }
         });
-        mOnUiThread.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.BLANK_TAG_URL));
+        {
+          final int childCallCount = childWebViewClient.getShouldOverrideUrlLoadingCallCount();
+          mOnUiThread.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.BLANK_TAG_URL));
 
-        new PollingCheck(TEST_TIMEOUT) {
-            @Override
-            protected boolean check() {
-                return childWebViewClient.hasOnPageFinishedCalled();
-            }
-        }.run();
-        assertEquals(mWebServer.getAssetUrl(TestHtmlConstants.PAGE_WITH_LINK_URL),
-                childWebViewClient.getLastShouldOverrideUrl());
+          new PollingCheck(TEST_TIMEOUT) {
+              @Override
+              protected boolean check() {
+                  return childWebViewClient.hasOnPageFinishedCalled();
+              }
+          }.run();
+          new PollingCheck(TEST_TIMEOUT) {
+              @Override
+              protected boolean check() {
+                  return childWebViewClient.getShouldOverrideUrlLoadingCallCount() > childCallCount;
+              }
+          }.run();
+          assertEquals(mWebServer.getAssetUrl(TestHtmlConstants.PAGE_WITH_LINK_URL),
+                  childWebViewClient.getLastShouldOverrideUrl());
+        }
 
-        // Now test a navigation within the page
-        //TODO(hush) Enable this portion when b/12804986 is fixed.
-        /*
-        WebViewOnUiThread childWebViewOnUiThread = new WebViewOnUiThread(this, childWebView);
         final int childCallCount = childWebViewClient.getShouldOverrideUrlLoadingCallCount();
         final int mainCallCount = mainWebViewClient.getShouldOverrideUrlLoadingCallCount();
         clickOnLinkUsingJs("link", childWebViewOnUiThread);
@@ -177,8 +183,8 @@
             }
         }.run();
         assertEquals(mainCallCount, mainWebViewClient.getShouldOverrideUrlLoadingCallCount());
-        assertEquals(TEST_URL, childWebViewClient.getLastShouldOverrideUrl());
-        */
+        assertEquals(
+            TestHtmlConstants.URL_IN_PAGE_WITH_LINK, childWebViewClient.getLastShouldOverrideUrl());
     }
 
     private void clickOnLinkUsingJs(final String linkId, WebViewOnUiThread webViewOnUiThread) {