Merge "Update Cts Verifier test to reflect new Settings location" into oreo-cts-dev
am: ea0ae8883f

Change-Id: I744fa8f76c7c2973a84c11e6a2c2988bbf946d81
diff --git a/CtsCoverage.mk b/CtsCoverage.mk
index c4536f6..aeef125 100644
--- a/CtsCoverage.mk
+++ b/CtsCoverage.mk
@@ -84,12 +84,10 @@
 cts-combined-xml-coverage : $(cts-combined-xml-coverage-report)
 
 # Put the test coverage report in the dist dir if "cts" is among the build goals.
-ifneq ($(filter cts, $(MAKECMDGOALS)),)
-  $(call dist-for-goals, cts, $(cts-test-coverage-report):cts-test-coverage-report.html)
-  $(call dist-for-goals, cts, $(cts-verifier-coverage-report):cts-verifier-coverage-report.html)
-  $(call dist-for-goals, cts, $(cts-combined-coverage-report):cts-combined-coverage-report.html)
-  $(call dist-for-goals, cts, $(cts-combined-xml-coverage-report):cts-combined-coverage-report.xml)
-endif
+$(call dist-for-goals, cts, $(cts-test-coverage-report):cts-test-coverage-report.html)
+$(call dist-for-goals, cts, $(cts-verifier-coverage-report):cts-verifier-coverage-report.html)
+$(call dist-for-goals, cts, $(cts-combined-coverage-report):cts-combined-coverage-report.html)
+$(call dist-for-goals, cts, $(cts-combined-xml-coverage-report):cts-combined-coverage-report.xml)
 
 # Arguments;
 #  1 - Name of the report printed out on the screen
@@ -98,7 +96,7 @@
 define generate-coverage-report
 	$(hide) mkdir -p $(dir $@)
 	$(hide) $(PRIVATE_CTS_API_COVERAGE_EXE) -d $(PRIVATE_DEXDEPS_EXE) -a $(PRIVATE_API_XML_DESC) -f $(3) -o $@ $(2)
-	@ echo $(1): file://$(ANDROID_BUILD_TOP)/$@
+	@ echo $(1): file://$$(cd $(dir $@); pwd)/$(notdir $@)
 endef
 
 # Reset temp vars
diff --git a/apps/CameraITS/tests/scene0/test_metadata.py b/apps/CameraITS/tests/scene0/test_metadata.py
index 752e02b..69ed19d 100644
--- a/apps/CameraITS/tests/scene0/test_metadata.py
+++ b/apps/CameraITS/tests/scene0/test_metadata.py
@@ -60,8 +60,8 @@
     check('md.has_key("android.sensor.rollingShutterSkew")')
     check('md["android.sensor.rollingShutterSkew"] is not None')
     if manual_sensor:
-        check('md["android.sensor.rollingShutterSkew"] > 0')
-        check('md["android.sensor.frameDuration"] > 0')
+        check('md["android.sensor.frameDuration"] > '
+              'md["android.sensor.rollingShutterSkew"] > 0')
 
     # Test: timestampSource must be a valid value.
     check('props.has_key("android.sensor.info.timestampSource")')
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index 022a0d2..86c3e77 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -58,16 +58,15 @@
                   criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
                         10, 0.03))
 
-# Constants to convert between different units (for clarity).
+# Constants to convert between different time units (for clarity).
 SEC_TO_NSEC = 1000*1000*1000.0
 SEC_TO_MSEC = 1000.0
 MSEC_TO_NSEC = 1000*1000.0
 MSEC_TO_SEC = 1/1000.0
 NSEC_TO_SEC = 1/(1000*1000*1000.0)
 NSEC_TO_MSEC = 1/(1000*1000.0)
-CM_TO_M = 1/100.0
 
-# PASS/FAIL thresholds.
+# Pass/fail thresholds.
 THRESH_MAX_CORR_DIST = 0.005
 THRESH_MAX_SHIFT_MS = 1
 THRESH_MIN_ROT = 0.001
@@ -77,10 +76,6 @@
 FACING_BACK = 1
 FACING_EXTERNAL = 2
 
-# Chart distance
-CHART_DISTANCE = 25  # cm
-
-
 def main():
     """Test if image and motion sensor events are well synchronized.
 
@@ -301,17 +296,14 @@
         # p0's shape is N * 1 * 2
         mask = (p0[:,0,1] >= ymin) & (p0[:,0,1] <= ymax)
         p0_filtered = p0[mask]
-        num_features = len(p0_filtered)
-        if num_features < MIN_FEATURE_PTS:
+        if len(p0_filtered) < MIN_FEATURE_PTS:
             print "Not enough feature points in frame", i
             print "Need at least %d features, got %d" % (
-                    MIN_FEATURE_PTS, num_features)
-            assert 0
-        else:
-            print "Number of features in frame %d is %d" % (i, num_features)
-        p1, st, _ = cv2.calcOpticalFlowPyrLK(gframe0, gframe1, p0_filtered,
-                                             None, **LK_PARAMS)
-        tform = procrustes_rotation(p0_filtered[st == 1], p1[st == 1])
+                    MIN_FEATURE_PTS, len(p0_filtered))
+            assert(0)
+        p1,st,_ = cv2.calcOpticalFlowPyrLK(gframe0, gframe1, p0_filtered, None,
+                **LK_PARAMS)
+        tform = procrustes_rotation(p0_filtered[st==1], p1[st==1])
         if facing == FACING_BACK:
             rot = -math.atan2(tform[0, 1], tform[0, 0])
         elif facing == FACING_FRONT:
@@ -397,9 +389,8 @@
         s,e,_,_,_ = cam.do_3a(get_results=True, do_af=False)
         req = its.objects.manual_capture_request(s, e)
         fps = 30
-        req["android.lens.focusDistance"] = 1 / (CHART_DISTANCE * CM_TO_M)
         req["android.control.aeTargetFpsRange"] = [fps, fps]
-        req["android.sensor.frameDuration"] = int(1000.0/fps * MSEC_TO_NSEC)
+        req["android.sensor.frameDuration"] = int(1000.0/fps * MSEC_TO_NSEC);
         print "Capturing %dx%d with sens. %d, exp. time %.1fms" % (
                 W, H, s, e*NSEC_TO_MSEC)
         caps = cam.do_capture([req]*N, fmt)
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk
index 2dd5f23..e9a5691 100644
--- a/apps/CtsVerifier/Android.mk
+++ b/apps/CtsVerifier/Android.mk
@@ -40,6 +40,8 @@
                                compatibility-device-util \
                                platform-test-annotations
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_PACKAGE_NAME := CtsVerifier
 
 LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni \
@@ -71,7 +73,6 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 LOCAL_SRC_FILES := \
     $(call java-files-in, src/com/android/cts/verifier) \
-    $(call java-files-in, src/com/android/cts/verifier/backup) \
     $(call all-Iaidl-files-under, src)
 
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4 \
@@ -147,8 +148,6 @@
 		$(hide) $(ACP) -fpr $(HOST_OUT)/CameraITS $(verifier-dir)
 		$(hide) cd $(cts-dir) && zip -rq $(verifier-dir-name) $(verifier-dir-name)
 
-ifneq ($(filter cts, $(MAKECMDGOALS)),)
-  $(call dist-for-goals, cts, $(verifier-zip):$(verifier-zip-name))
-endif
+$(call dist-for-goals, cts, $(verifier-zip):$(verifier-zip-name))
 
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 2964ee9..ee9e0f3 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -18,7 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.android.cts.verifier"
       android:versionCode="5"
-      android:versionName="8.0_r2">
+      android:versionName="8.0_r1">
 
     <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="26"/>
 
@@ -2716,6 +2716,17 @@
                 android:value="android.software.live_tv" />
         </activity>
 
+        <activity android:name=".tv.MicrophoneDeviceTestActivity"
+                  android:label="@string/tv_microphone_device_test">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_tv" />
+            <meta-data android:name="test_required_features"
+                       android:value="android.software.leanback" />
+        </activity>
+
         <activity android:name=".screenpinning.ScreenPinningTestActivity"
             android:label="@string/screen_pinning_test">
             <intent-filter>
diff --git a/apps/CtsVerifier/jni/verifier/Android.mk b/apps/CtsVerifier/jni/verifier/Android.mk
index 1e43211..42e2d26 100644
--- a/apps/CtsVerifier/jni/verifier/Android.mk
+++ b/apps/CtsVerifier/jni/verifier/Android.mk
@@ -32,5 +32,7 @@
 LOCAL_SHARED_LIBRARIES := liblog \
 		libnativehelper_compat_libc++
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 43407b1..8400d39 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -2867,7 +2867,7 @@
     <string name="disallow_remove_user">Disallow remove user</string>
     <string name="disallow_remove_user_action">Removing other users</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\"). You may not be able to observe a support dialog in the latter case.</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>
     <string name="disallow_share_location_action">Turning on location sharing</string>
     <string name="disallow_uninstall_apps">Disallow uninstall apps</string>
@@ -3420,6 +3420,35 @@
     2) You should see the text \"Cts App-Link Text\".\n
     </string>
 
+    <string name="tv_microphone_device_test">Microphone device test</string>
+    <string name="tv_microphone_device_test_info">
+    This test checks if InputDevice.hasMicrophone of the Media API reports a
+    correct value on every input device (including remote controls).
+    </string>
+    <string name="tv_microphone_device_test_prep_question">
+    Before continuing, please make sure that you pair all primary input
+    devices intended to be used by the device, including bluetooth
+    remotes and companion remote-control apps such as the Android TV Remote Control.
+    Have you paired every primary input device with the device under test (DUT)?
+    </string>
+    <string name="tv_microphone_device_test_mic_question">
+    Does input device \"%1$s\" have a microphone?
+    </string>
+    <string name="tv_microphone_device_test_negative_mismatch">
+    InputDevice.hasMicrophone reports that this input device DOES have a
+    microphone whereas you selected that it does not.  Please correct it by
+    declaring \"audio.mic = 0\" in the device\'s input device configuration
+    (.idc) file.
+    </string>
+    <string name="tv_microphone_device_test_positive_mismatch">
+    InputDevice.hasMicrophone reports that this input device does NOT have a
+    microphone whereas you selected that it does.  Please correct it by
+    declaring \"audio.mic = 1\" in the device\'s input device configuration
+    (.idc) file and make sure that relevant files such as key layout (.kl)
+    and key character map (.kcm) files are found by the system accordingly.
+    </string>
+    <string name="tv_microphone_device_test_no_input_devices">No input devices found.</string>
+
     <string name="overlay_view_text">Overlay View Dummy Text</string>
     <string name="custom_rating">Example of input app specific custom rating.</string>
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java
index 52b3dee..4c8204f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java
@@ -100,6 +100,7 @@
                 TestSensorOperation.createOperation(environment, 100 /* event count */);
         verifyMeasurements.addVerification(new MeanVerification(
                 expectations,
+                new float[]{1.95f, 1.95f, 1.95f} /* m / s^2 */,
                 new float[]{1.95f, 1.95f, 1.95f} /* m / s^2 */));
         verifyMeasurements.execute(getCurrentTestNode());
         return null;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/MicrophoneDeviceTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MicrophoneDeviceTestActivity.java
new file mode 100644
index 0000000..eca02c1
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/MicrophoneDeviceTestActivity.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.verifier.tv;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.hardware.input.InputManager;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.InputDevice;
+import android.view.View;
+import android.widget.Toast;
+
+import com.android.cts.verifier.R;
+
+/**
+ * Tests for verifying that all input devices report correct hasMicrophone() states.
+ */
+@SuppressLint("NewApi")
+public class MicrophoneDeviceTestActivity extends TvAppVerifierActivity
+        implements View.OnClickListener {
+    private static final String TAG = "MicrophoneDeviceTestActivity";
+    private static final boolean PASS = true;
+
+    private InputManager mInputManager;
+    private HashMap<View, List<Object>> mInputDeviceItems;
+    private View mPreparationYesItem;
+    private View mPreparationNoItem;
+
+    @Override
+    public void onClick(View v) {
+        final View postTarget = getPostTarget();
+
+        if (containsButton(mPreparationYesItem, v)) {
+            setPassState(mPreparationYesItem, true);
+            setButtonEnabled(mPreparationNoItem, false);
+            createInputDeviceItems();
+            return;
+        } else if (containsButton(mPreparationNoItem, v)) {
+            setPassState(mPreparationYesItem, false);
+            setButtonEnabled(mPreparationNoItem, false);
+            getPassButton().setEnabled(false);
+            return;
+        } else if (mInputDeviceItems == null) {
+            return;
+        }
+
+        for (View item : mInputDeviceItems.keySet()) {
+            if (containsButton(item, v)) {
+                final List<Object> triple = mInputDeviceItems.get(item);
+                final boolean userAnswer = (boolean) triple.get(0);
+                final boolean actualAnswer = (boolean) triple.get(1);
+                final View pairedItem = (View) triple.get(2);
+
+                if (userAnswer == actualAnswer) {
+                    setPassState(userAnswer ? item : pairedItem, true);
+                    setButtonEnabled(userAnswer ? pairedItem : item, false);
+                    item.setTag(PASS); pairedItem.setTag(PASS);
+                    if (checkAllPassed()) {
+                        getPassButton().setEnabled(true);
+                    }
+                    return;
+                }
+
+                final int messageId =
+                    actualAnswer ? R.string.tv_microphone_device_test_negative_mismatch :
+                    R.string.tv_microphone_device_test_positive_mismatch;
+                Toast.makeText(this, messageId, Toast.LENGTH_LONG).show();
+                setPassState(userAnswer ? item : pairedItem, false);
+                getPassButton().setEnabled(false);
+                return;
+            }
+        }
+    }
+
+    @Override
+    protected void createTestItems() {
+        mPreparationYesItem = createUserItem(
+                R.string.tv_microphone_device_test_prep_question,
+                R.string.tv_yes, this);
+        setButtonEnabled(mPreparationYesItem, true);
+        mPreparationNoItem = createButtonItem(R.string.tv_no, this);
+        setButtonEnabled(mPreparationNoItem, true);
+    }
+
+    private void createInputDeviceItems() {
+        final Context context = MicrophoneDeviceTestActivity.this;
+        mInputManager = (InputManager) context.getSystemService(Context.INPUT_SERVICE);
+
+        final int[] inputDeviceIds = mInputManager.getInputDeviceIds();
+        mInputDeviceItems = new HashMap<View, List<Object>>();
+
+        for (int inputDeviceId : inputDeviceIds) {
+            final InputDevice inputDevice = mInputManager.getInputDevice(inputDeviceId);
+            final boolean hasMicrophone = inputDevice.hasMicrophone();
+            Log.w(TAG, "name: " + inputDevice.getName() + ", mic: " + hasMicrophone + ", virtual: "
+                  + inputDevice.isVirtual() + ", descriptor: " + inputDevice.getDescriptor());
+
+            // Skip virtual input devices such as virtual keyboards.  This does
+            // not, e.g., include com.google.android.tv.remote bluetooth connections.
+            if (inputDevice.isVirtual()) {
+                continue;
+            }
+
+            final CharSequence micQuestion =
+                getString(R.string.tv_microphone_device_test_mic_question, inputDevice.getName());
+
+            final View inputDeviceYesItem = createUserItem(micQuestion, R.string.tv_yes, this);
+            setButtonEnabled(inputDeviceYesItem, true);
+            final View inputDeviceNoItem = createButtonItem(R.string.tv_no, this);
+            setButtonEnabled(inputDeviceNoItem, true);
+            mInputDeviceItems.put(
+                inputDeviceYesItem, Arrays.asList(true, hasMicrophone, inputDeviceNoItem));
+            mInputDeviceItems.put(
+                inputDeviceNoItem, Arrays.asList(false, hasMicrophone, inputDeviceYesItem));
+        }
+
+        if (mInputDeviceItems.size() == 0) {
+            Toast.makeText(this, R.string.tv_microphone_device_test_no_input_devices,
+                           Toast.LENGTH_LONG).show();
+            getPassButton().setEnabled(true);
+        }
+    }
+
+    @Override
+    protected void setInfoResources() {
+        setInfoResources(R.string.tv_microphone_device_test,
+                R.string.tv_microphone_device_test_info, -1);
+    }
+
+    private boolean hasPassed(View item) {
+        return (item.getTag() != null) && ((Boolean) item.getTag()) == PASS;
+    }
+
+    private boolean checkAllPassed() {
+        if (mInputDeviceItems != null && mInputDeviceItems.size() > 0) {
+            for (View item : mInputDeviceItems.keySet()) {
+                if (!hasPassed(item)) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java
index d580ef8..41ab6f7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/TvAppVerifierActivity.java
@@ -91,6 +91,22 @@
     }
 
     /**
+     * Call this to create a test step where the user must perform some action.
+     */
+    protected View createUserItem(CharSequence instructionCharSequence,
+                                  int buttonTextId, View.OnClickListener l) {
+        View item = mInflater.inflate(R.layout.tv_item, mItemList, false);
+        TextView instructions = (TextView) item.findViewById(R.id.instructions);
+        instructions.setText(instructionCharSequence);
+        Button button = (Button) item.findViewById(R.id.user_action_button);
+        button.setVisibility(View.VISIBLE);
+        button.setText(buttonTextId);
+        button.setOnClickListener(l);
+        mItemList.addView(item);
+        return item;
+    }
+
+    /**
      * Call this to create a test step where the test automatically evaluates whether
      * an expected condition is satisfied.
      */
diff --git a/build/device_info_package.mk b/build/device_info_package.mk
index dcc81d3..d9d08e8 100644
--- a/build/device_info_package.mk
+++ b/build/device_info_package.mk
@@ -49,7 +49,7 @@
 
 # Generator of APK manifests.
 MANIFEST_GENERATOR_JAR := $(HOST_OUT_JAVA_LIBRARIES)/compatibility-manifest-generator.jar
-MANIFEST_GENERATOR := java -jar $(MANIFEST_GENERATOR_JAR)
+MANIFEST_GENERATOR := $(JAVA) -jar $(MANIFEST_GENERATOR_JAR)
 
 # Generate the manifest
 manifest_xml := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/AndroidManifest.xml
diff --git a/build/support_package.mk b/build/support_package.mk
index e25ba8a..83d7da9 100644
--- a/build/support_package.mk
+++ b/build/support_package.mk
@@ -22,5 +22,6 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 
+-include cts/error_prone_rules_tests.mk
 include $(BUILD_PACKAGE)
 
diff --git a/build/test_package.mk b/build/test_package.mk
index 3cec0af..2aa0852 100644
--- a/build/test_package.mk
+++ b/build/test_package.mk
@@ -20,5 +20,6 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES += platform-test-annotations
 
+-include cts/error_prone_rules_tests.mk
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
diff --git a/build/test_target_java_library.mk b/build/test_target_java_library.mk
index eb11ef7..c932c30 100644
--- a/build/test_target_java_library.mk
+++ b/build/test_target_java_library.mk
@@ -20,5 +20,6 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_STATIC_JAVA_LIBRARIES += platform-test-annotations
 
+-include cts/error_prone_rules_tests.mk
 include $(BUILD_JAVA_LIBRARY)
 
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/VintfDeviceInfo.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/VintfDeviceInfo.java
index c9a6265..468bcc1 100644
--- a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/VintfDeviceInfo.java
+++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/VintfDeviceInfo.java
@@ -45,7 +45,6 @@
         store.addResult("os_version", VintfRuntimeInfo.getOsVersion());
         store.addResult("hardware_id", VintfRuntimeInfo.getHardwareId());
         store.addResult("kernel_version", VintfRuntimeInfo.getKernelVersion());
-        store.addResult("kernel_sepolicy_version", VintfRuntimeInfo.getKernelSepolicyVersion());
         store.addResult("sepolicy_version", VintfObject.getSepolicyVersion());
 
         String[] hals = VintfObject.getHalNamesAndVersions();
diff --git a/common/device-side/util/jni/Android.mk b/common/device-side/util/jni/Android.mk
index 7b73707..8627d24 100644
--- a/common/device-side/util/jni/Android.mk
+++ b/common/device-side/util/jni/Android.mk
@@ -32,4 +32,6 @@
 LOCAL_STATIC_LIBRARIES := cpufeatures
 LOCAL_SDK_VERSION := 19
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/common/util/src/com/android/compatibility/common/util/VendorInterfaceTest.java b/common/util/src/com/android/compatibility/common/util/VendorInterfaceTest.java
index 5bcaf0c..5a448f1 100644
--- a/common/util/src/com/android/compatibility/common/util/VendorInterfaceTest.java
+++ b/common/util/src/com/android/compatibility/common/util/VendorInterfaceTest.java
@@ -26,8 +26,7 @@
  * AOSP requirement.
  * <p>
  * Test classes and test cases marked with this annotation will be included in the
- * cts-vendor-interface plan
- * by default.
+ * cts-vendor-interface plan by default.
  */
 @Retention(RetentionPolicy.RUNTIME)
 @Target({ElementType.METHOD, ElementType.TYPE})
diff --git a/error_prone_rules_tests.mk b/error_prone_rules_tests.mk
index 78cb3a0..cec29b7 100644
--- a/error_prone_rules_tests.mk
+++ b/error_prone_rules_tests.mk
@@ -16,6 +16,5 @@
 
 # Goal is to eventually merge with error_prone_rules.mk
 LOCAL_ERROR_PRONE_FLAGS:= -Xep:JUnit3TestNotRun:ERROR \
-                          -Xep:JUnitAmbiguousTestClass:ERROR \
                           -Xep:TryFailThrowable:ERROR
 
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk
index f8db5aa..18c8aec 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk
@@ -23,8 +23,9 @@
     android-support-test \
     compatibility-device-util \
     ctstestrunner \
-    ub-uiautomator \
-    legacy-android-test
+    ub-uiautomator
+
+LOCAL_JAVA_LIBRARIES := legacy-android-test
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
     ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java \
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk
index 9e6ea3e..652ebfb 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk
@@ -23,8 +23,9 @@
     android-support-test \
     compatibility-device-util \
     ctstestrunner \
-    ub-uiautomator \
-    legacy-android-test
+    ub-uiautomator
+
+LOCAL_JAVA_LIBRARIES := legacy-android-test
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
     ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
diff --git a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java b/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
index 0a1f012..231bddc 100644
--- a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
@@ -68,11 +68,19 @@
             Object[] dexElements = getDexElementsFromClassLoader((BaseDexClassLoader) loader);
             assertTrue(dexElements != null && dexElements.length > 1);
 
+            // First dex file is either the shared library or the cts instrumentation library.
             DexFile libDexFile = getDexFileFromDexElement(dexElements[0]);
             String libPath = libDexFile.getName();
-            DexFile apkDexFile = getDexFileFromDexElement(dexElements[1]);
+            // The last dex file should be the test apk file: com.android.cts.useslibrary.
+            DexFile apkDexFile = getDexFileFromDexElement(dexElements[dexElements.length - 1]);
             String apkPath = apkDexFile.getName();
+
+            // In order to ensure the collision check is executed we use the apkDexFile when
+            // constructing the test class path for duplicates.
+            // We do not use the shared libraries apks because they are compiled with a special
+            // marker which may skip the collision check (b/37777332).
             String testPath = libPath + File.pathSeparator + apkPath + File.pathSeparator + apkPath;
+
             PathClassLoader testLoader = new PathClassLoader(testPath, null);
             Object[] testDexElements = getDexElementsFromClassLoader(testLoader);
             assertTrue(testDexElements != null && testDexElements.length == 3);
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk
index 61d2493..3893b7a 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk
@@ -24,8 +24,6 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
     ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
 
-LOCAL_JAVA_RESOURCE_DIRS := $(LOCAL_PATH)/res
-
 # tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
diff --git a/hostsidetests/backup/Android.mk b/hostsidetests/backup/Android.mk
index 3ed8e99..75796a1 100644
--- a/hostsidetests/backup/Android.mk
+++ b/hostsidetests/backup/Android.mk
@@ -18,8 +18,6 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_RESOURCE_DIRS := assets/
-
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
diff --git a/hostsidetests/compilation/assets/primary.prof b/hostsidetests/compilation/assets/primary.prof
new file mode 100644
index 0000000..404089d
--- /dev/null
+++ b/hostsidetests/compilation/assets/primary.prof
Binary files differ
diff --git a/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java b/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java
index 1f5d669..2fc3e1e 100644
--- a/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java
+++ b/hostsidetests/compilation/src/android/cts/compilation/AdbRootDependentCompilationTest.java
@@ -72,8 +72,8 @@
     }
 
     private ITestDevice mDevice;
-    private File textProfileFile;
-    private byte[] initialOdexFileContents;
+    private byte[] profileBytes;
+    private File localProfileFile;
     private File apkFile;
     private boolean mCanEnableDeviceRootAccess;
 
@@ -97,19 +97,18 @@
         mDevice.uninstallPackage(APPLICATION_PACKAGE); // in case it's still installed
         mDevice.installPackage(apkFile, false);
 
-        // Write the text profile to a temporary file so that we can run profman on it to create a
-        // real profile.
-        byte[] profileBytes = ByteStreams.toByteArray(
-                getClass().getResourceAsStream("/primary.prof.txt"));
+        // Load snapshot of file contents from {@link ProfileLocation#CUR} after
+        // manually running the target application manually for a few minutes.
+        profileBytes = ByteStreams.toByteArray(getClass().getResourceAsStream("/primary.prof"));
+        localProfileFile = File.createTempFile("compilationtest", "prof");
+        Files.write(profileBytes, localProfileFile);
         assertTrue("empty profile", profileBytes.length > 0); // sanity check
-        textProfileFile = File.createTempFile("compilationtest", "prof.txt");
-        Files.write(profileBytes, textProfileFile);
     }
 
     @Override
     protected void tearDown() throws Exception {
         FileUtil.deleteFile(apkFile);
-        FileUtil.deleteFile(textProfileFile);
+        FileUtil.deleteFile(localProfileFile);
         mDevice.uninstallPackage(APPLICATION_PACKAGE);
         super.tearDown();
     }
@@ -189,7 +188,7 @@
     }
 
     /**
-     * Places the profile in the specified locations, recompiles (without -f)
+     * Places {@link #profileBytes} in the specified locations, recompiles (without -f)
      * and checks the compiler-filter in the odex file.
      *
      * @return whether the test ran (as opposed to early exit)
@@ -249,8 +248,7 @@
     }
 
     /**
-     * Copies {@link #textProfileFile} to the device and convert it to a binary profile on the
-     * client device.
+     * Copies {@link #localProfileFile} to the specified location on the client device.
      */
     private void writeProfile(ProfileLocation location) throws Exception {
         String targetPath = location.getPath();
@@ -265,34 +263,12 @@
         while (owner.startsWith(" ")) {
             owner = owner.substring(1);
         }
-
-        String targetPathTemp = targetPath + ".tmp";
-        executePush(textProfileFile.getAbsolutePath(), targetPathTemp, targetDir);
-        assertTrue("Failed to push text profile", doesFileExist(targetPathTemp));
-
-        String targetPathApk = targetPath + ".apk";
-        executePush(apkFile.getAbsolutePath(), targetPathApk, targetDir);
-        assertTrue("Failed to push APK from ", doesFileExist(targetPathApk));
-        // Run profman to create the real profile on device.
-        try {
-            String pathSpec = executeSuShellAdbCommand(1, "pm", "path", APPLICATION_PACKAGE)[0];
-            pathSpec = pathSpec.replace("package:", "");
-            assertTrue("Failed find APK " + pathSpec, doesFileExist(pathSpec));
-            executeSuShellAdbCommand(
-                "profman",
-                "--create-profile-from=" + targetPathTemp,
-                "--apk=" + pathSpec,
-                "--dex-location=" + pathSpec,
-                "--reference-profile-file=" + targetPath);
-        } catch (Exception e) {
-            assertEquals("", e.toString());
-        }
+        executePush(localProfileFile.getAbsolutePath(), targetPath, targetDir);
         executeSuShellAdbCommand(0, "chown", owner, targetPath);
         // Verify that the file was written successfully
         assertTrue("failed to create profile file", doesFileExist(targetPath));
-        String[] result = executeSuShellAdbCommand(1, "stat", "-c", "%s", targetPath);
-        assertTrue("profile " + targetPath + " is " + Integer.parseInt(result[0]) + " bytes",
-                   Integer.parseInt(result[0]) > 0);
+        assertEquals(Integer.toString(profileBytes.length),
+                executeSuShellAdbCommand(1, "stat", "-c", "%s", targetPath)[0]);
     }
 
     /**
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk b/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk
index 6454e46..f2bad22 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk
+++ b/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk
@@ -29,6 +29,8 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-v4 ctstestrunner ub-uiautomator android-support-test
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SDK_VERSION := test_current
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk
index 46d9cc0..3657e14 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk
@@ -28,6 +28,8 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner compatibility-device-util
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
diff --git a/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk
index 9afaa7a..da1ed56 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk
@@ -28,6 +28,8 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner compatibility-device-util
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
index 516e32e..ca6a9b2 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
-LOCAL_JAVA_LIBRARIES = conscrypt
+LOCAL_JAVA_LIBRARIES = conscrypt legacy-android-test
 
 LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 compatibility-device-util ctstestrunner ub-uiautomator
 
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
index 962c5f5..f73e80a 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
-LOCAL_JAVA_LIBRARIES = conscrypt
+LOCAL_JAVA_LIBRARIES = conscrypt legacy-android-test
 
 LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 compatibility-device-util ctstestrunner ub-uiautomator
 
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
index 19fd3bd..285cbc7 100644
--- a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
+++ b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
+LOCAL_JAVA_LIBRARIES := legacy-android-test cts-junit
 
 LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner android-support-test
 
diff --git a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
index 9e86d13..5b2c8be 100644
--- a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
+++ b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
+LOCAL_JAVA_LIBRARIES := cts-junit
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
index dc9e4c9..dbcfb96 100644
--- a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
+++ b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
+LOCAL_JAVA_LIBRARIES := cts-junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/incident/apps/errorsapp/jni/Android.mk b/hostsidetests/incident/apps/errorsapp/jni/Android.mk
index 7d3eb55..5101bf3 100644
--- a/hostsidetests/incident/apps/errorsapp/jni/Android.mk
+++ b/hostsidetests/incident/apps/errorsapp/jni/Android.mk
@@ -25,9 +25,6 @@
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
 
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
-
 LOCAL_SDK_VERSION := current
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/hostsidetests/jvmti/allocation-tracking/Android.mk b/hostsidetests/jvmti/allocation-tracking/Android.mk
index c5619ad..15c3e50 100644
--- a/hostsidetests/jvmti/allocation-tracking/Android.mk
+++ b/hostsidetests/jvmti/allocation-tracking/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiTrackingHostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../host_side.mk
diff --git a/hostsidetests/jvmti/allocation-tracking/jarjar-rules.txt b/hostsidetests/jvmti/allocation-tracking/jarjar-rules.txt
new file mode 100644
index 0000000..072c926
--- /dev/null
+++ b/hostsidetests/jvmti/allocation-tracking/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTestAllocationTracking@1
diff --git a/hostsidetests/jvmti/base/jni/cts_agent.cpp b/hostsidetests/jvmti/base/jni/cts_agent.cpp
index bb1e620..665a47e 100644
--- a/hostsidetests/jvmti/base/jni/cts_agent.cpp
+++ b/hostsidetests/jvmti/base/jni/cts_agent.cpp
@@ -49,7 +49,7 @@
     LOG(FATAL) << "Could not get shared jvmtiEnv";
   }
 
-  SetAllCapabilities(jvmti_env);
+  SetStandardCapabilities(jvmti_env);
   return 0;
 }
 
@@ -64,7 +64,7 @@
     LOG(FATAL) << "Could not get shared jvmtiEnv";
   }
 
-  SetAllCapabilities(jvmti_env);
+  SetStandardCapabilities(jvmti_env);
   InformMainAttach(jvmti_env, env, kMainClass, kMainClassStartup);
   return 0;
 }
diff --git a/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml b/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml
deleted file mode 100644
index a2d6ca6..0000000
--- a/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?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.
- -->
-
-<!--
- * This is a sample of how to create an app for a run-test-based JVMTI
- * test.
- -->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.jvmti.cts.run_test_{NR}">
-
-    <application android:debuggable="true">
-        <uses-library android:name="android.test.runner" />
-        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="{NR}" />
-        <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_{NR}" >
-    </instrumentation>
-</manifest>
-
diff --git a/hostsidetests/jvmti/host_side.mk b/hostsidetests/jvmti/host_side.mk
new file mode 100644
index 0000000..c865d5a
--- /dev/null
+++ b/hostsidetests/jvmti/host_side.mk
@@ -0,0 +1,45 @@
+# 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.
+
+# This file is meant to be included for every host-side test case to
+# have common build system code.
+#
+# For example:
+#
+#   LOCAL_PATH := $(call my-dir)
+#
+#   include $(CLEAR_VARS)
+#
+#   LOCAL_MODULE := CtsJvmtiRunTest902HostTestCases
+#
+#   include $(LOCAL_PATH)/../host_side.mk
+#
+
+
+ifndef LOCAL_PATH
+  $(error LOCAL_PATH not defined)
+endif
+ifndef LOCAL_MODULE
+  $(error LOCAL_MODULE not defined)
+endif
+
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
+
diff --git a/hostsidetests/jvmti/redefining/Android.mk b/hostsidetests/jvmti/redefining/Android.mk
index d0a728d..a5c0f07 100644
--- a/hostsidetests/jvmti/redefining/Android.mk
+++ b/hostsidetests/jvmti/redefining/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRedefineClassesHostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../host_side.mk
diff --git a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
index a7bd120..d68d1dd 100644
--- a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
+++ b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
@@ -342,7 +342,6 @@
              *      return-object v0
              *  .end method
             */
-            /* DISABLED Due to b/62237378
             new RedefineError(JvmtiErrors.FAILS_VERIFICATION, Transform2.class,
                     "ZGV4CjAzNQBOhefYdQRcgqmkwhWsSyzb5I3udX0SnJ44AwAAcAAAAHhWNBIAAAAAAAAAAIwCAAAN" +
                     "AAAAcAAAAAYAAACkAAAAAQAAALwAAAAAAAAAAAAAAAMAAADIAAAAAQAAAOAAAAA4AgAAAAEAAAAB" +
@@ -359,7 +358,6 @@
                     "BgAAAKQAAAADAAAAAQAAALwAAAAFAAAAAwAAAMgAAAAGAAAAAQAAAOAAAAACIAAADQAAAAABAAAE" +
                     "IAAAAgAAABgCAAADEAAAAgAAACgCAAAGIAAAAQAAADgCAAADIAAAAgAAAEgCAAABIAAAAgAAAFQC" +
                     "AAAAIAAAAQAAAH4CAAAAEAAAAQAAAIwCAAA="),
-             */
             /**
              * Base64 for this class.
              *
diff --git a/hostsidetests/jvmti/redefining/jarjar-rules.txt b/hostsidetests/jvmti/redefining/jarjar-rules.txt
new file mode 100644
index 0000000..63f7888
--- /dev/null
+++ b/hostsidetests/jvmti/redefining/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTestRedefining@1
diff --git a/hostsidetests/jvmti/run-tests/Android.mk b/hostsidetests/jvmti/run-tests/Android.mk
index 64fe597..ca07cab 100644
--- a/hostsidetests/jvmti/run-tests/Android.mk
+++ b/hostsidetests/jvmti/run-tests/Android.mk
@@ -13,5 +13,166 @@
 # limitations under the License.
 
 LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
 
+# shim classes. We use one that exposes the common functionality.
+LOCAL_SHIM_CLASSES := \
+  src/902-hello-transformation/src/art/Redefinition.java \
+  src/903-hello-tagging/src/art/Main.java \
+  src/989-method-trace-throw/src/art/Trace.java \
+
+LOCAL_SRC_FILES := $(LOCAL_SHIM_CLASSES)
+
+# Actual test classes.
+LOCAL_SRC_FILES += \
+  src/901-hello-ti-agent/src/art/Test901.java \
+  src/902-hello-transformation/src/art/Test902.java \
+  src/903-hello-tagging/src/art/Test903.java \
+  src/904-object-allocation/src/art/Test904.java \
+  src/905-object-free/src/art/Test905.java \
+  src/906-iterate-heap/src/art/Test906.java \
+  src/907-get-loaded-classes/src/art/Test907.java \
+    src/907-get-loaded-classes/src/art/Cerr.java \
+  src/908-gc-start-finish/src/art/Test908.java \
+  src/910-methods/src/art/Test910.java \
+  src/911-get-stack-trace/src/art/Test911.java \
+    src/911-get-stack-trace/src/art/AllTraces.java \
+    src/911-get-stack-trace/src/art/ControlData.java \
+    src/911-get-stack-trace/src/art/Frames.java \
+    src/911-get-stack-trace/src/art/OtherThread.java \
+    src/911-get-stack-trace/src/art/PrintThread.java \
+    src/911-get-stack-trace/src/art/Recurse.java \
+    src/911-get-stack-trace/src/art/SameThread.java \
+    src/911-get-stack-trace/src/art/ThreadListTraces.java \
+  src/912-classes/src-art/art/Test912.java \
+    src/912-classes/src-art/art/DexData.java \
+  src/913-heaps/src/art/Test913.java \
+  src/914-hello-obsolescence/src/art/Test914.java \
+  src/915-obsolete-2/src/art/Test915.java \
+  src/917-fields-transformation/src/art/Test917.java \
+  src/918-fields/src/art/Test918.java \
+  src/919-obsolete-fields/src/art/Test919.java \
+  src/920-objects/src/art/Test920.java \
+  src/922-properties/src/art/Test922.java \
+  src/923-monitors/src/art/Test923.java \
+  src/924-threads/src/art/Test924.java \
+  src/925-threadgroups/src/art/Test925.java \
+  src/926-multi-obsolescence/src/art/Test926.java \
+  src/927-timers/src/art/Test927.java \
+  src/928-jni-table/src/art/Test928.java \
+  src/930-hello-retransform/src/art/Test930.java \
+  src/931-agent-thread/src/art/Test931.java \
+  src/932-transform-saves/src/art/Test932.java \
+  src/933-misc-events/src/art/Test933.java \
+  src/940-recursive-obsolete/src/art/Test940.java \
+  src/942-private-recursive/src/art/Test942.java \
+  src/944-transform-classloaders/src/art/Test944.java \
+  src/945-obsolete-native/src/art/Test945.java \
+  src/947-reflect-method/src/art/Test947.java \
+  src/951-threaded-obsolete/src/art/Test951.java \
+  src/982-ok-no-retransform/src/art/Test982.java \
+  src/984-obsolete-invoke/src/art/Test984.java \
+  src/985-re-obsolete/src/art/Test985.java \
+  src/986-native-method-bind/src/art/Test986.java \
+  src/988-method-trace/src/art/Test988.java \
+    src/988-method-trace/src/art/Test988Intrinsics.java \
+  src/989-method-trace-throw/src/art/Test989.java \
+  src/990-field-trace/src/art/Test990.java \
+  src/991-field-trace-2/src/art/Test991.java \
+  src/992-source-data/src/art/Test992.java \
+    src/992-source-data/src/art/Target2.java \
+
+JVMTI_RUN_TEST_GENERATED_NUMBERS := \
+  901 \
+  902 \
+  903 \
+  904 \
+  905 \
+  906 \
+  907 \
+  908 \
+  910 \
+  911 \
+  912 \
+  913 \
+  914 \
+  915 \
+  917 \
+  918 \
+  919 \
+  920 \
+  922 \
+  923 \
+  924 \
+  925 \
+  926 \
+  927 \
+  928 \
+  930 \
+  931 \
+  932 \
+  933 \
+  940 \
+  942 \
+  944 \
+  945 \
+  947 \
+  951 \
+  982 \
+  984 \
+  985 \
+  986 \
+  988 \
+  989 \
+  990 \
+  991 \
+  992 \
+
+# 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)), \
+  $(filter $(DIR)%,$(LOCAL_SRC_FILES))))
+ifneq ($(sort $(LOCAL_SRC_FILES)),$(JVMTI_RUN_TEST_DIR_CHECK))
+  $(error Missing file, compare $(sort $(LOCAL_SRC_FILES)) with $(JVMTI_RUN_TEST_DIR_CHECK))
+endif
+
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
+LOCAL_MODULE := run-test-jvmti-java
+
+GENERATED_SRC_DIR := $(call local-generated-sources-dir)
+JVMTI_RUN_TEST_GENERATED_FILES := \
+  $(foreach NR,$(JVMTI_RUN_TEST_GENERATED_NUMBERS),$(GENERATED_SRC_DIR)/results.$(NR).expected.txt)
+
+define GEN_JVMTI_RUN_TEST_GENERATED_FILE
+
+GEN_INPUT := $(wildcard $(LOCAL_PATH)/src/$(1)*/expected.txt)
+ifeq (true,$(ANDROID_COMPILE_WITH_JACK))
+GEN_JACK := $(wildcard $(LOCAL_PATH)/src/$(1)*/expected_jack.diff)
+else
+GEN_JACK :=
+endif
+GEN_OUTPUT := $(GENERATED_SRC_DIR)/results.$(1).expected.txt
+$$(GEN_OUTPUT): PRIVATE_GEN_JACK := $$(GEN_JACK)
+$$(GEN_OUTPUT): $$(GEN_INPUT) $$(GEN_JACK)
+	cp $$< $$@
+ifneq (,$$(GEN_JACK))
+	(cd $$(dir $$@) && patch $$(notdir $$@)) < $$(PRIVATE_GEN_JACK)
+endif
+
+GEN_INPUT :=
+GEN_OUTPUT :=
+
+endef
+
+$(foreach NR,$(JVMTI_RUN_TEST_GENERATED_NUMBERS),\
+  $(eval $(call GEN_JVMTI_RUN_TEST_GENERATED_FILE,$(NR))))
+LOCAL_JAVA_RESOURCE_FILES := $(JVMTI_RUN_TEST_GENERATED_FILES)
+
+# Avoid linking against any @hide APIs.
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/src b/hostsidetests/jvmti/run-tests/src
new file mode 120000
index 0000000..0291142
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/src
@@ -0,0 +1 @@
+../../../../art/test
\ No newline at end of file
diff --git a/hostsidetests/jvmti/run-tests/test-902/Android.mk b/hostsidetests/jvmti/run-tests/test-902/Android.mk
index 7479ad8..4467924 100644
--- a/hostsidetests/jvmti/run-tests/test-902/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-902/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest902HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-902/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-902/jarjar-rules.txt
new file mode 100644
index 0000000..1649520
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-902/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest902@1
diff --git a/hostsidetests/jvmti/run-tests/test-903/Android.mk b/hostsidetests/jvmti/run-tests/test-903/Android.mk
index 1b67da1..74208d0 100644
--- a/hostsidetests/jvmti/run-tests/test-903/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-903/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest903HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-903/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-903/jarjar-rules.txt
new file mode 100644
index 0000000..f1a253e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-903/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest903@1
diff --git a/hostsidetests/jvmti/run-tests/test-904/Android.mk b/hostsidetests/jvmti/run-tests/test-904/Android.mk
index b814acb..bfbbfa2 100644
--- a/hostsidetests/jvmti/run-tests/test-904/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-904/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest904HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-904/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-904/jarjar-rules.txt
new file mode 100644
index 0000000..e2fe6f33
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-904/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest904@1
diff --git a/hostsidetests/jvmti/run-tests/test-905/Android.mk b/hostsidetests/jvmti/run-tests/test-905/Android.mk
index 9e58b9b..cd9234a 100644
--- a/hostsidetests/jvmti/run-tests/test-905/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-905/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest905HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-905/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-905/jarjar-rules.txt
new file mode 100644
index 0000000..9b0c5aa
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-905/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest905@1
diff --git a/hostsidetests/jvmti/run-tests/test-906/Android.mk b/hostsidetests/jvmti/run-tests/test-906/Android.mk
index 553b898..d9105ca 100644
--- a/hostsidetests/jvmti/run-tests/test-906/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-906/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest906HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-906/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-906/jarjar-rules.txt
new file mode 100644
index 0000000..9e40985
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-906/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest906@1
diff --git a/hostsidetests/jvmti/run-tests/test-907/Android.mk b/hostsidetests/jvmti/run-tests/test-907/Android.mk
index cf79d0b..12c66f2 100644
--- a/hostsidetests/jvmti/run-tests/test-907/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-907/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest907HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-907/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-907/jarjar-rules.txt
new file mode 100644
index 0000000..9c6b06f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-907/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest907@1
diff --git a/hostsidetests/jvmti/run-tests/test-908/Android.mk b/hostsidetests/jvmti/run-tests/test-908/Android.mk
index 40ef837..2879daf 100644
--- a/hostsidetests/jvmti/run-tests/test-908/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-908/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest908HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-908/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-908/jarjar-rules.txt
new file mode 100644
index 0000000..7915bff
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-908/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest908@1
diff --git a/hostsidetests/jvmti/run-tests/test-910/Android.mk b/hostsidetests/jvmti/run-tests/test-910/Android.mk
index 8cfe0a5..85334b3 100644
--- a/hostsidetests/jvmti/run-tests/test-910/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-910/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest910HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-910/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-910/jarjar-rules.txt
new file mode 100644
index 0000000..2856a08
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-910/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest910@1
diff --git a/hostsidetests/jvmti/run-tests/test-911/Android.mk b/hostsidetests/jvmti/run-tests/test-911/Android.mk
index 0906b99..445fab0 100644
--- a/hostsidetests/jvmti/run-tests/test-911/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-911/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest911HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-911/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-911/jarjar-rules.txt
new file mode 100644
index 0000000..676e1db
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-911/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest911@1
diff --git a/hostsidetests/jvmti/run-tests/test-981/Android.mk b/hostsidetests/jvmti/run-tests/test-912/Android.mk
similarity index 72%
rename from hostsidetests/jvmti/run-tests/test-981/Android.mk
rename to hostsidetests/jvmti/run-tests/test-912/Android.mk
index 4bbc20a..aa69a75 100644
--- a/hostsidetests/jvmti/run-tests/test-981/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-912/Android.mk
@@ -16,11 +16,6 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE := CtsJvmtiRunTest981HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_MODULE := CtsJvmtiRunTest912HostTestCases
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-912/AndroidTest.xml
similarity index 75%
rename from hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
rename to hostsidetests/jvmti/run-tests/test-912/AndroidTest.xml
index e6351d3..697beb2 100644
--- a/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-912/AndroidTest.xml
@@ -14,14 +14,14 @@
      limitations under the License.
 -->
 <configuration description="Config for CTS JVMTI test cases">
-    <option name="config-descriptor:metadata" key="component" value="art" />
-    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+    <target_preparer class="android.jvmti.cts.JvmtiPreparer">
         <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsJvmtiRunTest981DeviceApp.apk" />
+        <option name="test-file-name" value="CtsJvmtiRunTest912DeviceApp.apk" />
+        <option name="package-name" value="android.jvmti.cts.run_test_912" />
     </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
-        <option name="jar" value="CtsJvmtiRunTest981HostTestCases.jar" />
-        <option name="set-option" value="test-file-name:CtsJvmtiRunTest981DeviceApp.apk" />
-        <option name="set-option" value="package-name:android.jvmti.cts.run_test_981" />
+        <option name="jar" value="CtsJvmtiRunTest912HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest912DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_912" />
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-981/app/Android.mk b/hostsidetests/jvmti/run-tests/test-912/app/Android.mk
similarity index 95%
rename from hostsidetests/jvmti/run-tests/test-981/app/Android.mk
rename to hostsidetests/jvmti/run-tests/test-912/app/Android.mk
index ec8f7aa..58d4156 100644
--- a/hostsidetests/jvmti/run-tests/test-981/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-912/app/Android.mk
@@ -28,6 +28,6 @@
 LOCAL_SDK_VERSION := current
 
 # TODO: Refactor. This is the only thing every changing.
-LOCAL_PACKAGE_NAME := CtsJvmtiRunTest981DeviceApp
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest912DeviceApp
 
 include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-912/app/AndroidManifest.xml
similarity index 90%
rename from hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
rename to hostsidetests/jvmti/run-tests/test-912/app/AndroidManifest.xml
index a0e898a..d689692 100644
--- a/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
+++ b/hostsidetests/jvmti/run-tests/test-912/app/AndroidManifest.xml
@@ -16,11 +16,11 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.jvmti.cts.run_test_981">
+    package="android.jvmti.cts.run_test_912">
 
     <application android:debuggable="true">
         <uses-library android:name="android.test.runner" />
-        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="981" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="912" />
         <activity android:name="android.jvmti.JvmtiActivity" >
         </activity>
     </application>
@@ -29,7 +29,7 @@
     <instrumentation
         android:name="android.support.test.runner.AndroidJUnitRunner"
         android:label="CTS tests for JVMTI"
-        android:targetPackage="android.jvmti.cts.run_test_981" >
+        android:targetPackage="android.jvmti.cts.run_test_912" >
     </instrumentation>
 </manifest>
 
diff --git a/hostsidetests/jvmti/run-tests/test-912/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-912/jarjar-rules.txt
new file mode 100644
index 0000000..357b05e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-912/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest912@1
diff --git a/hostsidetests/jvmti/run-tests/test-913/Android.mk b/hostsidetests/jvmti/run-tests/test-913/Android.mk
index 8075fe2..3c87a22 100644
--- a/hostsidetests/jvmti/run-tests/test-913/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-913/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest913HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-913/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-913/jarjar-rules.txt
new file mode 100644
index 0000000..735418d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-913/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest913@1
diff --git a/hostsidetests/jvmti/run-tests/test-914/Android.mk b/hostsidetests/jvmti/run-tests/test-914/Android.mk
index 5f7ddee..7732cb1 100644
--- a/hostsidetests/jvmti/run-tests/test-914/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-914/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest914HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-914/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-914/jarjar-rules.txt
new file mode 100644
index 0000000..db77ad0
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-914/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest914@1
diff --git a/hostsidetests/jvmti/run-tests/test-915/Android.mk b/hostsidetests/jvmti/run-tests/test-915/Android.mk
index 2e2e438..384884a 100644
--- a/hostsidetests/jvmti/run-tests/test-915/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-915/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest915HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-915/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-915/jarjar-rules.txt
new file mode 100644
index 0000000..650ee3c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-915/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest915@1
diff --git a/hostsidetests/jvmti/run-tests/test-917/Android.mk b/hostsidetests/jvmti/run-tests/test-917/Android.mk
index 1e84675..ebf60f5 100644
--- a/hostsidetests/jvmti/run-tests/test-917/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-917/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest917HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-917/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-917/jarjar-rules.txt
new file mode 100644
index 0000000..de3b6cc
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-917/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest917@1
diff --git a/hostsidetests/jvmti/run-tests/test-918/Android.mk b/hostsidetests/jvmti/run-tests/test-918/Android.mk
index 5d6f8d0..f6ba563 100644
--- a/hostsidetests/jvmti/run-tests/test-918/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-918/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest918HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-918/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-918/jarjar-rules.txt
new file mode 100644
index 0000000..0635cae
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-918/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest918@1
diff --git a/hostsidetests/jvmti/run-tests/test-919/Android.mk b/hostsidetests/jvmti/run-tests/test-919/Android.mk
index 8916d6e..b14ab91 100644
--- a/hostsidetests/jvmti/run-tests/test-919/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-919/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest919HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-919/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-919/jarjar-rules.txt
new file mode 100644
index 0000000..69ffbde
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-919/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest919@1
diff --git a/hostsidetests/jvmti/run-tests/test-920/Android.mk b/hostsidetests/jvmti/run-tests/test-920/Android.mk
index f92ed94..80ddaa8 100644
--- a/hostsidetests/jvmti/run-tests/test-920/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-920/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest920HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-920/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-920/jarjar-rules.txt
new file mode 100644
index 0000000..a819464
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-920/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest920@1
diff --git a/hostsidetests/jvmti/run-tests/test-922/Android.mk b/hostsidetests/jvmti/run-tests/test-922/Android.mk
index 2de665a..d84b832 100644
--- a/hostsidetests/jvmti/run-tests/test-922/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-922/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest922HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-922/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-922/jarjar-rules.txt
new file mode 100644
index 0000000..9334c2d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-922/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest922@1
diff --git a/hostsidetests/jvmti/run-tests/test-923/Android.mk b/hostsidetests/jvmti/run-tests/test-923/Android.mk
index dd1de3c..d7f9f09 100644
--- a/hostsidetests/jvmti/run-tests/test-923/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-923/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest923HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-923/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-923/jarjar-rules.txt
new file mode 100644
index 0000000..5054eeb
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-923/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest923@1
diff --git a/hostsidetests/jvmti/run-tests/test-924/Android.mk b/hostsidetests/jvmti/run-tests/test-924/Android.mk
index 28c4b89..7e71607 100644
--- a/hostsidetests/jvmti/run-tests/test-924/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-924/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest924HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-924/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-924/jarjar-rules.txt
new file mode 100644
index 0000000..86780fc
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-924/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest924@1
diff --git a/hostsidetests/jvmti/run-tests/test-926/Android.mk b/hostsidetests/jvmti/run-tests/test-926/Android.mk
index fcd46ad..d11f3f3 100644
--- a/hostsidetests/jvmti/run-tests/test-926/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-926/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest926HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-926/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-926/jarjar-rules.txt
new file mode 100644
index 0000000..831e1634
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-926/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest926@1
diff --git a/hostsidetests/jvmti/run-tests/test-927/Android.mk b/hostsidetests/jvmti/run-tests/test-927/Android.mk
index 939601c..839ab86 100644
--- a/hostsidetests/jvmti/run-tests/test-927/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-927/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest927HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-927/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-927/jarjar-rules.txt
new file mode 100644
index 0000000..e342e09
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-927/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest927@1
diff --git a/hostsidetests/jvmti/run-tests/test-928/Android.mk b/hostsidetests/jvmti/run-tests/test-928/Android.mk
index 2eac8f9..30ec7b5 100644
--- a/hostsidetests/jvmti/run-tests/test-928/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-928/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest928HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-928/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-928/jarjar-rules.txt
new file mode 100644
index 0000000..52ce9fe
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-928/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest928@1
diff --git a/hostsidetests/jvmti/run-tests/test-930/Android.mk b/hostsidetests/jvmti/run-tests/test-930/Android.mk
index 2ac9ae2..73e6ba5d 100644
--- a/hostsidetests/jvmti/run-tests/test-930/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-930/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest930HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-930/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-930/jarjar-rules.txt
new file mode 100644
index 0000000..b45db2f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-930/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest930@1
diff --git a/hostsidetests/jvmti/run-tests/test-931/Android.mk b/hostsidetests/jvmti/run-tests/test-931/Android.mk
index ae04387..3c2175d 100644
--- a/hostsidetests/jvmti/run-tests/test-931/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-931/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest931HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-931/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-931/jarjar-rules.txt
new file mode 100644
index 0000000..9570d03
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-931/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest931@1
diff --git a/hostsidetests/jvmti/run-tests/test-932/Android.mk b/hostsidetests/jvmti/run-tests/test-932/Android.mk
index c952c86..3773279 100644
--- a/hostsidetests/jvmti/run-tests/test-932/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-932/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest932HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-932/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-932/jarjar-rules.txt
new file mode 100644
index 0000000..fc9fd30
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-932/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest932@1
diff --git a/hostsidetests/jvmti/run-tests/test-940/Android.mk b/hostsidetests/jvmti/run-tests/test-940/Android.mk
index 4ed5dec..372ee0d 100644
--- a/hostsidetests/jvmti/run-tests/test-940/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-940/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest940HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-940/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-940/jarjar-rules.txt
new file mode 100644
index 0000000..71c7825
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-940/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest940@1
diff --git a/hostsidetests/jvmti/run-tests/test-942/Android.mk b/hostsidetests/jvmti/run-tests/test-942/Android.mk
index d2605b7..9a9407a 100644
--- a/hostsidetests/jvmti/run-tests/test-942/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-942/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest942HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-942/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-942/jarjar-rules.txt
new file mode 100644
index 0000000..76d0e86
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-942/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest942@1
diff --git a/hostsidetests/jvmti/run-tests/test-944/Android.mk b/hostsidetests/jvmti/run-tests/test-944/Android.mk
index 16f9c7f..c60d2e2 100644
--- a/hostsidetests/jvmti/run-tests/test-944/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-944/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest944HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-944/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-944/jarjar-rules.txt
new file mode 100644
index 0000000..3f0fecf
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-944/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest944@1
diff --git a/hostsidetests/jvmti/run-tests/test-945/Android.mk b/hostsidetests/jvmti/run-tests/test-945/Android.mk
index e86d85e..433d9ac6 100644
--- a/hostsidetests/jvmti/run-tests/test-945/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-945/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest945HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-945/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-945/jarjar-rules.txt
new file mode 100644
index 0000000..03ea4b9
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-945/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest945@1
diff --git a/hostsidetests/jvmti/run-tests/test-947/Android.mk b/hostsidetests/jvmti/run-tests/test-947/Android.mk
index 4b4cead..0201816 100644
--- a/hostsidetests/jvmti/run-tests/test-947/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-947/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest947HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-947/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-947/jarjar-rules.txt
new file mode 100644
index 0000000..d229133
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-947/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest947@1
diff --git a/hostsidetests/jvmti/run-tests/test-951/Android.mk b/hostsidetests/jvmti/run-tests/test-951/Android.mk
index ba45b86..e198f70 100644
--- a/hostsidetests/jvmti/run-tests/test-951/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-951/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest951HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-951/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-951/jarjar-rules.txt
new file mode 100644
index 0000000..34d0341
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-951/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest951@1
diff --git a/hostsidetests/jvmti/run-tests/test-982/Android.mk b/hostsidetests/jvmti/run-tests/test-982/Android.mk
index 908adaf..e245e1d 100644
--- a/hostsidetests/jvmti/run-tests/test-982/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-982/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest982HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-982/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-982/jarjar-rules.txt
new file mode 100644
index 0000000..125fa3f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-982/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest982@1
diff --git a/hostsidetests/jvmti/run-tests/test-984/Android.mk b/hostsidetests/jvmti/run-tests/test-984/Android.mk
index 3ddb2ad..b0a919a 100644
--- a/hostsidetests/jvmti/run-tests/test-984/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-984/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest984HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-984/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-984/jarjar-rules.txt
new file mode 100644
index 0000000..b50c2b6
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-984/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest984@1
diff --git a/hostsidetests/jvmti/run-tests/test-985/Android.mk b/hostsidetests/jvmti/run-tests/test-985/Android.mk
index 0ed12de..0a55fac 100644
--- a/hostsidetests/jvmti/run-tests/test-985/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-985/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest985HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-985/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-985/jarjar-rules.txt
new file mode 100644
index 0000000..a784447
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-985/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest985@1
diff --git a/hostsidetests/jvmti/run-tests/test-986/Android.mk b/hostsidetests/jvmti/run-tests/test-986/Android.mk
index 8e6ec6f..6be45f2 100644
--- a/hostsidetests/jvmti/run-tests/test-986/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-986/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiRunTest986HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../../host_side.mk
diff --git a/hostsidetests/jvmti/run-tests/test-986/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-986/jarjar-rules.txt
new file mode 100644
index 0000000..51026b8
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-986/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest986@1
diff --git a/hostsidetests/jvmti/tagging/Android.mk b/hostsidetests/jvmti/tagging/Android.mk
index 61e06a4..1ee7bee 100644
--- a/hostsidetests/jvmti/tagging/Android.mk
+++ b/hostsidetests/jvmti/tagging/Android.mk
@@ -17,10 +17,5 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsJvmtiTaggingHostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
 
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(LOCAL_PATH)/../host_side.mk
diff --git a/hostsidetests/jvmti/tagging/jarjar-rules.txt b/hostsidetests/jvmti/tagging/jarjar-rules.txt
new file mode 100644
index 0000000..3dbf65a
--- /dev/null
+++ b/hostsidetests/jvmti/tagging/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTestTagging@1
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk
index bc09dc4..7e2753f 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk
@@ -20,8 +20,6 @@
 
 LOCAL_MODULE_TAGS := tests
 
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
 LOCAL_JNI_SHARED_LIBRARIES := libstaticsharednativelibprovider
 
 LOCAL_PACKAGE_NAME := CtsStaticSharedNativeLibProvider
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk
index 0abc351d..c2bc395 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk
@@ -20,8 +20,6 @@
 
 LOCAL_MODULE_TAGS := tests
 
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
 LOCAL_JNI_SHARED_LIBRARIES := libstaticsharednativelibprovider
 
 LOCAL_PACKAGE_NAME := CtsStaticSharedNativeLibProvider1
diff --git a/hostsidetests/security/Android.mk b/hostsidetests/security/Android.mk
index ffb5add..db1562c 100644
--- a/hostsidetests/security/Android.mk
+++ b/hostsidetests/security/Android.mk
@@ -34,6 +34,12 @@
 
 LOCAL_CTS_TEST_PACKAGE := android.host.security
 
+ifeq ($(HOST_OS),darwin)
+SHAREDLIB_EXT=dylib
+else
+SHAREDLIB_EXT=so
+endif
+
 selinux_plat_seapp_contexts := $(call intermediates-dir-for,ETC,plat_seapp_contexts)/plat_seapp_contexts
 
 selinux_plat_seapp_neverallows := $(call intermediates-dir-for,ETC,plat_seapp_neverallows)/plat_seapp_neverallows
@@ -47,6 +53,9 @@
 LOCAL_JAVA_RESOURCE_FILES := \
     $(HOST_OUT_EXECUTABLES)/checkseapp \
     $(HOST_OUT_EXECUTABLES)/checkfc \
+    $(HOST_OUT_EXECUTABLES)/sepolicy_tests \
+    $(HOST_OUT)/lib64/libsepolwrap.$(SHAREDLIB_EXT) \
+    $(HOST_OUT)/lib64/libc++.$(SHAREDLIB_EXT) \
     $(selinux_plat_seapp_contexts) \
     $(selinux_plat_seapp_neverallows) \
     $(selinux_plat_file_contexts) \
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6730/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-6730/Android.mk
index 14337ab..0c188b3 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-6730/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-6730/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6731/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-6731/Android.mk
index 718dbe3..02db3e3 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-6731/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-6731/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6732/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-6732/Android.mk
index 03b7b87..7b74ac1 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-6732/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-6732/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6733/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-6733/Android.mk
index 7b02188..a52f5de 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-6733/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-6733/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6734/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-6734/Android.mk
index e1eebbd..a22522d 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-6734/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-6734/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6735/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-6735/Android.mk
index 8935cd6..7d28f31 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-6735/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-6735/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6736/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-6736/Android.mk
index fd7fc21..4b4757f 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-6736/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-6736/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8412/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8412/Android.mk
index bba13f3..150c96e 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8412/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8412/Android.mk
@@ -26,10 +26,5 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8424/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8424/Android.mk
index 5ff169b..e91fd50 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8424/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8424/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8425/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8425/Android.mk
index e984812..9b948ad 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8425/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8425/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8426/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8426/Android.mk
index a134d9c..03a06c7 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8426/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8426/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8427/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8427/Android.mk
index 131f240..65be8d3 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8427/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8427/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8428/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8428/Android.mk
index 21326f9..2c9ba08 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8428/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8428/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8429/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8429/Android.mk
index bfe8718..21ad67a 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8429/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8429/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk
index 839047b..5ea76d5 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8431/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8431/Android.mk
index d0ef823..7000aad 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8431/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8431/Android.mk
@@ -26,10 +26,5 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8432/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8432/Android.mk
index 614d20b..5e3c137 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8432/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8432/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8434/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8434/Android.mk
index 6b20fe4..360cf89 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8434/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8434/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8435/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8435/Android.mk
index 62efb65..45378d1 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8435/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8435/Android.mk
@@ -26,10 +26,5 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8444/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8444/Android.mk
index 50e2f6a..f6833c6 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8444/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8444/Android.mk
@@ -26,10 +26,5 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8448/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8448/Android.mk
index cd6049f..72ea6c6 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8448/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8448/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8449/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8449/Android.mk
index ce1e1bb..0d8c039 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8449/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8449/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8460/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8460/Android.mk
index b9c51d1..e054dd2 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8460/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8460/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS := -Wall -W -g -O2 -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8482/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8482/Android.mk
index b41fb16..d3f76b6 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-8482/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-8482/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-9120/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-9120/Android.mk
index 95ddb3d..9c68cac 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-9120/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2016-9120/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0403/Android.mk b/hostsidetests/security/securityPatch/CVE-2017-0403/Android.mk
index cb31e4d..b7ccd24 100644
--- a/hostsidetests/security/securityPatch/CVE-2017-0403/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2017-0403/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0404/Android.mk b/hostsidetests/security/securityPatch/CVE-2017-0404/Android.mk
index 9e30d30..ac72a0f 100644
--- a/hostsidetests/security/securityPatch/CVE-2017-0404/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2017-0404/Android.mk
@@ -26,10 +26,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0429/Android.mk b/hostsidetests/security/securityPatch/CVE-2017-0429/Android.mk
index afb77b4..78cb573 100644
--- a/hostsidetests/security/securityPatch/CVE-2017-0429/Android.mk
+++ b/hostsidetests/security/securityPatch/CVE-2017-0429/Android.mk
@@ -26,10 +26,5 @@
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0564/kernel-headers/linux/ion.h b/hostsidetests/security/securityPatch/CVE-2017-0564/kernel-headers/linux/ion.h
new file mode 100644
index 0000000..7b5b031
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2017-0564/kernel-headers/linux/ion.h
@@ -0,0 +1,78 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ***   To edit the content of this header, modify the corresponding
+ ***   source file (e.g. under external/kernel-headers/original/) then
+ ***   run bionic/libc/kernel/tools/update_all.py
+ ***
+ ***   Any manual change here will be lost the next time this script will
+ ***   be run. You've been warned!
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef _UAPI_LINUX_ION_H
+#define _UAPI_LINUX_ION_H
+#include <linux/ioctl.h>
+#include <linux/types.h>
+typedef int ion_user_handle_t;
+enum ion_heap_type {
+  ION_HEAP_TYPE_SYSTEM,
+  ION_HEAP_TYPE_SYSTEM_CONTIG,
+  ION_HEAP_TYPE_CARVEOUT,
+  ION_HEAP_TYPE_CHUNK,
+  ION_HEAP_TYPE_DMA,
+  ION_HEAP_TYPE_CUSTOM,
+};
+#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8)
+#define ION_FLAG_CACHED 1
+#define ION_FLAG_CACHED_NEEDS_SYNC 2
+struct ion_allocation_data {
+  size_t len;
+  size_t align;
+  unsigned int heap_id_mask;
+  unsigned int flags;
+  ion_user_handle_t handle;
+};
+struct ion_fd_data {
+  ion_user_handle_t handle;
+  int fd;
+};
+struct ion_handle_data {
+  ion_user_handle_t handle;
+};
+struct ion_custom_data {
+  unsigned int cmd;
+  unsigned long arg;
+};
+#define MAX_HEAP_NAME 32
+struct ion_heap_data {
+  char name[MAX_HEAP_NAME];
+  __u32 type;
+  __u32 heap_id;
+  __u32 reserved0;
+  __u32 reserved1;
+  __u32 reserved2;
+};
+struct ion_heap_query {
+  __u32 cnt;
+  __u32 reserved0;
+  __u64 heaps;
+  __u32 reserved1;
+  __u32 reserved2;
+};
+#define ION_IOC_MAGIC 'I'
+#define ION_IOC_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_allocation_data)
+#define ION_IOC_FREE _IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data)
+#define ION_IOC_MAP _IOWR(ION_IOC_MAGIC, 2, struct ion_fd_data)
+#define ION_IOC_SHARE _IOWR(ION_IOC_MAGIC, 4, struct ion_fd_data)
+#define ION_IOC_IMPORT _IOWR(ION_IOC_MAGIC, 5, struct ion_fd_data)
+#define ION_IOC_SYNC _IOWR(ION_IOC_MAGIC, 7, struct ion_fd_data)
+#define ION_IOC_CUSTOM _IOWR(ION_IOC_MAGIC, 6, struct ion_custom_data)
+#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query)
+#endif
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0564/original-kernel-headers/linux/ion.h b/hostsidetests/security/securityPatch/CVE-2017-0564/original-kernel-headers/linux/ion.h
new file mode 100644
index 0000000..14cd873
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2017-0564/original-kernel-headers/linux/ion.h
@@ -0,0 +1,236 @@
+/*
+ * drivers/staging/android/uapi/ion.h
+ *
+ * Copyright (C) 2011 Google, Inc.
+ *
+ * This software is licensed under the terms of the GNU General Public
+ * License version 2, as published by the Free Software Foundation, and
+ * may be copied, distributed, and modified under those terms.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#ifndef _UAPI_LINUX_ION_H
+#define _UAPI_LINUX_ION_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+typedef int ion_user_handle_t;
+
+/**
+ * enum ion_heap_types - list of all possible types of heaps
+ * @ION_HEAP_TYPE_SYSTEM:	 memory allocated via vmalloc
+ * @ION_HEAP_TYPE_SYSTEM_CONTIG: memory allocated via kmalloc
+ * @ION_HEAP_TYPE_CARVEOUT:	 memory allocated from a prereserved
+ *				 carveout heap, allocations are physically
+ *				 contiguous
+ * @ION_HEAP_TYPE_DMA:		 memory allocated via DMA API
+ * @ION_NUM_HEAPS:		 helper for iterating over heaps, a bit mask
+ *				 is used to identify the heaps, so only 32
+ *				 total heap types are supported
+ */
+enum ion_heap_type {
+	ION_HEAP_TYPE_SYSTEM,
+	ION_HEAP_TYPE_SYSTEM_CONTIG,
+	ION_HEAP_TYPE_CARVEOUT,
+	ION_HEAP_TYPE_CHUNK,
+	ION_HEAP_TYPE_DMA,
+	ION_HEAP_TYPE_CUSTOM, /*
+			       * must be last so device specific heaps always
+			       * are at the end of this enum
+			       */
+};
+
+#define ION_NUM_HEAP_IDS		(sizeof(unsigned int) * 8)
+
+/**
+ * allocation flags - the lower 16 bits are used by core ion, the upper 16
+ * bits are reserved for use by the heaps themselves.
+ */
+
+/*
+ * mappings of this buffer should be cached, ion will do cache maintenance
+ * when the buffer is mapped for dma
+ */
+#define ION_FLAG_CACHED 1
+
+/*
+ * mappings of this buffer will created at mmap time, if this is set
+ * caches must be managed manually
+ */
+#define ION_FLAG_CACHED_NEEDS_SYNC 2
+
+/**
+ * DOC: Ion Userspace API
+ *
+ * create a client by opening /dev/ion
+ * most operations handled via following ioctls
+ *
+ */
+
+/**
+ * struct ion_allocation_data - metadata passed from userspace for allocations
+ * @len:		size of the allocation
+ * @align:		required alignment of the allocation
+ * @heap_id_mask:	mask of heap ids to allocate from
+ * @flags:		flags passed to heap
+ * @handle:		pointer that will be populated with a cookie to use to
+ *			refer to this allocation
+ *
+ * Provided by userspace as an argument to the ioctl
+ */
+struct ion_allocation_data {
+	size_t len;
+	size_t align;
+	unsigned int heap_id_mask;
+	unsigned int flags;
+	ion_user_handle_t handle;
+};
+
+/**
+ * struct ion_fd_data - metadata passed to/from userspace for a handle/fd pair
+ * @handle:	a handle
+ * @fd:		a file descriptor representing that handle
+ *
+ * For ION_IOC_SHARE or ION_IOC_MAP userspace populates the handle field with
+ * the handle returned from ion alloc, and the kernel returns the file
+ * descriptor to share or map in the fd field.  For ION_IOC_IMPORT, userspace
+ * provides the file descriptor and the kernel returns the handle.
+ */
+struct ion_fd_data {
+	ion_user_handle_t handle;
+	int fd;
+};
+
+/**
+ * struct ion_handle_data - a handle passed to/from the kernel
+ * @handle:	a handle
+ */
+struct ion_handle_data {
+	ion_user_handle_t handle;
+};
+
+/**
+ * struct ion_custom_data - metadata passed to/from userspace for a custom ioctl
+ * @cmd:	the custom ioctl function to call
+ * @arg:	additional data to pass to the custom ioctl, typically a user
+ *		pointer to a predefined structure
+ *
+ * This works just like the regular cmd and arg fields of an ioctl.
+ */
+struct ion_custom_data {
+	unsigned int cmd;
+	unsigned long arg;
+};
+
+#define MAX_HEAP_NAME			32
+
+/**
+ * struct ion_heap_data - data about a heap
+ * @name - first 32 characters of the heap name
+ * @type - heap type
+ * @heap_id - heap id for the heap
+ */
+struct ion_heap_data {
+	char name[MAX_HEAP_NAME];
+	__u32 type;
+	__u32 heap_id;
+	__u32 reserved0;
+	__u32 reserved1;
+	__u32 reserved2;
+};
+
+/**
+ * struct ion_heap_query - collection of data about all heaps
+ * @cnt - total number of heaps to be copied
+ * @heaps - buffer to copy heap data
+ */
+struct ion_heap_query {
+	__u32 cnt; /* Total number of heaps to be copied */
+	__u32 reserved0; /* align to 64bits */
+	__u64 heaps; /* buffer to be populated */
+	__u32 reserved1;
+	__u32 reserved2;
+};
+
+#define ION_IOC_MAGIC		'I'
+
+/**
+ * DOC: ION_IOC_ALLOC - allocate memory
+ *
+ * Takes an ion_allocation_data struct and returns it with the handle field
+ * populated with the opaque handle for the allocation.
+ */
+#define ION_IOC_ALLOC		_IOWR(ION_IOC_MAGIC, 0, \
+				      struct ion_allocation_data)
+
+/**
+ * DOC: ION_IOC_FREE - free memory
+ *
+ * Takes an ion_handle_data struct and frees the handle.
+ */
+#define ION_IOC_FREE		_IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data)
+
+/**
+ * DOC: ION_IOC_MAP - get a file descriptor to mmap
+ *
+ * Takes an ion_fd_data struct with the handle field populated with a valid
+ * opaque handle.  Returns the struct with the fd field set to a file
+ * descriptor open in the current address space.  This file descriptor
+ * can then be used as an argument to mmap.
+ */
+#define ION_IOC_MAP		_IOWR(ION_IOC_MAGIC, 2, struct ion_fd_data)
+
+/**
+ * DOC: ION_IOC_SHARE - creates a file descriptor to use to share an allocation
+ *
+ * Takes an ion_fd_data struct with the handle field populated with a valid
+ * opaque handle.  Returns the struct with the fd field set to a file
+ * descriptor open in the current address space.  This file descriptor
+ * can then be passed to another process.  The corresponding opaque handle can
+ * be retrieved via ION_IOC_IMPORT.
+ */
+#define ION_IOC_SHARE		_IOWR(ION_IOC_MAGIC, 4, struct ion_fd_data)
+
+/**
+ * DOC: ION_IOC_IMPORT - imports a shared file descriptor
+ *
+ * Takes an ion_fd_data struct with the fd field populated with a valid file
+ * descriptor obtained from ION_IOC_SHARE and returns the struct with the handle
+ * filed set to the corresponding opaque handle.
+ */
+#define ION_IOC_IMPORT		_IOWR(ION_IOC_MAGIC, 5, struct ion_fd_data)
+
+/**
+ * DOC: ION_IOC_SYNC - syncs a shared file descriptors to memory
+ *
+ * Deprecated in favor of using the dma_buf api's correctly (syncing
+ * will happen automatically when the buffer is mapped to a device).
+ * If necessary should be used after touching a cached buffer from the cpu,
+ * this will make the buffer in memory coherent.
+ */
+#define ION_IOC_SYNC		_IOWR(ION_IOC_MAGIC, 7, struct ion_fd_data)
+
+/**
+ * DOC: ION_IOC_CUSTOM - call architecture specific ion ioctl
+ *
+ * Takes the argument of the architecture specific ioctl to call and
+ * passes appropriate userdata for that ioctl
+ */
+#define ION_IOC_CUSTOM		_IOWR(ION_IOC_MAGIC, 6, struct ion_custom_data)
+
+/**
+ * DOC: ION_IOC_HEAP_QUERY - information about available heaps
+ *
+ * Takes an ion_heap_query structure and populates information about
+ * available Ion heaps.
+ */
+#define ION_IOC_HEAP_QUERY     _IOWR(ION_IOC_MAGIC, 8, \
+					struct ion_heap_query)
+
+#endif /* _UAPI_LINUX_ION_H */
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0564/poc.c b/hostsidetests/security/securityPatch/CVE-2017-0564/poc.c
index 7734d4c..ae5ad40 100644
--- a/hostsidetests/security/securityPatch/CVE-2017-0564/poc.c
+++ b/hostsidetests/security/securityPatch/CVE-2017-0564/poc.c
@@ -29,7 +29,11 @@
 #include <string.h>
 #include <fcntl.h>
 #include <errno.h>
-#include <linux/ion.h>
+
+// Include a fixed version of the ion.h file because it changes per kernel.
+// This test is going to be extremely brittle due to it's dependency on
+// a structure that is going to change with different kernels.
+#include "kernel-headers/linux/ion.h"
 
 #define ION_HEAP(bit) (1 << (bit))
 
@@ -73,7 +77,7 @@
 #ifdef NEW_ION
         .heap_id_mask = ion_type,
         //.flags = ION_SECURE | ION_FORCE_CONTIGUOUS,
-        .flags = (1 << 0),
+        //.flags = (1 << 0),
         .flags = 0x0,
 #else
         .flags = ION_SECURE | ION_FORCE_CONTIGUOUS | ION_HEAP(ION_CP_MM_HEAP_ID),
@@ -165,7 +169,7 @@
 
 int main()
 {
-    int ret, i, count;
+    int ret, count;
     pthread_t tid_free[2];
 
     count = 0;
@@ -178,6 +182,7 @@
 	return -1;
     }
 
+    size_t i;
     for (i=0; i < sizeof(ion_type)/sizeof(ion_type[0]); i++) {
         ret = ion_alloc(ion_fd, 0x1000, &ion_handle, ion_type[i]);
         if (ret == 0) {
diff --git a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
index cff9ef9..b048672 100644
--- a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
+++ b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
@@ -46,6 +46,7 @@
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.Scanner;
@@ -60,6 +61,10 @@
  */
 public class SELinuxHostTest extends DeviceTestCase implements IBuildReceiver, IDeviceTest {
 
+    private static final Map<ITestDevice, File> cachedDevicePolicyFiles = new HashMap<>(1);
+    private static final Map<ITestDevice, File> cachedDevicePlatFcFiles = new HashMap<>(1);
+    private static final Map<ITestDevice, File> cachedDeviceNonplatFcFiles = new HashMap<>(1);
+
     private File sepolicyAnalyze;
     private File checkSeapp;
     private File checkFc;
@@ -75,6 +80,9 @@
     private File devicePcFile;
     private File deviceSvcFile;
     private File seappNeverAllowFile;
+    private File libsepolwrap;
+    private File libcpp;
+    private File sepolicyTests;
 
     private IBuildInfo mBuild;
 
@@ -104,9 +112,11 @@
         InputStream is = this.getClass().getResourceAsStream(resName);
         File tempFile = File.createTempFile("SELinuxHostTest", ".tmp");
         FileOutputStream os = new FileOutputStream(tempFile);
-        int rByte = 0;
-        while ((rByte = is.read()) != -1) {
-            os.write(rByte);
+        byte[] buf = new byte[1024];
+        int len;
+
+        while ((len = is.read(buf)) != -1) {
+            os.write(buf, 0, len);
         }
         os.flush();
         os.close();
@@ -133,10 +143,52 @@
         sepolicyAnalyze = buildHelper.getTestFile("sepolicy-analyze");
         sepolicyAnalyze.setExecutable(true);
 
-        /* obtain sepolicy file from running device */
-        devicePolicyFile = File.createTempFile("sepolicy", ".tmp");
-        devicePolicyFile.deleteOnExit();
-        mDevice.pullFile("/sys/fs/selinux/policy", devicePolicyFile);
+        devicePolicyFile = getDevicePolicyFile(mDevice);
+        if (mDevice.doesFileExist("/system/etc/selinux/plat_file_contexts")) {
+            devicePlatFcFile = getDeviceFile(mDevice, cachedDevicePlatFcFiles,
+                    "/system/etc/selinux/plat_file_contexts", "plat_file_contexts");
+            deviceNonplatFcFile = getDeviceFile(mDevice, cachedDeviceNonplatFcFiles,
+                    "/vendor/etc/selinux/nonplat_file_contexts", "nonplat_file_contexts");
+        } else {
+            devicePlatFcFile = getDeviceFile(mDevice, cachedDevicePlatFcFiles,
+                    "/plat_file_contexts", "plat_file_contexts");
+            deviceNonplatFcFile = getDeviceFile(mDevice, cachedDeviceNonplatFcFiles,
+                    "/nonplat_file_contexts", "nonplat_file_contexts");
+        }
+    }
+
+    /*
+     * IMPLEMENTATION DETAILS: We cache some host-side policy files on per-device basis (in case
+     * CTS supports running against multiple devices at the same time). HashMap is used instead
+     * of WeakHashMap because in the grand scheme of things, keeping ITestDevice and
+     * corresponding File objects from being garbage-collected is not a big deal in CTS. If this
+     * becomes a big deal, this can be switched to WeakHashMap.
+     */
+    private static File getDeviceFile(ITestDevice device,
+            Map<ITestDevice, File> cache, String deviceFilePath,
+            String tmpFileName) throws Exception {
+        File file;
+        synchronized (cache) {
+            file = cache.get(device);
+        }
+        if (file != null) {
+            return file;
+        }
+        file = File.createTempFile(tmpFileName, ".tmp");
+        file.deleteOnExit();
+        device.pullFile(deviceFilePath, file);
+        synchronized (cache) {
+            cache.put(device, file);
+        }
+        return file;
+    }
+
+    // NOTE: cts/tools/selinux depends on this method. Rename/change with caution.
+    /**
+     * Returns the host-side file containing the SELinux policy of the device under test.
+     */
+    public static File getDevicePolicyFile(ITestDevice device) throws Exception {
+        return getDeviceFile(device, cachedDevicePolicyFiles, "/sys/fs/selinux/policy", "sepolicy");
     }
 
     /**
@@ -429,13 +481,6 @@
         checkFc = copyResourceToTempFile("/checkfc");
         checkFc.setExecutable(true);
 
-        /* obtain file_contexts file(s) from running device */
-        devicePlatFcFile = File.createTempFile("file_contexts", ".tmp");
-        devicePlatFcFile.deleteOnExit();
-        if (!mDevice.pullFile("/system/etc/selinux/plat_file_contexts", devicePlatFcFile)) {
-            mDevice.pullFile("/plat_file_contexts", devicePlatFcFile);
-        }
-
         /* retrieve the AOSP file_contexts file from jar */
         aospFcFile = copyResourceToTempFile("/plat_file_contexts");
 
@@ -513,24 +558,16 @@
         checkFc = copyResourceToTempFile("/checkfc");
         checkFc.setExecutable(true);
 
-        /* obtain file_contexts file(s) from running device */
-        devicePlatFcFile = File.createTempFile("plat_file_contexts", ".tmp");
-        devicePlatFcFile.deleteOnExit();
-        deviceNonplatFcFile = File.createTempFile("nonplat_file_contexts", ".tmp");
-        deviceNonplatFcFile.deleteOnExit();
-        if (mDevice.pullFile("/system/etc/selinux/plat_file_contexts", devicePlatFcFile)) {
-            mDevice.pullFile("/vendor/etc/selinux/nonplat_file_contexts", deviceNonplatFcFile);
-        } else {
-            mDevice.pullFile("/plat_file_contexts", devicePlatFcFile);
-            mDevice.pullFile("/nonplat_file_contexts", deviceNonplatFcFile);
-        }
-        appendTo(devicePlatFcFile.getAbsolutePath(),
-                deviceNonplatFcFile.getAbsolutePath());
+        /* combine plat and nonplat policies for testing */
+        File combinedFcFile = File.createTempFile("combined_file_context", ".tmp");
+        combinedFcFile.deleteOnExit();
+        appendTo(combinedFcFile.getAbsolutePath(), devicePlatFcFile.getAbsolutePath());
+        appendTo(combinedFcFile.getAbsolutePath(), deviceNonplatFcFile.getAbsolutePath());
 
         /* run checkfc sepolicy file_contexts */
         ProcessBuilder pb = new ProcessBuilder(checkFc.getAbsolutePath(),
                 devicePolicyFile.getAbsolutePath(),
-                devicePlatFcFile.getAbsolutePath());
+                combinedFcFile.getAbsolutePath());
         pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
         pb.redirectErrorStream(true);
         Process p = pb.start();
@@ -618,6 +655,67 @@
                    + errorString, errorString.length() == 0);
     }
 
+    private boolean isMac() {
+        String os = System.getProperty("os.name").toLowerCase();
+        return (os.startsWith("mac") || os.startsWith("darwin"));
+    }
+
+    private void setupLibraries() throws Exception {
+        // The host side binary tests are host OS specific. Use Linux
+        // libraries on Linux and Mac libraries on Mac.
+        if (isMac()) {
+            libsepolwrap = copyResourceToTempFile("/libsepolwrap.dylib");
+            libcpp = copyResourceToTempFile("/libc++.dylib");
+            libcpp.renameTo(new File(System.getProperty("java.io.tmpdir") + "/libc++.dylib"));
+        } else {
+            libsepolwrap = copyResourceToTempFile("/libsepolwrap.so");
+            libcpp = copyResourceToTempFile("/libc++.so");
+            libcpp.renameTo(new File(System.getProperty("java.io.tmpdir") + "/libc++.so"));
+        }
+        libsepolwrap.deleteOnExit();
+        libcpp.deleteOnExit();
+    }
+
+    private void assertSepolicyTests(String Test) throws Exception {
+        setupLibraries();
+        sepolicyTests = copyResourceToTempFile("/sepolicy_tests");
+        sepolicyTests.setExecutable(true);
+        ProcessBuilder pb = new ProcessBuilder(
+                sepolicyTests.getAbsolutePath(),
+                "-l", libsepolwrap.getAbsolutePath(),
+                "-f", devicePlatFcFile.getAbsolutePath(),
+                "-f", deviceNonplatFcFile.getAbsolutePath(),
+                "-p", devicePolicyFile.getAbsolutePath(),
+                "--test", Test);
+        Map<String, String> env = pb.environment();
+        if (isMac()) {
+            env.put("DYLD_LIBRARY_PATH", System.getProperty("java.io.tmpdir"));
+        } else {
+            env.put("LD_LIBRARY_PATH", System.getProperty("java.io.tmpdir"));
+        }
+        pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
+        pb.redirectErrorStream(true);
+        Process p = pb.start();
+        p.waitFor();
+        BufferedReader result = new BufferedReader(new InputStreamReader(p.getInputStream()));
+        String line;
+        StringBuilder errorString = new StringBuilder();
+        while ((line = result.readLine()) != null) {
+            errorString.append(line);
+            errorString.append("\n");
+        }
+        assertTrue(errorString.toString(), errorString.length() == 0);
+    }
+
+    /**
+     * Tests that all types on /data have the data_file_type attribute.
+     *
+     * @throws Exception
+     */
+    public void testDataTypeViolators() throws Exception {
+        assertSepolicyTests("TestDataTypeViolations");
+    }
+
    /**
      * Tests that the policy defines no booleans (runtime conditional policy).
      *
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
index 075e09c..3b793b0 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
@@ -27,7 +27,6 @@
 import java.util.List;
 
 import static android.server.cts.ActivityAndWindowManagersState.dpToPx;
-import static android.server.cts.ActivityAndWindowManagersState.DEFAULT_DISPLAY_ID;
 
 /**
  * Build: mmma -j32 cts/hostsidetests/services
@@ -49,7 +48,6 @@
 
     private static final int SMALL_WIDTH_DP = 426;
     private static final int SMALL_HEIGHT_DP = 320;
-    private static final int NAVI_BAR_HEIGHT_DP = 48;
 
     /**
      * Tests that the WindowManager#getDefaultDisplay() and the Configuration of the Activity
@@ -160,6 +158,7 @@
 
         final String logSeparator = clearLogcat();
         launchActivityInDockStack(LAUNCHING_ACTIVITY);
+
         getLaunchActivityBuilder().setToSide(true).setTargetActivityName(RESIZEABLE_ACTIVITY_NAME)
                 .execute();
         final ReportedSizes initialSizes = getActivityDisplaySize(RESIZEABLE_ACTIVITY_NAME,
@@ -486,39 +485,10 @@
     }
 
     /**
-     * If aspect ratio larger than 2.0, and system insets less than default system insets height
-     * (from nav bar),it won't meet CTS testcase requirement, so we treat these scenario specially
-     * and do not check the rotation.
-     */
-    private boolean shouldSkipRotationCheck() throws Exception{
-        WindowManagerState wmState = mAmWmState.getWmState();
-        wmState.computeState(mDevice);
-        WindowManagerState.Display display = wmState.getDisplay(DEFAULT_DISPLAY_ID);
-        Rectangle displayRect = display.getDisplayRect();
-        Rectangle appRect = display.getAppRect();
-
-        float aspectRatio = 0.0f;
-        int naviBarHeight;
-        if (wmState.getRotation() == 0 || wmState.getRotation() == 2) {
-            aspectRatio = (float) displayRect.height / displayRect.width;
-            naviBarHeight = displayRect.height - appRect.height;
-        } else {
-            aspectRatio = (float) displayRect.width / displayRect.height;
-            naviBarHeight = displayRect.width - appRect.width;
-        }
-
-        int density = display.getDpi();
-        int systemInsetsHeight = dpToPx(NAVI_BAR_HEIGHT_DP, density);
-        // After changed rotation the dispalySize will be effected by aspect ratio and system UI
-        // insets (from nav bar) together, so we should check if needed to skip testcase
-        return aspectRatio >= 2.0 && naviBarHeight < systemInsetsHeight;
-    }
-
-    /**
      * Asserts that after rotation, the aspect ratios of display size, metrics, and configuration
      * have flipped.
      */
-    private void assertSizesRotate(ReportedSizes rotationA, ReportedSizes rotationB)
+    private static void assertSizesRotate(ReportedSizes rotationA, ReportedSizes rotationB)
             throws Exception {
         assertEquals(rotationA.displayWidth, rotationA.metricsWidth);
         assertEquals(rotationA.displayHeight, rotationA.metricsHeight);
@@ -529,17 +499,12 @@
         final boolean afterPortrait = rotationB.displayWidth < rotationB.displayHeight;
         assertFalse(beforePortrait == afterPortrait);
 
-        // When rotation is land, displayHeight calculated base on N does not contain
-        // statusBarHeight, while displayHeight calculated base on O version contains
-        // statusBarHeight. Therefore starting with O we don't check config rotation and
-        // smallestWidth on some devices with tall aspect ratio.
-        if (!shouldSkipRotationCheck()) {
-            final boolean beforeConfigPortrait = rotationA.widthDp < rotationA.heightDp;
-            final boolean afterConfigPortrait = rotationB.widthDp < rotationB.heightDp;
-            assertEquals(beforePortrait, beforeConfigPortrait);
-            assertEquals(afterPortrait, afterConfigPortrait);
-            assertEquals(rotationA.smallestWidthDp, rotationB.smallestWidthDp);
-        }
+        final boolean beforeConfigPortrait = rotationA.widthDp < rotationA.heightDp;
+        final boolean afterConfigPortrait = rotationB.widthDp < rotationB.heightDp;
+        assertEquals(beforePortrait, beforeConfigPortrait);
+        assertEquals(afterPortrait, afterConfigPortrait);
+
+        assertEquals(rotationA.smallestWidthDp, rotationB.smallestWidthDp);
     }
 
     /**
diff --git a/hostsidetests/theme/assets/P b/hostsidetests/theme/assets/P
new file mode 120000
index 0000000..978b4e8
--- /dev/null
+++ b/hostsidetests/theme/assets/P
@@ -0,0 +1 @@
+26
\ No newline at end of file
diff --git a/hostsidetests/tzdata/Android.mk b/hostsidetests/tzdata/Android.mk
new file mode 100644
index 0000000..3cee8b5
--- /dev/null
+++ b/hostsidetests/tzdata/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)
+
+# Only compile source java files in this apk.
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_MODULE := CtsHostTzDataTests
+
+LOCAL_JAVA_LIBRARIES := tradefed
+
+LOCAL_STATIC_JAVA_LIBRARIES := tzdata-testing-host time_zone_distro-host time_zone_distro_tools-host
+
+LOCAL_CTS_TEST_PACKAGE := android.host.tzdata
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
diff --git a/hostsidetests/tzdata/AndroidTest.xml b/hostsidetests/tzdata/AndroidTest.xml
new file mode 100644
index 0000000..cccfe5a
--- /dev/null
+++ b/hostsidetests/tzdata/AndroidTest.xml
@@ -0,0 +1,20 @@
+<?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.
+-->
+<configuration description="Config for CTS tzdatacheck host test cases">
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsHostTzDataTests.jar" />
+    </test>
+</configuration>
diff --git a/hostsidetests/tzdata/src/com/android/cts/tzdata/TzDataCheckTest.java b/hostsidetests/tzdata/src/com/android/cts/tzdata/TzDataCheckTest.java
new file mode 100644
index 0000000..2e9707c
--- /dev/null
+++ b/hostsidetests/tzdata/src/com/android/cts/tzdata/TzDataCheckTest.java
@@ -0,0 +1,977 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.tzdata;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.timezone.distro.DistroVersion;
+import com.android.timezone.distro.TimeZoneDistro;
+import com.android.timezone.distro.tools.TimeZoneDistroBuilder;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Comparator;
+import java.util.StringJoiner;
+import java.util.function.Consumer;
+import libcore.tzdata.testing.ZoneInfoTestHelper;
+
+import static org.junit.Assert.assertArrayEquals;
+
+/**
+ * Tests for the tzdatacheck binary.
+ *
+ * <p>The tzdatacheck binary operates over two directories: the "system directory" containing the
+ * time zone rules in the system image, and a "data directory" in the data partition which can
+ * optionally contain time zone rules data files for bionic/libcore and ICU.
+ *
+ * <p>This test executes the tzdatacheck binary to confirm it operates correctly in a number of
+ * simulated situations; simulated system and data directories in various states are created in a
+ * location the shell user has permission to access and the tzdatacheck binary is then executed.
+ * The status code and directory state after execution is then used to determine if the tzdatacheck
+ * binary operated correctly.
+ *
+ * <p>Most of the tests below prepare simulated directory structure for the system and data dirs
+ * on the host before pushing them to the device. Device state is then checked rather than syncing
+ * the files back.
+ */
+public class TzDataCheckTest extends DeviceTestCase {
+
+    /**
+     * The name of the directory containing the current time zone rules data beneath
+     * {@link #mDataDir}.  Also known to {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and
+     * tzdatacheck.cpp.
+     */
+    private static final String CURRENT_DIR_NAME = "current";
+
+    /**
+     * The name of the directory containing the staged time zone rules data beneath
+     * {@link #mDataDir}.  Also known to {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and
+     * tzdatacheck.cpp.
+     */
+    private static final String STAGED_DIR_NAME = "staged";
+
+    /**
+     * The name of the file inside the staged directory that indicates the staged operation is an
+     * uninstall. Also known to {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and
+     * tzdatacheck.cpp.
+     */
+    private static final String UNINSTALL_TOMBSTONE_FILE_NAME = "STAGED_UNINSTALL_TOMBSTONE";
+
+    /**
+     * The name of the /system time zone data file. Also known to
+     * {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and tzdatacheck.cpp.
+     */
+    private static final String SYSTEM_TZDATA_FILE_NAME = "tzdata";
+
+    /** A valid time zone rules version guaranteed to be older than {@link #RULES_VERSION_TWO} */
+    private static final String RULES_VERSION_ONE = "2016g";
+    /** A valid time zone rules version guaranteed to be newer than {@link #RULES_VERSION_ONE} */
+    private static final String RULES_VERSION_TWO = "2016h";
+    /**
+     * An arbitrary, valid time zone rules version used when it doesn't matter what the rules
+     * version is.
+     */
+    private static final String VALID_RULES_VERSION = RULES_VERSION_ONE;
+
+    /** An arbitrary valid revision number. */
+    private static final int VALID_REVISION = 1;
+
+    private String mDeviceAndroidRootDir;
+    private PathPair mTestRootDir;
+    private PathPair mSystemDir;
+    private PathPair mDataDir;
+
+    public void setUp() throws Exception {
+        super.setUp();
+
+        // It's not clear how we would get this without invoking "/system/bin/sh", but we need the
+        // value first to do so. It has been hardcoded instead.
+        mDeviceAndroidRootDir = "/system";
+
+        // Create a test root directory on host and device.
+        Path hostTestRootDir = Files.createTempDirectory("tzdatacheck_test");
+        mTestRootDir = new PathPair(
+                hostTestRootDir,
+                "/data/local/tmp/tzdatacheck_test");
+        createDeviceDirectory(mTestRootDir);
+
+        // tzdatacheck requires two directories: a "system" path and a "data" path.
+        mSystemDir = mTestRootDir.createSubPath("system_dir");
+        mDataDir = mTestRootDir.createSubPath("data_dir");
+
+        // Create the host-side directory structure (for preparing files before pushing them to
+        // device and looking at files retrieved from device).
+        createHostDirectory(mSystemDir);
+        createHostDirectory(mDataDir);
+
+        // Create the equivalent device-side directory structure for receiving files.
+        createDeviceDirectory(mSystemDir);
+        createDeviceDirectory(mDataDir);
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        // Remove the test root directories that have been created by this test.
+        deleteHostDirectory(mTestRootDir, true /* failOnError */);
+        deleteDeviceDirectory(mTestRootDir, true /* failOnError */);
+        super.tearDown();
+    }
+
+    public void testTooFewArgs() throws Exception {
+        // No need to set up or push files to the device for this test.
+        assertEquals(1, runTzDataCheckWithArgs(new String[0]));
+        assertEquals(1, runTzDataCheckWithArgs(new String[] { "oneArg" }));
+    }
+
+    // {dataDir}/staged exists but it is a file.
+    public void testStaging_stagingDirIsFile() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        // Create a file with the same name as the directory that tzdatacheck expects.
+        Files.write(dataStagedDir.hostPath, new byte[] { 'a' });
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code. Failures due to staging issues are
+        // generally ignored providing the device is left in a reasonable state.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the file was just ignored. This is a fairly arbitrary choice to leave it rather
+        // than delete.
+        assertDevicePathExists(dataStagedDir);
+        assertDevicePathIsFile(dataStagedDir);
+    }
+
+    // {dataDir}/staged exists but /current dir is a file.
+    public void testStaging_uninstall_currentDirIsFile() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+
+        // Create a staged uninstall.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        createStagedUninstallOnHost(dataStagedDir);
+
+        // Create a file with the same name as the directory that tzdatacheck expects.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        Files.write(dataCurrentDir.hostPath, new byte[] { 'a' });
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the device was left in a valid "uninstalled" state.
+        assertDevicePathDoesNotExist(dataStagedDir);
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/staged contains an uninstall, but there is nothing to uninstall.
+    public void testStaging_uninstall_noCurrent() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+
+        // Set up the /data directory structure on host.
+
+        // Create a staged uninstall.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        createStagedUninstallOnHost(dataStagedDir);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code. Failures due to staging issues are
+        // generally ignored providing the device is left in a reasonable state.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the device was left in a valid "uninstalled" state.
+        assertDevicePathDoesNotExist(dataStagedDir);
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/staged contains an uninstall, and there is something to uninstall.
+    public void testStaging_uninstall_withCurrent() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+
+        // Create a staged uninstall.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        createStagedUninstallOnHost(dataStagedDir);
+
+        // Create a current installed distro.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        byte[] distroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code. Failures due to staging issues are
+        // generally ignored providing the device is left in a reasonable state.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the device was left in a valid "uninstalled" state.
+        assertDevicePathDoesNotExist(dataStagedDir);
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/staged exists but /current dir is a file.
+    public void testStaging_install_currentDirIsFile() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+
+        // Create a staged install.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        byte[] distroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataStagedDir, distroBytes);
+
+        // Create a file with the same name as the directory that tzdatacheck expects.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        Files.write(dataCurrentDir.hostPath, new byte[] { 'a' });
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code. Failures due to staging issues are
+        // generally ignored providing the device is left in a reasonable state.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the device was left in a valid "installed" state.
+        assertDevicePathDoesNotExist(dataStagedDir);
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
+    }
+
+    // {dataDir}/staged contains an install, but there is nothing to replace.
+    public void testStaging_install_noCurrent() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+
+        // Set up the /data directory structure on host.
+
+        // Create a staged install.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        byte[] stagedDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataStagedDir, stagedDistroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code. Failures due to staging issues are
+        // generally ignored providing the device is left in a reasonable state.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the device was left in a valid "installed" state.
+        assertDevicePathDoesNotExist(dataStagedDir);
+        assertDeviceDirContainsDistro(dataCurrentDir, stagedDistroBytes);
+    }
+
+    // {dataDir}/staged contains an install, and there is something to replace.
+    public void testStaging_install_withCurrent() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        DistroVersion currentDistroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION, 1, VALID_RULES_VERSION, 1);
+        DistroVersion stagedDistroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION, 1, VALID_RULES_VERSION, 2);
+
+        // Set up the /data directory structure on host.
+
+        // Create a staged uninstall.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        byte[] stagedDistroBytes = createValidDistroBuilder()
+                .setDistroVersion(stagedDistroVersion)
+                .buildBytes();
+        unpackOnHost(dataStagedDir, stagedDistroBytes);
+
+        // Create a current installed distro.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        byte[] currentDistroBytes = createValidDistroBuilder()
+                .setDistroVersion(currentDistroVersion)
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, currentDistroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code. Failures due to staging issues are
+        // generally ignored providing the device is left in a reasonable state.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the device was left in a valid "installed" state.
+        // The stagedDistro should now be the one in the current dir.
+        assertDevicePathDoesNotExist(dataStagedDir);
+        assertDeviceDirContainsDistro(dataCurrentDir, stagedDistroBytes);
+    }
+
+    // {dataDir}/staged contains an invalid install, and there is something to replace.
+    // Most of the invalid cases are tested without staging; this is just to prove that staging
+    // an invalid distro is handled the same.
+    public void testStaging_install_withCurrent_invalidStaged() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+
+        // Create a staged uninstall which contains invalid.
+        PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
+        byte[] stagedDistroBytes = createValidDistroBuilder()
+                .clearVersionForTests()
+                .buildUnvalidatedBytes();
+        unpackOnHost(dataStagedDir, stagedDistroBytes);
+
+        // Create a current installed distro.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        byte[] currentDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, currentDistroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code. The staged directory will have become the
+        // current one, but then it will be discovered to be invalid and will be removed.
+        assertEquals(3, runTzDataCheckOnDevice());
+
+        // Assert the device was left in a valid "uninstalled" state.
+        assertDevicePathDoesNotExist(dataStagedDir);
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // No {dataDir}/current exists.
+    public void testNoCurrentDataDir() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Deliberately not creating anything on host in the data dir here, leaving the empty
+        // structure.
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(0, runTzDataCheckOnDevice());
+    }
+
+    // {dataDir}/current exists but it is a file.
+    public void testCurrentDataDirIsFile() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        // Create a file with the same name as the directory that tzdatacheck expects.
+        Files.write(dataCurrentDir.hostPath, new byte[] { 'a' });
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(2, runTzDataCheckOnDevice());
+
+        // Assert the file was just ignored. This is a fairly arbitrary choice to leave it rather
+        // than delete.
+        assertDevicePathExists(dataCurrentDir);
+        assertDevicePathIsFile(dataCurrentDir);
+    }
+
+    // {dataDir}/current exists but is missing the distro version file.
+    public void testMissingDataDirDistroVersionFile() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        byte[] distroWithoutAVersionFileBytes = createValidDistroBuilder()
+                .clearVersionForTests()
+                .buildUnvalidatedBytes();
+        unpackOnHost(dataCurrentDir, distroWithoutAVersionFileBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(3, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was deleted.
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/current exists but the distro version file is short.
+    public void testShortDataDirDistroVersionFile() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        unpackOnHost(dataCurrentDir, createValidDistroBuilder().buildBytes());
+        // Replace the distro version file with a short file.
+        Path distroVersionFile =
+                dataCurrentDir.hostPath.resolve(TimeZoneDistro.DISTRO_VERSION_FILE_NAME);
+        assertHostFileExists(distroVersionFile);
+        Files.write(distroVersionFile, new byte[3]);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(3, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was deleted.
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/current exists and the distro version file is long enough, but contains junk.
+    public void testCorruptDistroVersionFile() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        unpackOnHost(dataCurrentDir, createValidDistroBuilder().buildBytes());
+
+        // Replace the distro version file with junk.
+        Path distroVersionFile =
+                dataCurrentDir.hostPath.resolve(TimeZoneDistro.DISTRO_VERSION_FILE_NAME);
+        assertHostFileExists(distroVersionFile);
+
+        int fileLength = (int) Files.size(distroVersionFile);
+        byte[] junkArray = new byte[fileLength]; // all zeros
+        Files.write(distroVersionFile, junkArray);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(4, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was deleted.
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/current exists but the distro version is incorrect.
+    public void testInvalidMajorDistroVersion_older() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        DistroVersion oldMajorDistroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION - 1, 1, VALID_RULES_VERSION, 1);
+        byte[] distroBytes = createValidDistroBuilder()
+                .setDistroVersion(oldMajorDistroVersion)
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(5, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was deleted.
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/current exists but the distro version is incorrect.
+    public void testInvalidMajorDistroVersion_newer() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        DistroVersion newMajorDistroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION + 1,
+                DistroVersion.CURRENT_FORMAT_MINOR_VERSION,
+                VALID_RULES_VERSION, VALID_REVISION);
+        byte[] distroBytes = createValidDistroBuilder()
+                .setDistroVersion(newMajorDistroVersion)
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(5, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was deleted.
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/current exists but the distro version is incorrect.
+    public void testInvalidMinorDistroVersion_older() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        DistroVersion oldMinorDistroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
+                DistroVersion.CURRENT_FORMAT_MINOR_VERSION - 1,
+                VALID_RULES_VERSION, 1);
+        byte[] distroBytes = createValidDistroBuilder()
+                .setDistroVersion(oldMinorDistroVersion)
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(5, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was deleted.
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    // {dataDir}/current exists but the distro version is newer (which is accepted because it should
+    // be backwards compatible).
+    public void testValidMinorDistroVersion_newer() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(VALID_RULES_VERSION);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        DistroVersion newMajorDistroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
+                DistroVersion.CURRENT_FORMAT_MINOR_VERSION + 1,
+                VALID_RULES_VERSION, VALID_REVISION);
+        byte[] distroBytes = createValidDistroBuilder()
+                .setDistroVersion(newMajorDistroVersion)
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was not touched.
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
+    }
+
+    // {dataDir}/current is valid but the tzdata file in /system is missing.
+    public void testSystemTzDataFileMissing() throws Exception {
+        // Deliberately not writing anything in /system here.
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        byte[] validDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, validDistroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(6, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was not touched.
+        assertDeviceDirContainsDistro(dataCurrentDir, validDistroBytes);
+    }
+
+    // {dataDir}/current is valid but the tzdata file in /system has an invalid header.
+    public void testSystemTzDataFileCorrupt() throws Exception {
+        // Set up the /system directory structure on host.
+        byte[] invalidTzDataBytes = new byte[20];
+        Files.write(mSystemDir.hostPath.resolve(SYSTEM_TZDATA_FILE_NAME), invalidTzDataBytes);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        byte[] validDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, validDistroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(7, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was not touched.
+        assertDeviceDirContainsDistro(dataCurrentDir, validDistroBytes);
+    }
+
+    // {dataDir}/current is valid and the tzdata file in /system is older.
+    public void testSystemTzRulesOlder() throws Exception {
+        // Set up the /system directory structure on host.
+        createSystemTzDataFileOnHost(RULES_VERSION_ONE);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        // Newer than RULES_VERSION_ONE in /system
+        final String distroRulesVersion = RULES_VERSION_TWO;
+        DistroVersion distroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
+                DistroVersion.CURRENT_FORMAT_MINOR_VERSION, distroRulesVersion, VALID_REVISION);
+        byte[] distroBytes = createValidDistroBuilder()
+                .setDistroVersion(distroVersion)
+                .setTzDataFile(createValidTzDataBytes(distroRulesVersion))
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was not touched.
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
+    }
+
+    // {dataDir}/current is valid and the tzdata file in /system is the same (and should be kept).
+    public void testSystemTzDataSame() throws Exception {
+        // Set up the /system directory structure on host.
+        final String systemRulesVersion = VALID_RULES_VERSION;
+        createSystemTzDataFileOnHost(systemRulesVersion);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        DistroVersion distroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
+                DistroVersion.CURRENT_FORMAT_MINOR_VERSION, systemRulesVersion, VALID_REVISION);
+        byte[] distroBytes = createValidDistroBuilder()
+                .setDistroVersion(distroVersion)
+                .setTzDataFile(createValidTzDataBytes(systemRulesVersion))
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // Assert the current data directory was not touched.
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
+    }
+
+    // {dataDir}/current is valid and the tzdata file in /system is the newer.
+    public void testSystemTzDataNewer() throws Exception {
+        // Set up the /system directory structure on host.
+        String systemRulesVersion = RULES_VERSION_TWO;
+        createSystemTzDataFileOnHost(systemRulesVersion);
+
+        // Set up the /data directory structure on host.
+        PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
+        String distroRulesVersion = RULES_VERSION_ONE; // Older than the system version.
+        DistroVersion distroVersion = new DistroVersion(
+                DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
+                DistroVersion.CURRENT_FORMAT_MINOR_VERSION,
+                distroRulesVersion,
+                VALID_REVISION);
+        byte[] distroBytes = createValidDistroBuilder()
+                .setDistroVersion(distroVersion)
+                .setTzDataFile(createValidTzDataBytes(distroRulesVersion))
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
+
+        // Push the host test directory and contents to the device.
+        pushHostTestDirToDevice();
+
+        // Execute tzdatacheck and check the status code.
+        assertEquals(0, runTzDataCheckOnDevice());
+
+        // It is important the dataCurrentDir is deleted in this case - this test case is the main
+        // reason tzdatacheck exists.
+        assertDevicePathDoesNotExist(dataCurrentDir);
+    }
+
+    private void createSystemTzDataFileOnHost(String systemRulesVersion) throws IOException {
+        byte[] systemTzData = createValidTzDataBytes(systemRulesVersion);
+        Files.write(mSystemDir.hostPath.resolve(SYSTEM_TZDATA_FILE_NAME), systemTzData);
+    }
+
+    private static void createStagedUninstallOnHost(PathPair stagedDir) throws Exception {
+        createHostDirectory(stagedDir);
+
+        PathPair uninstallTombstoneFile = stagedDir.createSubPath(UNINSTALL_TOMBSTONE_FILE_NAME);
+        // Create an empty file.
+        new FileOutputStream(uninstallTombstoneFile.hostFile()).close();
+    }
+
+    private static void unpackOnHost(PathPair path, byte[] distroBytes) throws Exception {
+        createHostDirectory(path);
+        new TimeZoneDistro(distroBytes).extractTo(path.hostFile());
+    }
+
+    private static TimeZoneDistroBuilder createValidDistroBuilder() throws Exception {
+        String distroRulesVersion = VALID_RULES_VERSION;
+        DistroVersion validDistroVersion =
+                new DistroVersion(
+                        DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
+                        DistroVersion.CURRENT_FORMAT_MINOR_VERSION,
+                        distroRulesVersion, VALID_REVISION);
+        return new TimeZoneDistroBuilder()
+                .setDistroVersion(validDistroVersion)
+                .setTzDataFile(createValidTzDataBytes(distroRulesVersion))
+                .setIcuDataFile(new byte[10]);
+    }
+
+    private static byte[] createValidTzDataBytes(String rulesVersion) {
+        return new ZoneInfoTestHelper.TzDataBuilder()
+                .initializeToValid()
+                .setHeaderMagic("tzdata" + rulesVersion)
+                .build();
+    }
+
+    private int runTzDataCheckOnDevice() throws Exception {
+        return runTzDataCheckWithArgs(new String[] { mSystemDir.devicePath, mDataDir.devicePath });
+    }
+
+    private int runTzDataCheckWithArgs(String[] args) throws Exception {
+        String command = createTzDataCheckCommand(mDeviceAndroidRootDir, args);
+        return executeCommandOnDeviceWithResultCode(command).statusCode;
+    }
+
+    private static String createTzDataCheckCommand(String rootDir, String[] args) {
+        StringJoiner joiner = new StringJoiner(" ");
+        String tzDataCheckCommand = rootDir + "/bin/tzdatacheck";
+        joiner.add(tzDataCheckCommand);
+        for (String arg : args) {
+            joiner.add(arg);
+        }
+        return joiner.toString();
+    }
+
+    private static void assertHostFileExists(Path path) {
+        assertTrue(Files.exists(path));
+    }
+
+    private String executeCommandOnDeviceRaw(String command) throws DeviceNotAvailableException {
+        return getDevice().executeShellCommand(command);
+    }
+
+    private void createDeviceDirectory(PathPair dir) throws DeviceNotAvailableException {
+        executeCommandOnDeviceRaw("mkdir -p " + dir.devicePath);
+    }
+
+    private static void createHostDirectory(PathPair dir) throws Exception {
+        Files.createDirectory(dir.hostPath);
+    }
+
+    private static class ShellResult {
+        final String output;
+        final int statusCode;
+
+        private ShellResult(String output, int statusCode) {
+            this.output = output;
+            this.statusCode = statusCode;
+        }
+    }
+
+    private ShellResult executeCommandOnDeviceWithResultCode(String command) throws Exception {
+        // A file to hold the script we're going to create.
+        PathPair scriptFile = mTestRootDir.createSubPath("script.sh");
+        // A file to hold the output of the script.
+        PathPair scriptOut = mTestRootDir.createSubPath("script.out");
+
+        // The content of the script. Runs the command, capturing stdout and stderr to scriptOut
+        // and printing the result code.
+        String hostScriptContent = command + " > " + scriptOut.devicePath + " 2>&1 ; echo -n $?";
+
+        // Parse and return the result.
+        try {
+            Files.write(scriptFile.hostPath, hostScriptContent.getBytes(StandardCharsets.US_ASCII));
+
+            // Push the script to the device.
+            pushFile(scriptFile);
+
+            // Execute the script using "sh".
+            String execCommandUnderShell =
+                    mDeviceAndroidRootDir + "/bin/sh " + scriptFile.devicePath;
+            String resultCodeString = executeCommandOnDeviceRaw(execCommandUnderShell);
+
+            // Pull back scriptOut to the host and read the content.
+            pullFile(scriptOut);
+            byte[] outputBytes = Files.readAllBytes(scriptOut.hostPath);
+            String output = new String(outputBytes, StandardCharsets.US_ASCII);
+
+            int resultCode;
+            try {
+                resultCode = Integer.parseInt(resultCodeString);
+            } catch (NumberFormatException e) {
+                fail("Command: " + command
+                        + " returned a non-integer: \"" + resultCodeString + "\""
+                        + ", output=\"" + output + "\"");
+                return null;
+            }
+            return new ShellResult(output, resultCode);
+        } finally {
+            deleteDeviceFile(scriptFile, false /* failOnError */);
+            deleteDeviceFile(scriptOut, false /* failOnError */);
+            deleteHostFile(scriptFile, false /* failOnError */);
+            deleteHostFile(scriptOut, false /* failOnError */);
+        }
+    }
+
+    private void pushHostTestDirToDevice() throws Exception {
+        assertTrue(getDevice().pushDir(mTestRootDir.hostFile(), mTestRootDir.devicePath));
+    }
+
+    private void pullFile(PathPair file) throws DeviceNotAvailableException {
+        assertTrue("Could not pull file " + file.devicePath + " to " + file.hostFile(),
+                getDevice().pullFile(file.devicePath, file.hostFile()));
+    }
+
+    private void pushFile(PathPair file) throws DeviceNotAvailableException {
+        assertTrue("Could not push file " + file.hostFile() + " to " + file.devicePath,
+                getDevice().pushFile(file.hostFile(), file.devicePath));
+    }
+
+    private void deleteHostFile(PathPair file, boolean failOnError) {
+        try {
+            Files.deleteIfExists(file.hostPath);
+        } catch (IOException e) {
+            if (failOnError) {
+                fail(e);
+            }
+        }
+    }
+
+    private void deleteDeviceDirectory(PathPair dir, boolean failOnError)
+            throws DeviceNotAvailableException {
+        String deviceDir = dir.devicePath;
+        try {
+            executeCommandOnDeviceRaw("rm -r " + deviceDir);
+        } catch (Exception e) {
+            if (failOnError) {
+                throw deviceFail(e);
+            }
+        }
+    }
+
+    private void deleteDeviceFile(PathPair file, boolean failOnError)
+            throws DeviceNotAvailableException {
+        try {
+            assertDevicePathIsFile(file);
+            executeCommandOnDeviceRaw("rm " + file.devicePath);
+        } catch (Exception e) {
+            if (failOnError) {
+                throw deviceFail(e);
+            }
+        }
+    }
+
+    private static void deleteHostDirectory(PathPair dir, final boolean failOnError) {
+        Path hostPath = dir.hostPath;
+        if (Files.exists(hostPath)) {
+            Consumer<Path> pathConsumer = file -> {
+                try {
+                    Files.delete(file);
+                } catch (Exception e) {
+                    if (failOnError) {
+                        fail(e);
+                    }
+                }
+            };
+
+            try {
+                Files.walk(hostPath).sorted(Comparator.reverseOrder()).forEach(pathConsumer);
+            } catch (IOException e) {
+                fail(e);
+            }
+        }
+    }
+
+    private void assertDevicePathExists(PathPair path) throws DeviceNotAvailableException {
+        assertTrue(getDevice().doesFileExist(path.devicePath));
+    }
+
+    private void assertDeviceDirContainsDistro(PathPair distroPath, byte[] expectedDistroBytes)
+            throws Exception {
+        // Pull back just the version file and compare it.
+        File localFile = mTestRootDir.createSubPath("temp.file").hostFile();
+        try {
+            String remoteVersionFile = distroPath.devicePath + "/"
+                    + TimeZoneDistro.DISTRO_VERSION_FILE_NAME;
+            assertTrue("Could not pull file " + remoteVersionFile + " to " + localFile,
+                    getDevice().pullFile(remoteVersionFile, localFile));
+
+            byte[] bytes = Files.readAllBytes(localFile.toPath());
+            assertArrayEquals(bytes,
+                    new TimeZoneDistro(expectedDistroBytes).getDistroVersion().toBytes());
+        } finally {
+            localFile.delete();
+        }
+    }
+
+    private void assertDevicePathDoesNotExist(PathPair path) throws DeviceNotAvailableException {
+        assertFalse(getDevice().doesFileExist(path.devicePath));
+    }
+
+    private void assertDevicePathIsFile(PathPair path) throws DeviceNotAvailableException {
+        // This check cannot rely on getDevice().getFile(devicePath).isDirectory() here because that
+        // requires that the user has rights to list all files beneath each and every directory in
+        // the path. That is not the case for the shell user and the /data and /data/local
+        // directories. http://b/35753041.
+        String output = executeCommandOnDeviceRaw("stat -c %F " + path.devicePath);
+        assertTrue(path.devicePath + " not a file. Received: " + output,
+                output.startsWith("regular") && output.endsWith("file\n"));
+    }
+
+    private static DeviceNotAvailableException deviceFail(Exception e)
+            throws DeviceNotAvailableException {
+        if (e instanceof DeviceNotAvailableException) {
+            throw (DeviceNotAvailableException) e;
+        }
+        fail(e);
+        return null;
+    }
+
+    private static void fail(Exception e) {
+        e.printStackTrace();
+        fail(e.getMessage());
+    }
+
+    /** A path that has equivalents on both host and device. */
+    private static class PathPair {
+        private final Path hostPath;
+        private final String devicePath;
+
+        PathPair(Path hostPath, String devicePath) {
+            this.hostPath = hostPath;
+            this.devicePath = devicePath;
+        }
+
+        File hostFile() {
+            return hostPath.toFile();
+        }
+
+        PathPair createSubPath(String s) {
+            return new PathPair(hostPath.resolve(s), devicePath + "/" + s);
+        }
+    }
+}
diff --git a/suite/audio_quality/Android.mk b/suite/audio_quality/Android.mk
index c3404d2..9cf5dc8 100644
--- a/suite/audio_quality/Android.mk
+++ b/suite/audio_quality/Android.mk
@@ -50,8 +50,6 @@
 
 cts: $(CTS_AUDIO_QUALITY_ZIP)
 
-ifneq ($(filter cts, $(MAKECMDGOALS)),)
 $(call dist-for-goals, cts, $(CTS_AUDIO_QUALITY_ZIP))
-endif # cts
 
 endif # linux
diff --git a/suite/audio_quality/lib/Android.mk b/suite/audio_quality/lib/Android.mk
index cd19e85..2b3c22a 100644
--- a/suite/audio_quality/lib/Android.mk
+++ b/suite/audio_quality/lib/Android.mk
@@ -19,7 +19,7 @@
 LOCAL_SRC_FILES := $(call all-subdir-cpp-files)
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/include $(LOCAL_PATH)/src
 LOCAL_STATIC_LIBRARIES += libutils liblog libtinyalsa libcutils libtinyxml2
-LOCAL_CFLAGS:= -g -fno-exceptions
+LOCAL_CFLAGS:= -g -fno-exceptions -Wno-unused-parameter
 LOCAL_LDFLAGS:= -g -lrt -ldl -lm -fno-exceptions
 LOCAL_MODULE_HOST_OS := linux
 LOCAL_MODULE:= libcts_audio_quality
diff --git a/suite/audio_quality/lib/src/task/ModelBuilder.cpp b/suite/audio_quality/lib/src/task/ModelBuilder.cpp
index 78e5138..f1a506b 100644
--- a/suite/audio_quality/lib/src/task/ModelBuilder.cpp
+++ b/suite/audio_quality/lib/src/task/ModelBuilder.cpp
@@ -87,7 +87,7 @@
 {
     XMLDocument doc;
     int error = doc.LoadFile(xmlFileName.string());
-    if (error != XML_NO_ERROR) {
+    if (error != XML_SUCCESS) {
         LOGE("ModelBuilder::parseTestDescriptionXml cannot load file %s: %d", xmlFileName.string(), error);
         return NULL;
     }
diff --git a/suite/audio_quality/test/Android.mk b/suite/audio_quality/test/Android.mk
index 7a84802..f8fe13c 100644
--- a/suite/audio_quality/test/Android.mk
+++ b/suite/audio_quality/test/Android.mk
@@ -33,7 +33,7 @@
 # need to keep everything in libcts_.. Otherwise, linker will drop some
 # functions and linker error happens
 LOCAL_WHOLE_STATIC_LIBRARIES := libcts_audio_quality
-LOCAL_CFLAGS:= -g -fno-exceptions
+LOCAL_CFLAGS:= -g -fno-exceptions -Wno-unused-parameter
 LOCAL_LDFLAGS:= -g -lrt -ldl -lm -fno-exceptions -lpthread
 LOCAL_CXX_STL := libc++_static
 LOCAL_MODULE_HOST_OS := linux
diff --git a/suite/audio_quality/test/LogTest.cpp b/suite/audio_quality/test/LogTest.cpp
index 4412338..51cde10 100644
--- a/suite/audio_quality/test/LogTest.cpp
+++ b/suite/audio_quality/test/LogTest.cpp
@@ -14,6 +14,7 @@
  * the License.
  */
 
+#include <inttypes.h>
 #include <stdint.h>
 #include <gtest/gtest.h>
 
@@ -46,12 +47,14 @@
     int64_t d = 3;
     int64_t e = 4;
     int64_t f = 5;
-    printf("printf %lld %lld %lld %lld %lld %lld\n", a, b, c, d, e, f);
-    LOGD(  "logd   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGV(  "logv   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGI(  "logi   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGW(  "logw   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGE(  "loge   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
+#define PrintABCDEF "%" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 \
+    " %" PRId64
+    printf("printf " PrintABCDEF "\n", a, b, c, d, e, f);
+    LOGD(  "logd   " PrintABCDEF, a, b, c, d, e, f);
+    LOGV(  "logv   " PrintABCDEF, a, b, c, d, e, f);
+    LOGI(  "logi   " PrintABCDEF, a, b, c, d, e, f);
+    LOGW(  "logw   " PrintABCDEF, a, b, c, d, e, f);
+    LOGE(  "loge   " PrintABCDEF, a, b, c, d, e, f);
 
     Log::Instance()->setLogLevel(level);
 }
diff --git a/tests/app/app/AndroidManifest.xml b/tests/app/app/AndroidManifest.xml
index b2412f65..7d5da99 100644
--- a/tests/app/app/AndroidManifest.xml
+++ b/tests/app/app/AndroidManifest.xml
@@ -56,15 +56,6 @@
 
         <activity android:name="android.app.stubs.ActionBarActivity" />
 
-        <activity android:name="android.app.stubs.DialogStubActivity"
-            android:label="DialogStubActivity"
-            android:configChanges="keyboardHidden|orientation|screenSize">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
-            </intent-filter>
-        </activity>
-
         <activity android:name="android.app.stubs.MockActivity" android:label="MockActivity">
             <meta-data android:name="android.app.alias"
                 android:resource="@xml/alias" />
diff --git a/tests/autofillservice/AndroidTest.xml b/tests/autofillservice/AndroidTest.xml
index d4afbb3..6be93de 100644
--- a/tests/autofillservice/AndroidTest.xml
+++ b/tests/autofillservice/AndroidTest.xml
@@ -23,8 +23,6 @@
 
   <test class="com.android.tradefed.testtype.AndroidJUnitTest">
     <option name="package" value="android.autofillservice.cts" />
-    <!-- 20x default timeout of 600sec -->
-    <option name="shell-timeout" value="12000000"/>
   </test>
 
 </configuration>
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
index 56e52f5..72f5197 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
@@ -2590,13 +2590,10 @@
             assertThat(selection.getClientState().getCharSequence("clientStateKey")).isEqualTo(
                     "clientStateValue");
 
-            assertThat(selection.getEvents().size()).isEqualTo(2);
-            FillEventHistory.Event event1 = selection.getEvents().get(0);
-            assertThat(event1.getType()).isEqualTo(TYPE_DATASET_AUTHENTICATION_SELECTED);
-            assertThat(event1.getDatasetId()).isEqualTo("name");
-            FillEventHistory.Event event2 = selection.getEvents().get(1);
-            assertThat(event2.getType()).isEqualTo(TYPE_DATASET_SELECTED);
-            assertThat(event2.getDatasetId()).isNull();
+            assertThat(selection.getEvents().size()).isEqualTo(1);
+            FillEventHistory.Event event = selection.getEvents().get(0);
+            assertThat(event.getType()).isEqualTo(TYPE_DATASET_AUTHENTICATION_SELECTED);
+            assertThat(event.getDatasetId()).isEqualTo("name");
         });
     }
 
diff --git a/tests/camera/libctscamera2jni/Android.mk b/tests/camera/libctscamera2jni/Android.mk
index 4b80553..e6a078f 100644
--- a/tests/camera/libctscamera2jni/Android.mk
+++ b/tests/camera/libctscamera2jni/Android.mk
@@ -27,8 +27,6 @@
 LOCAL_C_INCLUDES := \
 	$(JNI_H_INCLUDE) \
 	system/core/include \
-	frameworks/av/include/camera/ndk \
-	frameworks/av/include/ndk \
 
 # Flags needed by DNG SDK
 LOCAL_CFLAGS := -DUNIX_ENV=1 -DqDNGBigEndian=0 -DqDNGThreadSafe=1 -DqDNGUseLibJPEG=1 -DqDNGUseXMP=0 -DqDNGValidate=1 -DqDNGValidateTarget=1 -DqAndroid=1 -fexceptions -Wsign-compare -Wno-reorder -Wframe-larger-than=20000
diff --git a/tests/camera/libctscamera2jni/native-camera-jni.cpp b/tests/camera/libctscamera2jni/native-camera-jni.cpp
index 96b9ea1..42907c4 100644
--- a/tests/camera/libctscamera2jni/native-camera-jni.cpp
+++ b/tests/camera/libctscamera2jni/native-camera-jni.cpp
@@ -29,12 +29,12 @@
 
 #include <android/native_window_jni.h>
 
-#include "NdkCameraError.h"
-#include "NdkCameraManager.h"
-#include "NdkCameraDevice.h"
-#include "NdkCameraCaptureSession.h"
-#include "NdkImage.h"
-#include "NdkImageReader.h"
+#include "camera/NdkCameraError.h"
+#include "camera/NdkCameraManager.h"
+#include "camera/NdkCameraDevice.h"
+#include "camera/NdkCameraCaptureSession.h"
+#include "media/NdkImage.h"
+#include "media/NdkImageReader.h"
 
 #define LOG_ERROR(buf, ...) sprintf(buf, __VA_ARGS__); \
                             ALOGE("%s", buf);
diff --git a/tests/dram/jni/Android.mk b/tests/dram/jni/Android.mk
index 4469cc4..1021aaa 100644
--- a/tests/dram/jni/Android.mk
+++ b/tests/dram/jni/Android.mk
@@ -26,4 +26,6 @@
 
 LOCAL_SDK_VERSION := 14
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/fragment/Android.mk b/tests/fragment/Android.mk
index 053e668..bd243c2 100644
--- a/tests/fragment/Android.mk
+++ b/tests/fragment/Android.mk
@@ -33,8 +33,7 @@
     mockito-target-minus-junit4 \
     android-common \
     compatibility-device-util \
-    ctstestrunner \
-    platform-test-annotations
+    ctstestrunner
 #LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util android-support-test
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
@@ -44,4 +43,4 @@
 
 LOCAL_SDK_VERSION := current
 
-include $(BUILD_PACKAGE)
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/jdwp/AndroidTest.xml b/tests/jdwp/AndroidTest.xml
index 192ba78..72d26b1 100644
--- a/tests/jdwp/AndroidTest.xml
+++ b/tests/jdwp/AndroidTest.xml
@@ -39,5 +39,8 @@
         <option name="known-failures" value="/expectations/jdwp-known-failures.txt" />
         <option name="runtime-hint" value="16m" />
 
+        <!-- Temporary work around to avoid running android.test.AndroidTestCase. -->
+        <!-- TODO(64541592) - remove once AndroidTestCase is not statically included. -->
+        <option name="exclude-filter" value="android.test.AndroidTestCase" />
     </test>
 </configuration>
diff --git a/tests/libcore/jsr166/Android.mk b/tests/libcore/jsr166/Android.mk
index e71bb57..bc01844 100644
--- a/tests/libcore/jsr166/Android.mk
+++ b/tests/libcore/jsr166/Android.mk
@@ -36,10 +36,6 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
-LOCAL_JAVA_RESOURCE_FILES := \
-    libcore/expectations/brokentests.txt \
-    libcore/expectations/icebox.txt \
-    libcore/expectations/knownfailures.txt \
-    libcore/expectations/taggedtests.txt
+LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/libcore/jsr166/AndroidTest.xml b/tests/libcore/jsr166/AndroidTest.xml
index 865f805..2a3e5d2 100644
--- a/tests/libcore/jsr166/AndroidTest.xml
+++ b/tests/libcore/jsr166/AndroidTest.xml
@@ -32,9 +32,6 @@
         <option name="instrumentation-arg" key="filter"
                 value="com.android.cts.core.runner.ExpectationBasedFilter" />
         <option name="core-expectation" value="/knownfailures.txt" />
-        <option name="core-expectation" value="/brokentests.txt" />
-        <option name="core-expectation" value="/icebox.txt" />
-        <option name="core-expectation" value="/taggedtests.txt" />
         <option name="runtime-hint" value="10m"/>
         <!-- 20x default timeout of 600sec -->
         <option name="shell-timeout" value="12000000"/>
diff --git a/tests/libcore/luni/Android.mk b/tests/libcore/luni/Android.mk
index c42a987..cdba3f9 100644
--- a/tests/libcore/luni/Android.mk
+++ b/tests/libcore/luni/Android.mk
@@ -24,8 +24,8 @@
     core-tests \
     cts-core-test-runner \
     mockito-target-minus-junit4 \
-    tzdata_shared2-tests \
-    tzdata_update2-tests
+    time_zone_distro-tests \
+    time_zone_distro_installer-tests
 
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
@@ -38,7 +38,8 @@
 LOCAL_DX_FLAGS := --multi-dex
 
 LOCAL_PROGUARD_ENABLED := disabled
-
+# Keep META-INF/ resources from LOCAL_STATIC_JAVA_LIBRARIES. http://b/62341677
+LOCAL_DONT_DELETE_JAR_META_INF := true
 LOCAL_JNI_SHARED_LIBRARIES := libjavacoretests libsqlite_jni libnativehelper_compat_libc++ libc++
 
 # Include both the 32 and 64 bit versions of libjavacoretests,
@@ -48,11 +49,10 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
+# NOTE: virtualdeviceknownfailures.txt is only used for simulated/cloud-based
+# continuous build configurations, so it's not referenced in AndroidTest.xml
 LOCAL_JAVA_RESOURCE_FILES := \
-    libcore/expectations/brokentests.txt \
-    libcore/expectations/icebox.txt \
     libcore/expectations/knownfailures.txt \
-    libcore/expectations/taggedtests.txt \
     libcore/expectations/virtualdeviceknownfailures.txt
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/libcore/luni/AndroidTest.xml b/tests/libcore/luni/AndroidTest.xml
index 4abb65c..a8c4142 100644
--- a/tests/libcore/luni/AndroidTest.xml
+++ b/tests/libcore/luni/AndroidTest.xml
@@ -32,9 +32,6 @@
         <option name="instrumentation-arg" key="filter"
                 value="com.android.cts.core.runner.ExpectationBasedFilter" />
         <option name="core-expectation" value="/knownfailures.txt" />
-        <option name="core-expectation" value="/brokentests.txt" />
-        <option name="core-expectation" value="/icebox.txt" />
-        <option name="core-expectation" value="/taggedtests.txt" />
         <option name="runtime-hint" value="45m"/>
         <!-- 20x default timeout of 600sec -->
         <option name="shell-timeout" value="12000000"/>
diff --git a/tests/libcore/ojluni/Android.mk b/tests/libcore/ojluni/Android.mk
index 36ba4f2..1dd6b4f 100644
--- a/tests/libcore/ojluni/Android.mk
+++ b/tests/libcore/ojluni/Android.mk
@@ -21,6 +21,10 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
     core-ojtests-public
 
+LOCAL_JAVA_LIBRARIES := testng
+
+LOCAL_DX_FLAGS := --core-library
+
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
 
@@ -30,6 +34,9 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_JACK_FLAGS := --multi-dex native
 
+# Keep META-INF/ resources from LOCAL_STATIC_JAVA_LIBRARIES. http://b/62231394
+LOCAL_DONT_DELETE_JAR_META_INF := true
+
 LOCAL_PROGUARD_ENABLED := disabled
 
 # Include both the 32 and 64 bit versions of libjavacoretests,
@@ -39,10 +46,6 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
-LOCAL_JAVA_RESOURCE_FILES := \
-    libcore/expectations/brokentests.txt \
-    libcore/expectations/icebox.txt \
-    libcore/expectations/knownfailures.txt \
-    libcore/expectations/taggedtests.txt
+LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/libcore/ojluni/AndroidTest.xml b/tests/libcore/ojluni/AndroidTest.xml
index 2eb644e..9bf7113 100644
--- a/tests/libcore/ojluni/AndroidTest.xml
+++ b/tests/libcore/ojluni/AndroidTest.xml
@@ -34,10 +34,6 @@
         <option name="instrumentation-arg" key="core-listener"
                 value="com.android.cts.runner.CtsTestRunListener"/>
         <option name="core-expectation" value="/knownfailures.txt" />
-        <option name="core-expectation" value="/brokentests.txt" />
-        <option name="core-expectation" value="/icebox.txt" />
-        <option name="core-expectation" value="/taggedtests.txt" />
-        <option name="core-expectation" value="/expectations/cts-runner-specific-failures.txt" />
         <option name="runtime-hint" value="35m"/>
         <!-- 20x default timeout of 600sec -->
         <option name="shell-timeout" value="12000000"/>
diff --git a/tests/libcore/okhttp/Android.mk b/tests/libcore/okhttp/Android.mk
index 840f1a2..c308b59 100644
--- a/tests/libcore/okhttp/Android.mk
+++ b/tests/libcore/okhttp/Android.mk
@@ -42,10 +42,6 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
-LOCAL_JAVA_RESOURCE_FILES := \
-    libcore/expectations/brokentests.txt \
-    libcore/expectations/icebox.txt \
-    libcore/expectations/knownfailures.txt \
-    libcore/expectations/taggedtests.txt
+LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/libcore/okhttp/AndroidTest.xml b/tests/libcore/okhttp/AndroidTest.xml
index 970fd8e..4e79b80 100644
--- a/tests/libcore/okhttp/AndroidTest.xml
+++ b/tests/libcore/okhttp/AndroidTest.xml
@@ -32,9 +32,6 @@
         <option name="instrumentation-arg" key="filter"
                 value="com.android.cts.core.runner.ExpectationBasedFilter" />
         <option name="core-expectation" value="/knownfailures.txt" />
-        <option name="core-expectation" value="/brokentests.txt" />
-        <option name="core-expectation" value="/icebox.txt" />
-        <option name="core-expectation" value="/taggedtests.txt" />
         <option name="runtime-hint" value="15m"/>
         <!-- 20x default timeout of 600sec -->
         <option name="shell-timeout" value="12000000"/>
diff --git a/tests/libcore/wycheproof-bc/Android.mk b/tests/libcore/wycheproof-bc/Android.mk
new file mode 100644
index 0000000..3751ac5
--- /dev/null
+++ b/tests/libcore/wycheproof-bc/Android.mk
@@ -0,0 +1,49 @@
+# 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_PACKAGE_NAME := CtsLibcoreWycheproofBCTestCases
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-core-test-runner \
+    wycheproof
+
+LOCAL_JAVA_LIBRARIES := bouncycastle
+
+# Don't include this package in any target
+LOCAL_MODULE_TAGS := tests
+
+# When built, explicitly put it in the data partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under,src)
+
+LOCAL_DEX_PREOPT := false
+LOCAL_JACK_FLAGS := --multi-dex native
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+# Include both the 32 and 64 bit versions of libjavacoretests,
+# where applicable.
+LOCAL_MULTILIB := both
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/vm-tests-tf/AndroidManifest.xml b/tests/libcore/wycheproof-bc/AndroidManifest.xml
similarity index 69%
rename from tests/vm-tests-tf/AndroidManifest.xml
rename to tests/libcore/wycheproof-bc/AndroidManifest.xml
index 2a2f40a..15c5fd5 100644
--- a/tests/vm-tests-tf/AndroidManifest.xml
+++ b/tests/libcore/wycheproof-bc/AndroidManifest.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- * Copyright (C) 2007 The Android Open Source Project
+ * Copyright (C) 2017 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -15,15 +15,14 @@
  * limitations under the License.
  -->
 
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.core.vm-tests-tf">
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.libcore.cts.wycheproof.bouncycastle">
     <uses-permission android:name="android.permission.INTERNET" />
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
 
-    <instrumentation android:name="android.test.InstrumentationCoreTestRunner"
-                     android:targetPackage="android.core.vm-tests-tf"
-                     android:label="cts trade federation vm tests"/>
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.libcore.cts.wycheproof.bouncycastle"
+                     android:label="CTS Libcore Wycheproof Bouncy Castle test cases" />
 
 </manifest>
diff --git a/tests/libcore/wycheproof-bc/AndroidTest.xml b/tests/libcore/wycheproof-bc/AndroidTest.xml
new file mode 100644
index 0000000..4e9c320
--- /dev/null
+++ b/tests/libcore/wycheproof-bc/AndroidTest.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.
+-->
+<configuration description="Config for CTS Libcore Wycheproof Bouncy Castle test cases">
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.ApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <!-- this has just the instrumentation which acts as the tests we want to run -->
+        <option name="test-file-name" value="CtsLibcoreWycheproofBCTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.compatibility.testtype.LibcoreTest" >
+        <option name="package" value="android.libcore.cts.wycheproof.bouncycastle" />
+        <!-- The individual test cases don't work unless they're run in the
+             context of one of the suites, so we have to limit the test
+             infrastructure to only running the test suites. -->
+        <option name="test-package" value="android.libcore.cts.wycheproof" />
+        <option name="instrumentation-arg" key="listener"
+                value="com.android.cts.runner.CtsTestRunListener" />
+        <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"/>
+    </test>
+</configuration>
diff --git a/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleSupportProvider.java b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleSupportProvider.java
new file mode 100644
index 0000000..d6ab5c1
--- /dev/null
+++ b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleSupportProvider.java
@@ -0,0 +1,48 @@
+/*
+ * 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.libcore.cts.wycheproof;
+
+import java.security.Provider;
+
+/**
+ * Provides a small number of exports to allow Bouncy Castle tests to function properly.
+ * Our modified version of Bouncy Castle depends on Conscrypt for a few pieces of
+ * functionality, but in tests we don't want to have Conscrypt installed so that we can test
+ * Bouncy Castle properly.  We install this provider instead.
+ */
+public class BouncyCastleSupportProvider extends Provider {
+
+    // The classes are jarjared, so this is the prefix in practice.
+    private static final String PREFIX = "com.android.org.conscrypt.";
+
+    public BouncyCastleSupportProvider() {
+        // Our modified version of Bouncy Castle specifically expects certain algorithms
+        // to be provided by a provider named "AndroidOpenSSL", so we use that name
+        super("AndroidOpenSSL", 0.0,
+                "Provides algorithms that Bouncy Castle needs to work in tests");
+
+        // Conscrypt is the only SecureRandom implementation
+        put("SecureRandom.SHA1PRNG", PREFIX + "OpenSSLRandom");
+
+        // Bouncy Castle's MACs are backed by Conscrypt's MessageDigests
+        put("MessageDigest.SHA-1", PREFIX + "OpenSSLMessageDigestJDK$SHA1");
+        put("MessageDigest.SHA-224", PREFIX + "OpenSSLMessageDigestJDK$SHA224");
+        put("MessageDigest.SHA-256", PREFIX + "OpenSSLMessageDigestJDK$SHA256");
+        put("MessageDigest.SHA-384", PREFIX + "OpenSSLMessageDigestJDK$SHA384");
+        put("MessageDigest.SHA-512", PREFIX + "OpenSSLMessageDigestJDK$SHA512");
+    }
+}
diff --git a/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
new file mode 100644
index 0000000..dfb71e8
--- /dev/null
+++ b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
@@ -0,0 +1,91 @@
+/*
+ * 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.libcore.cts.wycheproof;
+
+import com.android.org.bouncycastle.jce.provider.BouncyCastleProvider;
+import com.google.security.wycheproof.AesGcmTest;
+import com.google.security.wycheproof.BasicTest;
+import com.google.security.wycheproof.CipherInputStreamTest;
+import com.google.security.wycheproof.CipherOutputStreamTest;
+import com.google.security.wycheproof.DhTest;
+import com.google.security.wycheproof.DhiesTest;
+import com.google.security.wycheproof.DsaTest;
+import com.google.security.wycheproof.EcKeyTest;
+import com.google.security.wycheproof.EcdhTest;
+import com.google.security.wycheproof.EcdsaTest;
+import com.google.security.wycheproof.RsaEncryptionTest;
+import com.google.security.wycheproof.RsaKeyTest;
+import com.google.security.wycheproof.RsaSignatureTest;
+import com.google.security.wycheproof.TestUtil;
+import com.google.security.wycheproof.WycheproofRunner;
+import com.google.security.wycheproof.WycheproofRunner.Fast;
+import com.google.security.wycheproof.WycheproofRunner.Provider;
+import com.google.security.wycheproof.WycheproofRunner.ProviderType;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite.SuiteClasses;
+
+import java.security.Security;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Checks that our Bouncy Castle provider properly implements all its functionality.
+ */
+@RunWith(WycheproofRunner.class)
+@SuiteClasses({
+        AesGcmTest.class,
+        BasicTest.class,
+        CipherInputStreamTest.class,
+        CipherOutputStreamTest.class,
+        DhTest.class,
+        DhiesTest.class,
+        DsaTest.class,
+        EcKeyTest.class,
+        EcdhTest.class,
+        EcdsaTest.class,
+        RsaEncryptionTest.class,
+        RsaKeyTest.class,
+        RsaSignatureTest.class,
+})
+@Provider(ProviderType.BOUNCY_CASTLE)
+@Fast
+public final class BouncyCastleTest {
+
+    private static final List<java.security.Provider> previousProviders = new ArrayList<>();
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        previousProviders.clear();
+        previousProviders.addAll(Arrays.asList(Security.getProviders()));
+        TestUtil.installOnlyThisProvider(new BouncyCastleProvider());
+        Security.addProvider(new BouncyCastleSupportProvider());
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        for (java.security.Provider p : Security.getProviders()) {
+            Security.removeProvider(p.getName());
+        }
+        for (java.security.Provider p : previousProviders) {
+            Security.addProvider(p);
+        }
+    }
+}
diff --git a/tests/libcore/wycheproof/Android.mk b/tests/libcore/wycheproof/Android.mk
new file mode 100644
index 0000000..bfcdda5
--- /dev/null
+++ b/tests/libcore/wycheproof/Android.mk
@@ -0,0 +1,49 @@
+# 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_PACKAGE_NAME := CtsLibcoreWycheproofConscryptTestCases
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-core-test-runner \
+    wycheproof
+
+LOCAL_JAVA_LIBRARIES := conscrypt
+
+# Don't include this package in any target
+LOCAL_MODULE_TAGS := tests
+
+# When built, explicitly put it in the data partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under,src)
+
+LOCAL_DEX_PREOPT := false
+LOCAL_JACK_FLAGS := --multi-dex native
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+# Include both the 32 and 64 bit versions of libjavacoretests,
+# where applicable.
+LOCAL_MULTILIB := both
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/vm-tests-tf/AndroidManifest.xml b/tests/libcore/wycheproof/AndroidManifest.xml
similarity index 69%
copy from tests/vm-tests-tf/AndroidManifest.xml
copy to tests/libcore/wycheproof/AndroidManifest.xml
index 2a2f40a..765c677 100644
--- a/tests/vm-tests-tf/AndroidManifest.xml
+++ b/tests/libcore/wycheproof/AndroidManifest.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- * Copyright (C) 2007 The Android Open Source Project
+ * Copyright (C) 2017 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -15,15 +15,14 @@
  * limitations under the License.
  -->
 
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.core.vm-tests-tf">
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.libcore.cts.wycheproof.conscrypt">
     <uses-permission android:name="android.permission.INTERNET" />
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
 
-    <instrumentation android:name="android.test.InstrumentationCoreTestRunner"
-                     android:targetPackage="android.core.vm-tests-tf"
-                     android:label="cts trade federation vm tests"/>
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.libcore.cts.wycheproof.conscrypt"
+                     android:label="CTS Libcore Wycheproof Conscrypt test cases" />
 
 </manifest>
diff --git a/tests/libcore/wycheproof/AndroidTest.xml b/tests/libcore/wycheproof/AndroidTest.xml
new file mode 100644
index 0000000..bab6eed
--- /dev/null
+++ b/tests/libcore/wycheproof/AndroidTest.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.
+-->
+<configuration description="Config for CTS Libcore Wycheproof Conscrypt test cases">
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.ApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <!-- this has just the instrumentation which acts as the tests we want to run -->
+        <option name="test-file-name" value="CtsLibcoreWycheproofConscryptTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.compatibility.testtype.LibcoreTest" >
+        <option name="package" value="android.libcore.cts.wycheproof.conscrypt" />
+        <!-- The individual test cases don't work unless they're run in the
+             context of one of the suites, so we have to limit the test
+             infrastructure to only running the test suites. -->
+        <option name="test-package" value="android.libcore.cts.wycheproof" />
+        <option name="instrumentation-arg" key="listener"
+                value="com.android.cts.runner.CtsTestRunListener" />
+        <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"/>
+    </test>
+</configuration>
diff --git a/tests/libcore/wycheproof/src/android/libcore/cts/wycheproof/ConscryptTest.java b/tests/libcore/wycheproof/src/android/libcore/cts/wycheproof/ConscryptTest.java
new file mode 100644
index 0000000..bee62fa
--- /dev/null
+++ b/tests/libcore/wycheproof/src/android/libcore/cts/wycheproof/ConscryptTest.java
@@ -0,0 +1,84 @@
+/*
+ * 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.libcore.cts.wycheproof;
+
+import com.android.org.conscrypt.OpenSSLProvider;
+import com.google.security.wycheproof.AesGcmTest;
+import com.google.security.wycheproof.BasicTest;
+import com.google.security.wycheproof.CipherInputStreamTest;
+import com.google.security.wycheproof.CipherOutputStreamTest;
+import com.google.security.wycheproof.EcKeyTest;
+import com.google.security.wycheproof.EcdhTest;
+import com.google.security.wycheproof.EcdsaTest;
+import com.google.security.wycheproof.RsaEncryptionTest;
+import com.google.security.wycheproof.RsaKeyTest;
+import com.google.security.wycheproof.RsaSignatureTest;
+import com.google.security.wycheproof.TestUtil;
+import com.google.security.wycheproof.WycheproofRunner;
+import com.google.security.wycheproof.WycheproofRunner.Fast;
+import com.google.security.wycheproof.WycheproofRunner.Provider;
+import com.google.security.wycheproof.WycheproofRunner.ProviderType;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite.SuiteClasses;
+
+import java.security.Security;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Checks that our Conscrypt provider properly implements all its functionality.
+ */
+@RunWith(WycheproofRunner.class)
+@SuiteClasses({
+        AesGcmTest.class,
+        BasicTest.class,
+        CipherInputStreamTest.class,
+        CipherOutputStreamTest.class,
+        EcKeyTest.class,
+        EcdhTest.class,
+        EcdsaTest.class,
+        RsaEncryptionTest.class,
+        RsaKeyTest.class,
+        RsaSignatureTest.class
+})
+@Provider(ProviderType.CONSCRYPT)
+@Fast
+public final class ConscryptTest {
+
+    private static final List<java.security.Provider> previousProviders = new ArrayList<>();
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        previousProviders.clear();
+        previousProviders.addAll(Arrays.asList(Security.getProviders()));
+        TestUtil.installOnlyThisProvider(new OpenSSLProvider());
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        for (java.security.Provider p : Security.getProviders()) {
+            Security.removeProvider(p.getName());
+        }
+        for (java.security.Provider p : previousProviders) {
+            Security.addProvider(p);
+        }
+    }
+}
diff --git a/tests/openglperf2/jni/Android.mk b/tests/openglperf2/jni/Android.mk
index c2bb7a8..174375d 100644
--- a/tests/openglperf2/jni/Android.mk
+++ b/tests/openglperf2/jni/Android.mk
@@ -21,6 +21,8 @@
 # Needed in order to use fences for synchronization
 LOCAL_CFLAGS += -DEGL_EGLEXT_PROTOTYPES -funsigned-char
 
+LOCAL_CFLAGS += -Wno-unused-parameter
+
 # Get all cpp files but not hidden files
 LOCAL_SRC_FILES := $(call all-subdir-cpp-files)
 
diff --git a/tests/sensor/Android.mk b/tests/sensor/Android.mk
index 7b6dd32..387e05f 100644
--- a/tests/sensor/Android.mk
+++ b/tests/sensor/Android.mk
@@ -32,7 +32,7 @@
 LOCAL_SDK_VERSION := current
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
+-include cts/error_prone_rules_tests.mk
 include $(BUILD_STATIC_JAVA_LIBRARY)
 
 #
diff --git a/tests/sensor/src/android/hardware/cts/SensorBatchingTests.java b/tests/sensor/src/android/hardware/cts/SensorBatchingTests.java
index cb4076c..1b2b25c 100644
--- a/tests/sensor/src/android/hardware/cts/SensorBatchingTests.java
+++ b/tests/sensor/src/android/hardware/cts/SensorBatchingTests.java
@@ -87,11 +87,11 @@
         runBatchingSensorTest(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED, RATE_50HZ, BATCHING_PERIOD);
     }
 
-    public void tesAccelUncalibrated_fastest_flush() throws Throwable {
+    public void testAccelUncalibrated_fastest_flush() throws Throwable {
         runFlushSensorTest(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED, RATE_FASTEST, BATCHING_PERIOD);
     }
 
-    public void tesAccelUncalibrated_50hz_flush() throws Throwable {
+    public void testAccelUncalibrated_50hz_flush() throws Throwable {
         runFlushSensorTest(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED, RATE_50HZ, BATCHING_PERIOD);
     }
 
diff --git a/tests/sensor/src/android/hardware/cts/helpers/FrameworkUnitTests.java b/tests/sensor/src/android/hardware/cts/helpers/FrameworkUnitTests.java
index 87a9a2e..6480f55 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/FrameworkUnitTests.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/FrameworkUnitTests.java
@@ -23,6 +23,7 @@
 import android.hardware.cts.helpers.sensorverification.EventGapVerificationTest;
 import android.hardware.cts.helpers.sensorverification.EventOrderingVerificationTest;
 import android.hardware.cts.helpers.sensorverification.FrequencyVerificationTest;
+import android.hardware.cts.helpers.sensorverification.InitialValueVerificationTest;
 import android.hardware.cts.helpers.sensorverification.JitterVerificationTest;
 import android.hardware.cts.helpers.sensorverification.MagnitudeVerificationTest;
 import android.hardware.cts.helpers.sensorverification.MeanVerificationTest;
@@ -42,12 +43,13 @@
         addTestSuite(SensorStatsTest.class);
 
         // sensorverification
+        addTestSuite(EventGapVerificationTest.class);
         addTestSuite(EventOrderingVerificationTest.class);
         addTestSuite(FrequencyVerificationTest.class);
+        addTestSuite(InitialValueVerificationTest.class);
         addTestSuite(JitterVerificationTest.class);
         addTestSuite(MagnitudeVerificationTest.class);
         addTestSuite(MeanVerificationTest.class);
-        addTestSuite(EventGapVerificationTest.class);
         addTestSuite(StandardDeviationVerificationTest.class);
         addTestSuite(TimestampClockSourceVerificationTest.class);
 
diff --git a/tests/sensor/src/android/hardware/cts/helpers/SensorCtsHelper.java b/tests/sensor/src/android/hardware/cts/helpers/SensorCtsHelper.java
index db9c5a5..bbe2006 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/SensorCtsHelper.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/SensorCtsHelper.java
@@ -228,6 +228,30 @@
     }
 
     /**
+     * Format an array of floats.
+     *
+     * @param array the array of floats
+     *
+     * @return The formatted string
+     */
+    public static String formatFloatArray(float[] array) {
+        StringBuilder sb = new StringBuilder();
+        if (array.length > 1) {
+            sb.append("(");
+        }
+        for (int i = 0; i < array.length; i++) {
+            sb.append(String.format("%.2f", array[i]));
+            if (i != array.length - 1) {
+                sb.append(", ");
+            }
+        }
+        if (array.length > 1) {
+            sb.append(")");
+        }
+        return sb.toString();
+    }
+
+    /**
      * @return A {@link File} representing a root directory to store sensor tests data.
      */
     public static File getSensorTestDataDirectory() throws IOException {
diff --git a/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java b/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java
index bc3db99..3892366 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/SensorStats.java
@@ -64,6 +64,8 @@
     public static final String STANDARD_DEVIATION_KEY = "standard_deviation";
     public static final String MAGNITUDE_KEY = "magnitude";
     public static final String DELAYED_BATCH_DELIVERY = "delayed_batch_delivery";
+    public static final String INITIAL_MEAN_KEY = "initial_mean";
+    public static final String LATER_MEAN_KEY = "later_mean";
 
     private final Map<String, Object> mValues = new HashMap<>();
     private final Map<String, SensorStats> mSensorStats = new HashMap<>();
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java
index 30da9a0..abfa692 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/SensorOperationTest.java
@@ -59,7 +59,7 @@
         op = new FakeSensorOperation(true, 0, TimeUnit.MILLISECONDS);
         try {
             op.execute(mTestNode);
-            fail("AssertionError expected");
+            throw new Error("AssertionError expected");
         } catch (AssertionError e) {
             // Expected
         }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java b/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
index 8201861..ad2084d 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
@@ -40,6 +40,7 @@
 import android.hardware.cts.helpers.sensorverification.JitterVerification;
 import android.hardware.cts.helpers.sensorverification.MagnitudeVerification;
 import android.hardware.cts.helpers.sensorverification.MeanVerification;
+import android.hardware.cts.helpers.sensorverification.InitialValueVerification;
 import android.hardware.cts.helpers.sensorverification.StandardDeviationVerification;
 import android.os.Handler;
 import android.os.SystemClock;
@@ -110,6 +111,7 @@
         addVerification(MeanVerification.getDefault(mEnvironment));
         addVerification(StandardDeviationVerification.getDefault(mEnvironment));
         addVerification(EventTimestampSynchronizationVerification.getDefault(mEnvironment));
+        addVerification(InitialValueVerification.getDefault(mEnvironment));
     }
 
     public void addVerification(ISensorVerification verification) {
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventBasicVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventBasicVerificationTest.java
index 34be3c4..b682ac5 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventBasicVerificationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventBasicVerificationTest.java
@@ -65,7 +65,7 @@
 
         try {
             verification.verify(stats);
-            fail("Expect an AssertionError due to insufficient samples");
+            throw new Error("Expect an AssertionError due to insufficient samples");
         } catch (AssertionError e) {
             //Expected
         }
@@ -81,7 +81,7 @@
 
             try {
                 verification.verify(stats);
-                fail("Expect an AssertionError due to wrong sensor event");
+                throw new Error("Expect an AssertionError due to wrong sensor event");
             } catch (AssertionError e) {
                 //Expected
             }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
index f1dc229c8..9cb7436 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
@@ -58,7 +58,7 @@
         EventOrderingVerification verification = getVerification(0, 2, 1, 3, 4);
         try {
             verification.verify(stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
@@ -75,7 +75,7 @@
         EventOrderingVerification verification = getVerification(4, 0, 1, 2, 3);
         try {
             verification.verify(stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java
index bbf022a..8780a7d 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java
@@ -55,7 +55,7 @@
         verification = getVerification(850.0, 975.0, timestamps);
         try {
             verification.verify(getEnvironment(950), stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
@@ -65,7 +65,7 @@
         verification = getVerification(1025.0, 1150.0, timestamps);
         try {
             verification.verify(getEnvironment(1050), stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/InitialValueVerification.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/InitialValueVerification.java
new file mode 100644
index 0000000..da6a013
--- /dev/null
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/InitialValueVerification.java
@@ -0,0 +1,187 @@
+/*
+ * 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.hardware.cts.helpers.sensorverification;
+
+import android.hardware.Sensor;
+import android.hardware.cts.helpers.SensorCtsHelper;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+import android.util.Pair;
+
+import junit.framework.Assert;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A {@link ISensorVerification} which verifies that there are no ramps when starting the
+ * collection. To verify this, we compute the mean value at the beginning of the collection and
+ * compare it to the mean value at the end of the collection.
+ */
+public class InitialValueVerification extends AbstractSensorVerification {
+    public static final String PASSED_KEY = "initial_value_passed";
+    // Default length of the initial window: 2 seconds in ns
+    private static final long DEFAULT_INITIAL_WINDOW_LENGTH = 2_000_000_000L;
+
+    // sensorType: max absolute delta between the two means and initial window length
+    private static final Map<Integer, Pair<Float, Long>> DEFAULTS =
+        new HashMap<Integer, Pair<Float, Long>>(12);
+
+    static {
+        // Use a method so that the @deprecation warning can be set for that method only
+        setDefaults();
+    }
+
+    // First time stamp in nano seconds
+    private long mFirstTimestamp;
+    private float[] mInitialSum = null;
+    private int mInitialCount = 0;
+    private float[] mLaterSum = null;
+    private int mLaterCount = 0;
+
+    private final float mMaxAbsoluteDelta;
+    private final long mInitialWindowLength;
+
+    /**
+     * Construct a {@link InitialValueVerification}
+     *
+     * @param maxAbsoluteDelta the acceptable max absolute delta between the two means.
+     */
+    public InitialValueVerification(float maxAbsoluteDelta, long initialWindowLength) {
+        mMaxAbsoluteDelta = maxAbsoluteDelta;
+        mInitialWindowLength = initialWindowLength;
+    }
+
+    /**
+     * Get the default {@link InitialValueVerification} for a sensor.
+     *
+     * @param environment the test environment
+     * @return the verification or null if the verification does not apply to the sensor.
+     */
+    public static InitialValueVerification getDefault(TestSensorEnvironment environment) {
+        int sensorType = environment.getSensor().getType();
+        if (!DEFAULTS.containsKey(sensorType)) {
+            return null;
+        }
+        Pair<Float, Long> maxAbsoluteDeltaAndInitialWindowLength = DEFAULTS.get(sensorType);
+        return new InitialValueVerification(maxAbsoluteDeltaAndInitialWindowLength.first,
+                                            maxAbsoluteDeltaAndInitialWindowLength.second);
+    }
+
+    /**
+     * Verify that the mean at the initial window and later are similar to each other. Add
+     * {@value #PASSED_KEY}, {@value SensorStats#INITIAL_MEAN_KEY},
+     * {@value SensorStats#LATER_MEAN_KEY} keys to {@link SensorStats}.
+     *
+     * @throws AssertionError if the verification failed.
+     */
+    @Override
+    public void verify(TestSensorEnvironment environment, SensorStats stats) {
+        verify(stats);
+    }
+
+    /**
+     * Visible for unit tests only.
+     */
+    void verify(SensorStats stats) {
+        if (mInitialCount == 0) {
+            Assert.fail("Didn't collect any measurements");
+        }
+        if (mLaterCount == 0) {
+            Assert.fail(String.format("Didn't collect any measurements after %dns",
+                    mInitialWindowLength));
+        }
+        float[] initialMeans = new float[mInitialSum.length];
+        float[] laterMeans = new float[mInitialSum.length];
+        boolean success = true;
+        for (int i = 0; i < mInitialSum.length; i++) {
+            initialMeans[i] = mInitialSum[i] / mInitialCount;
+            laterMeans[i] = mLaterSum[i] / mLaterCount;
+            if (Math.abs(initialMeans[i] - laterMeans[i]) > mMaxAbsoluteDelta) {
+                success = false;
+            }
+        }
+        stats.addValue(SensorStats.INITIAL_MEAN_KEY, initialMeans);
+        stats.addValue(SensorStats.LATER_MEAN_KEY, laterMeans);
+        stats.addValue(PASSED_KEY, success);
+        if (!success) {
+            Assert.fail(String.format(
+                    "Means too far from each other: initial means = %s,"
+                            + "later means = %s, max allowed delta = %.2f",
+                    SensorCtsHelper.formatFloatArray(initialMeans),
+                    SensorCtsHelper.formatFloatArray(laterMeans),
+                    mMaxAbsoluteDelta));
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public InitialValueVerification clone() {
+        return new InitialValueVerification(mMaxAbsoluteDelta, mInitialWindowLength);
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    protected void addSensorEventInternal(TestSensorEvent event) {
+        if (mInitialSum == null) {
+            mFirstTimestamp = event.timestamp;
+            mInitialSum = new float[event.values.length];
+            mLaterSum = new float[event.values.length];
+        }
+        if (event.timestamp - mFirstTimestamp <= mInitialWindowLength) {
+            for (int i = 0; i < event.values.length; i++) {
+                mInitialSum[i] += event.values[i];
+            }
+            mInitialCount++;
+        } else {
+            for (int i = 0; i < event.values.length; i++) {
+                mLaterSum[i] += event.values[i];
+            }
+            mLaterCount++;
+        }
+    }
+
+    @SuppressWarnings("deprecation")
+    private static void setDefaults() {
+        DEFAULTS.put(Sensor.TYPE_ACCELEROMETER,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_MAGNETIC_FIELD,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_GYROSCOPE,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_GYROSCOPE_UNCALIBRATED,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_ORIENTATION,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        // Very tight absolute delta for the barometer.
+        DEFAULTS.put(Sensor.TYPE_PRESSURE,
+                new Pair<Float, Long>(3f, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_GRAVITY,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_LINEAR_ACCELERATION,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_ROTATION_VECTOR,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_GAME_ROTATION_VECTOR,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+        DEFAULTS.put(Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR,
+                new Pair<Float, Long>(Float.MAX_VALUE, DEFAULT_INITIAL_WINDOW_LENGTH));
+    }
+}
+
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/InitialValueVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/InitialValueVerificationTest.java
new file mode 100644
index 0000000..5e28d26
--- /dev/null
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/InitialValueVerificationTest.java
@@ -0,0 +1,127 @@
+/*
+ * 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.hardware.cts.helpers.sensorverification;
+
+import junit.framework.TestCase;
+
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Random;
+
+/**
+ * Tests for {@link InitialValueVerification}.
+ */
+public class InitialValueVerificationTest extends TestCase {
+    private static final long INITIAL_WINDOW_LENGTH = 2_000_000_000L; // 2s
+    private static final long TOTAL_WINDOW_LENGTH = 5_000_000_000L; // 5s
+    private static final long SENSOR_PERIOD = 500_000_000L; // 0.5s
+    private static final float MAX_ABSOLUTE_DELTA = 3f;
+    private static final Random random = new Random(123L);
+    private static final float NOISE_STD = 0.01f;
+
+    /**
+     * Test {@link InitialValueVerification#verify(SensorStats)}.
+     */
+    public void testVerify() {
+        float[] initialValues = new float[] {80.4f, 12.3f, -67f};
+        verifyStatsWithTwoWindows(initialValues, initialValues, true);
+
+        // Only modify the first element in the array but close enough
+        float[] laterValues = new float[] {78.1f, 12.3f, -67f};
+        verifyStatsWithTwoWindows(initialValues, laterValues, true);
+        // Only modify the first element in the array but by more than the MAX_ABSOLUTE_DELTA
+        laterValues = new float[] {70.1f, 12.3f, -67f};
+        verifyStatsWithTwoWindows(initialValues, laterValues, false);
+
+        // Only modify the second element in the array but close enough
+        laterValues = new float[] {80.4f, 11.3f, -67f};
+        verifyStatsWithTwoWindows(initialValues, laterValues, true);
+        // Only modify the second element in the array but by more than the MAX_ABSOLUTE_DELTA
+        laterValues = new float[] {80.4f, 7.3f, -67f};
+        verifyStatsWithTwoWindows(initialValues, laterValues, false);
+
+        // Only modify the third element in the array but close enough
+        laterValues = new float[] {80.4f, 12.3f, -65f};
+        verifyStatsWithTwoWindows(initialValues, laterValues, true);
+        // Only modify the third element in the array but by more than the MAX_ABSOLUTE_DELTA
+        laterValues = new float[] {80.4f, 12.3f, 45f};
+        verifyStatsWithTwoWindows(initialValues, laterValues, false);
+    }
+
+    private static InitialValueVerification getVerification(Collection<TestSensorEvent> events,
+            float maxAbsoluteDelta, long initialWindowLength) {
+        InitialValueVerification verification =
+                new InitialValueVerification(maxAbsoluteDelta, initialWindowLength);
+        verification.addSensorEvents(events);
+        return verification;
+    }
+
+    private static void verifyStatsWithTwoWindows(float[] initialValues, float[] laterValues,
+            boolean pass) {
+        List<TestSensorEvent> events = new ArrayList<>();
+        // Initial window
+        for (long timestamp = 0L; timestamp <= INITIAL_WINDOW_LENGTH; timestamp += SENSOR_PERIOD) {
+            float[] initialValuesWithNoise = addNoise(initialValues);
+            events.add(new TestSensorEvent(null /* sensor */, timestamp, 0 /* accuracy */,
+                    initialValuesWithNoise));
+        }
+        // Later window
+        for (long timestamp = INITIAL_WINDOW_LENGTH
+                + SENSOR_PERIOD; timestamp <= TOTAL_WINDOW_LENGTH; timestamp += SENSOR_PERIOD) {
+            float[] laterValuesWithNoise = addNoise(laterValues);
+            events.add(new TestSensorEvent(null /* sensor */, timestamp, 0 /* accuracy */,
+                    laterValuesWithNoise));
+        }
+        SensorStats stats = new SensorStats();
+        InitialValueVerification verification =
+                getVerification(events, MAX_ABSOLUTE_DELTA, INITIAL_WINDOW_LENGTH);
+
+        try {
+            verification.verify(stats);
+            assertTrue(pass);
+        } catch (AssertionError e) {
+            assertFalse(pass);
+        }
+        verifyStats(stats, pass, initialValues, laterValues);
+    }
+
+    private static float[] addNoise(float[] values) {
+        float[] valuesWithNoise = new float[values.length];
+        for(int i = 0; i < values.length; i++) {
+            valuesWithNoise[i] = values[i] + random.nextFloat() * NOISE_STD;
+        }
+        return valuesWithNoise;
+    }
+
+    private static void verifyStats(SensorStats stats, boolean passed, float[] initialMeans,
+            float[] laterMeans) {
+        assertEquals(passed, stats.getValue(InitialValueVerification.PASSED_KEY));
+        float[] actualInitialMeans = (float[]) stats.getValue(SensorStats.INITIAL_MEAN_KEY);
+        float[] actualLaterMeans = (float[]) stats.getValue(SensorStats.LATER_MEAN_KEY);
+        assertEquals(initialMeans.length, actualInitialMeans.length);
+        assertEquals(laterMeans.length, actualLaterMeans.length);
+        for (int i = 0; i < initialMeans.length; i++) {
+            assertEquals(initialMeans[i], actualInitialMeans[i], 0.1);
+            assertEquals(laterMeans[i], actualLaterMeans[i], 0.1);
+        }
+    }
+}
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
index d8e1586..4ac4999 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
@@ -62,7 +62,7 @@
         verification = getVerification(1, timestamps);
         try {
             verification.verify(environment, stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java
index ac873c1..dfd951d 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java
@@ -57,7 +57,7 @@
         } else {
             try {
                 verification.verify(stats);
-                fail("Expected an AssertionError");
+                throw new Error("Expected an AssertionError");
             } catch (AssertionError e) {
                 // Expected;
             }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java
index 6603895..17882d7 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java
@@ -20,6 +20,7 @@
 
 import android.hardware.Sensor;
 import android.hardware.SensorManager;
+import android.hardware.cts.helpers.SensorCtsHelper;
 import android.hardware.cts.helpers.SensorStats;
 import android.hardware.cts.helpers.TestSensorEnvironment;
 
@@ -33,24 +34,28 @@
     public static final String PASSED_KEY = "mean_passed";
 
     // sensorType: {expected, threshold}
-    private static final Map<Integer, Object[]> DEFAULTS = new HashMap<Integer, Object[]>(5);
+    private static final Map<Integer, ExpectedValuesAndThresholds> DEFAULTS
+        = new HashMap<Integer, ExpectedValuesAndThresholds>(5);
     static {
         // Use a method so that the @deprecation warning can be set for that method only
         setDefaults();
     }
 
     private final float[] mExpected;
-    private final float[] mThreshold;
+    private final float[] mUpperThresholds;
+    private final float[] mLowerThresholds;
 
     /**
      * Construct a {@link MeanVerification}
      *
      * @param expected the expected values
-     * @param threshold the thresholds
+     * @param upperThresholds the upper thresholds
+     * @param lowerThresholds the lower thresholds
      */
-    public MeanVerification(float[] expected, float[] threshold) {
+    public MeanVerification(float[] expected, float[] upperThresholds, float[] lowerThresholds) {
         mExpected = expected;
-        mThreshold = threshold;
+        mUpperThresholds = upperThresholds;
+        mLowerThresholds = lowerThresholds;
     }
 
     /**
@@ -64,9 +69,10 @@
         if (!DEFAULTS.containsKey(sensorType)) {
             return null;
         }
-        float[] expected = (float[]) DEFAULTS.get(sensorType)[0];
-        float[] threshold = (float[]) DEFAULTS.get(sensorType)[1];
-        return new MeanVerification(expected, threshold);
+        float[] expected = DEFAULTS.get(sensorType).mExpectedValues;
+        float[] upperThresholds = DEFAULTS.get(sensorType).mUpperThresholds;
+        float[] lowerThresholds = DEFAULTS.get(sensorType).mLowerThresholds;
+        return new MeanVerification(expected, upperThresholds, lowerThresholds);
     }
 
     /**
@@ -92,66 +98,104 @@
         float[] means = getMeans();
 
         boolean failed = false;
-        StringBuilder meanSb = new StringBuilder();
-        StringBuilder expectedSb = new StringBuilder();
-
-        if (means.length > 1) {
-            meanSb.append("(");
-            expectedSb.append("(");
-        }
         for (int i = 0; i < means.length; i++) {
-            if (Math.abs(means[i] - mExpected[i]) > mThreshold[i]) {
+            if (means[i]  > mExpected[i] + mUpperThresholds[i]) {
                 failed = true;
             }
-            meanSb.append(String.format("%.2f", means[i]));
-            if (i != means.length - 1) meanSb.append(", ");
-            expectedSb.append(String.format("%.2f+/-%.2f", mExpected[i], mThreshold[i]));
-            if (i != means.length - 1) expectedSb.append(", ");
-        }
-        if (means.length > 1) {
-            meanSb.append(")");
-            expectedSb.append(")");
+            if (means[i] < mExpected[i] - mLowerThresholds[i]) {
+                failed = true;
+            }
         }
 
         stats.addValue(PASSED_KEY, !failed);
         stats.addValue(SensorStats.MEAN_KEY, means);
 
         if (failed) {
-            Assert.fail(String.format("Mean out of range: mean=%s (expected %s)", meanSb.toString(),
-                    expectedSb.toString()));
+            Assert.fail(String.format("Mean out of range: mean=%s (expected %s)",
+                    SensorCtsHelper.formatFloatArray(means),
+                    SensorCtsHelper.formatFloatArray(mExpected)));
         }
     }
 
     @Override
     public MeanVerification clone() {
-        return new MeanVerification(mExpected, mThreshold);
+        return new MeanVerification(mExpected, mUpperThresholds, mLowerThresholds);
     }
 
     @SuppressWarnings("deprecation")
     private static void setDefaults() {
         // Sensors that we don't want to test at this time but still want to record the values.
         // Gyroscope should be 0 for a static device
-        DEFAULTS.put(Sensor.TYPE_GYROSCOPE, new Object[]{
-                new float[]{0.0f, 0.0f, 0.0f},
-                new float[]{Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE}});
+        DEFAULTS.put(Sensor.TYPE_GYROSCOPE,
+            new ExpectedValuesAndThresholds(new float[]{0.0f, 0.0f, 0.0f},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE}));
         // Pressure will not be exact in a controlled environment but should be relatively close to
-        // sea level. Second values should always be 0.
-        DEFAULTS.put(Sensor.TYPE_PRESSURE, new Object[]{
-                new float[]{SensorManager.PRESSURE_STANDARD_ATMOSPHERE, 0.0f, 0.0f},
-                new float[]{Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE}});
+        // sea level (400HPa and 200HPa are very lax thresholds).
+        // Second values should always be 0.
+        DEFAULTS.put(Sensor.TYPE_PRESSURE,
+            new ExpectedValuesAndThresholds(new float[]{SensorManager.PRESSURE_STANDARD_ATMOSPHERE,
+                                                        0.0f,
+                                                        0.0f},
+                                            new float[]{100f,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE},
+                                            new float[]{400f,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE}));
         // Linear acceleration should be 0 in all directions for a static device
-        DEFAULTS.put(Sensor.TYPE_LINEAR_ACCELERATION, new Object[]{
-                new float[]{0.0f, 0.0f, 0.0f},
-                new float[]{Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE}});
+        DEFAULTS.put(Sensor.TYPE_LINEAR_ACCELERATION,
+            new ExpectedValuesAndThresholds(new float[]{0.0f, 0.0f, 0.0f},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE}));
         // Game rotation vector should be (0, 0, 0, 1, 0) for a static device
-        DEFAULTS.put(Sensor.TYPE_GAME_ROTATION_VECTOR, new Object[]{
-                new float[]{0.0f, 0.0f, 0.0f, 1.0f, 0.0f},
-                new float[]{Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE,
-                        Float.MAX_VALUE}});
+        DEFAULTS.put(Sensor.TYPE_GAME_ROTATION_VECTOR,
+            new ExpectedValuesAndThresholds(new float[]{0.0f, 0.0f, 0.0f, 1.0f, 0.0f},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE}));
         // Uncalibrated gyroscope should be 0 for a static device but allow a bigger threshold
-        DEFAULTS.put(Sensor.TYPE_GYROSCOPE_UNCALIBRATED, new Object[]{
-                new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f},
-                new float[]{Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE,
-                        Float.MAX_VALUE, Float.MAX_VALUE}});
+        DEFAULTS.put(Sensor.TYPE_GYROSCOPE_UNCALIBRATED,
+            new ExpectedValuesAndThresholds(new float[]{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE},
+                                            new float[]{Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE,
+                                                        Float.MAX_VALUE}));
+    }
+
+    private static final class ExpectedValuesAndThresholds {
+        private float[] mExpectedValues;
+        private float[] mUpperThresholds;
+        private float[] mLowerThresholds;
+        private ExpectedValuesAndThresholds(float[] expectedValues,
+                                            float[] upperThresholds,
+                                            float[] lowerThresholds) {
+            mExpectedValues = expectedValues;
+            mUpperThresholds = upperThresholds;
+            mLowerThresholds = lowerThresholds;
+        }
     }
 }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java
index d7fcf9f..6661e78 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java
@@ -29,6 +29,7 @@
  * Tests for {@link MeanVerification}.
  */
 public class MeanVerificationTest extends TestCase {
+    private static final float[] MEANS = {2.0f, 3.0f, 6.0f};
 
     /**
      * Test {@link MeanVerification#verify(TestSensorEnvironment, SensorStats)}.
@@ -43,62 +44,106 @@
         };
 
         float[] expected = {2.0f, 3.0f, 6.0f};
-        float[] threshold = {0.1f, 0.1f, 0.1f};
+        float[] upperThresholds = {0.3f, 0.3f, 0.3f};
+        float[] lowerThresholds = {0.1f, 0.1f, 0.1f};
         SensorStats stats = new SensorStats();
-        MeanVerification verification = getVerification(expected, threshold, values);
+        MeanVerification verification =
+            getVerification(expected, upperThresholds, lowerThresholds, values);
         verification.verify(stats);
-        verifyStats(stats, true, new float[]{2.0f, 3.0f, 6.0f});
+        verifyStats(stats, true, MEANS);
 
-        expected = new float[]{2.5f, 2.5f, 5.5f};
-        threshold = new float[]{0.6f, 0.6f, 0.6f};
+        // Test the lower threshold
+        expected = new float[]{2.4f, 3.3f, 6.4f};
+        lowerThresholds = new float[]{0.6f, 0.6f, 0.6f};
         stats = new SensorStats();
-        verification = getVerification(expected, threshold, values);
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
         verification.verify(stats);
-        verifyStats(stats, true, new float[]{2.0f, 3.0f, 6.0f});
+        verifyStats(stats, true, MEANS);
 
-        expected = new float[]{2.5f, 2.5f, 5.5f};
-        threshold = new float[]{0.1f, 0.6f, 0.6f};
+        lowerThresholds = new float[]{0.1f, 0.6f, 0.6f};
         stats = new SensorStats();
-        verification = getVerification(expected, threshold, values);
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
         try {
             verification.verify(stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
-        verifyStats(stats, false, new float[]{2.0f, 3.0f, 6.0f});
+        verifyStats(stats, false, MEANS);
 
-        expected = new float[]{2.5f, 2.5f, 5.5f};
-        threshold = new float[]{0.6f, 0.1f, 0.6f};
+        lowerThresholds = new float[]{0.6f, 0.1f, 0.6f};
         stats = new SensorStats();
-        verification = getVerification(expected, threshold, values);
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
         try {
             verification.verify(stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
-        verifyStats(stats, false, new float[]{2.0f, 3.0f, 6.0f});
+        verifyStats(stats, false, MEANS);
 
-        threshold = new float[]{0.6f, 0.6f, 0.1f};
+        lowerThresholds = new float[]{0.6f, 0.6f, 0.1f};
         stats = new SensorStats();
-        verification = getVerification(expected, threshold, values);
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
         try {
             verification.verify(stats);
-            fail("Expected an AssertionError");
+            throw new Error("Expected an AssertionError");
         } catch (AssertionError e) {
             // Expected;
         }
-        verifyStats(stats, false, new float[]{2.0f, 3.0f, 6.0f});
+        verifyStats(stats, false, MEANS);
+
+        // Test the upper threshold
+        expected = new float[]{1.5f, 2.8f, 5.7f};
+        upperThresholds = new float[]{0.6f, 0.6f, 0.6f};
+        lowerThresholds = new float[]{0.1f, 0.1f, 0.1f};
+        stats = new SensorStats();
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
+        verification.verify(stats);
+        verifyStats(stats, true, MEANS);
+
+        upperThresholds = new float[]{0.1f, 0.6f, 0.6f};
+        stats = new SensorStats();
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
+        try {
+            verification.verify(stats);
+            throw new Error("Expected an AssertionError");
+        } catch (AssertionError e) {
+            // Expected;
+        }
+        verifyStats(stats, false, MEANS);
+
+        upperThresholds = new float[]{0.6f, 0.1f, 0.6f};
+        stats = new SensorStats();
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
+        try {
+            verification.verify(stats);
+            throw new Error("Expected an AssertionError");
+        } catch (AssertionError e) {
+            // Expected;
+        }
+        verifyStats(stats, false, MEANS);
+
+        upperThresholds = new float[]{0.6f, 0.6f, 0.1f};
+        stats = new SensorStats();
+        verification = getVerification(expected, upperThresholds, lowerThresholds, values);
+        try {
+            verification.verify(stats);
+            throw new Error("Expected an AssertionError");
+        } catch (AssertionError e) {
+            // Expected;
+        }
+        verifyStats(stats, false, MEANS);
     }
 
-    private static MeanVerification getVerification(float[] expected, float[] threshold,
-            float[] ... values) {
+    private static MeanVerification getVerification(float[] expected, float[] upperThresholds,
+            float[] lowerThresholds, float[] ... values) {
         Collection<TestSensorEvent> events = new ArrayList<>(values.length);
         for (float[] value : values) {
             events.add(new TestSensorEvent(null, 0, 0, value));
         }
-        MeanVerification verification = new MeanVerification(expected, threshold);
+        MeanVerification verification =
+            new MeanVerification(expected, upperThresholds, lowerThresholds);
         verification.addSensorEvents(events);
         return verification;
     }
@@ -106,6 +151,7 @@
     private void verifyStats(SensorStats stats, boolean passed, float[] means) {
         assertEquals(passed, stats.getValue(MeanVerification.PASSED_KEY));
         float[] actual = (float[]) stats.getValue(SensorStats.MEAN_KEY);
+        assertEquals(means.length, actual.length);
         for (int i = 0; i < means.length; i++) {
             assertEquals(means[i], actual[i], 0.1);
         }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/TimestampClockSourceVerificationTest.java b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/TimestampClockSourceVerificationTest.java
index b8412a6..a65323d 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensorverification/TimestampClockSourceVerificationTest.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensorverification/TimestampClockSourceVerificationTest.java
@@ -191,7 +191,7 @@
             for (int i = 0; i < indices.length; i++) {
                 assertEquals(indices[i], actualIndices[i]);
             }
-        } catch (Throwable t) {
+        } catch (Exception t) {
         }
     }
 
diff --git a/tests/simplecpu/jni/Android.mk b/tests/simplecpu/jni/Android.mk
index 877f1b6..c5f072e 100644
--- a/tests/simplecpu/jni/Android.mk
+++ b/tests/simplecpu/jni/Android.mk
@@ -26,4 +26,6 @@
 
 LOCAL_SDK_VERSION := 14
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/accounts/Android.mk b/tests/tests/accounts/Android.mk
index 3f6ad38..9ee9ba1 100644
--- a/tests/tests/accounts/Android.mk
+++ b/tests/tests/accounts/Android.mk
@@ -24,6 +24,8 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
     CtsAccountTestsCommon ctstestrunner
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
diff --git a/tests/tests/bionic/Android.build.copy.libs.mk b/tests/tests/bionic/Android.build.copy.libs.mk
index efd7e93..5016e33 100644
--- a/tests/tests/bionic/Android.build.copy.libs.mk
+++ b/tests/tests/bionic/Android.build.copy.libs.mk
@@ -112,11 +112,20 @@
   private_namespace_libs/libnstest_root.so \
   public_namespace_libs/libnstest_public.so \
   public_namespace_libs/libnstest_public_internal.so \
+  ld_preload_test_helper/ld_preload_test_helper \
+  ld_preload_test_helper_lib1.so \
+  ld_preload_test_helper_lib2.so \
+  ld_config_test_helper/ld_config_test_helper \
+  ns2/ld_config_test_helper_lib1.so \
+  ns2/ld_config_test_helper_lib2.so \
+  ld_config_test_helper_lib3.so \
 
 # These libraries are not built for mips.
 my_bionic_testlib_files_non_mips := \
   libgnu-hash-table-library.so \
   libtest_ifunc.so \
+  libtest_ifunc_variable.so \
+  libtest_ifunc_variable_impl.so \
 
 my_bionic_testlibs_src_dir := \
   $($(cts_bionic_tests_2nd_arch_prefix)TARGET_OUT_DATA_NATIVE_TESTS)/bionic-loader-test-libs
diff --git a/tests/tests/bionic/Android.mk b/tests/tests/bionic/Android.mk
index 6c4009c..ade0162 100644
--- a/tests/tests/bionic/Android.mk
+++ b/tests/tests/bionic/Android.mk
@@ -45,9 +45,11 @@
 
 cts_bionic_tests_2nd_arch_prefix :=
 include $(LOCAL_PATH)/Android.build.copy.libs.mk
-ifneq ($(TARGET_2ND_ARCH),)
-  cts_bionic_tests_2nd_arch_prefix := $(TARGET_2ND_ARCH_VAR_PREFIX)
-  include $(LOCAL_PATH)/Android.build.copy.libs.mk
+ifneq ($(TARGET_TRANSLATE_2ND_ARCH),true)
+  ifneq ($(TARGET_2ND_ARCH),)
+    cts_bionic_tests_2nd_arch_prefix := $(TARGET_2ND_ARCH_VAR_PREFIX)
+    include $(LOCAL_PATH)/Android.build.copy.libs.mk
+  endif
 endif
 
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/tests/tests/calendarcommon/Android.mk b/tests/tests/calendarcommon/Android.mk
index 7a8296c..3011ded 100644
--- a/tests/tests/calendarcommon/Android.mk
+++ b/tests/tests/calendarcommon/Android.mk
@@ -27,6 +27,8 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_SDK_VERSION := current
diff --git a/tests/tests/contactsproviderwipe/Android.mk b/tests/tests/contactsproviderwipe/Android.mk
index b7bd687..42ca2b6 100644
--- a/tests/tests/contactsproviderwipe/Android.mk
+++ b/tests/tests/contactsproviderwipe/Android.mk
@@ -30,8 +30,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_SRC_FILES := $(call all-java-files-under, src) \
-    $(call all-java-files-under, common/src)
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_PACKAGE_NAME := CtsContactsProviderWipe
 
diff --git a/tests/tests/content/src/android/content/cts/IntentTest.java b/tests/tests/content/src/android/content/cts/IntentTest.java
index dbbbe15..af53e56 100644
--- a/tests/tests/content/src/android/content/cts/IntentTest.java
+++ b/tests/tests/content/src/android/content/cts/IntentTest.java
@@ -1148,6 +1148,11 @@
                         .putExtra("int", 1000).putExtra("long", (long) 1000)
                         .putExtra("boolean", true).putExtra("float", 10.4f)
                         .setPackage("com.myapp"));
+        checkIntentUri(
+                "intent://example.org/db?123#Intent;scheme=z39.50r;end",
+                null,
+                new Intent().setAction(Intent.ACTION_VIEW)
+                        .setData(Uri.parse("z39.50r://example.org/db?123")));
     }
 
     private boolean compareIntents(Intent expected, Intent actual) {
diff --git a/tests/tests/dpi2/Android.mk b/tests/tests/dpi2/Android.mk
index 6e7c649..d6dd8fe 100644
--- a/tests/tests/dpi2/Android.mk
+++ b/tests/tests/dpi2/Android.mk
@@ -20,6 +20,8 @@
 # We use the DefaultManifestAttributesTest from the android.cts.dpi package.
 LOCAL_STATIC_JAVA_LIBRARIES := android.cts.dpi ctstestrunner junit
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_PACKAGE_NAME := CtsDpiTestCases2
diff --git a/tests/tests/drm/jni/Android.mk b/tests/tests/drm/jni/Android.mk
index 87f00a4..fe9a041 100644
--- a/tests/tests/drm/jni/Android.mk
+++ b/tests/tests/drm/jni/Android.mk
@@ -30,4 +30,6 @@
 LOCAL_SHARED_LIBRARIES := liblog libdl
 LOCAL_SDK_VERSION := 23
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/graphics/assets/unsorted_cmap12.ttf b/tests/tests/graphics/assets/unsorted_cmap12.ttf
deleted file mode 100644
index d9587df..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap12.ttf
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap12.ttx b/tests/tests/graphics/assets/unsorted_cmap12.ttx
deleted file mode 100644
index 6444903..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap12.ttx
+++ /dev/null
@@ -1,199 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
-
-  <GlyphOrder>
-    <GlyphID id="0" name=".notdef"/>
-    <GlyphID id="1" name="3em"/>
-  </GlyphOrder>
-
-  <head>
-    <tableVersion value="1.0"/>
-    <fontRevision value="1.0"/>
-    <checkSumAdjustment value="0x640cdb2f"/>
-    <magicNumber value="0x5f0f3cf5"/>
-    <flags value="00000000 00000011"/>
-    <unitsPerEm value="1000"/>
-    <created value="Fri Mar 17 07:26:00 2017"/>
-    <macStyle value="00000000 00000000"/>
-    <lowestRecPPEM value="7"/>
-    <fontDirectionHint value="2"/>
-    <glyphDataFormat value="0"/>
-  </head>
-
-  <hhea>
-    <tableVersion value="0x00010000"/>
-    <ascent value="1000"/>
-    <descent value="-200"/>
-    <lineGap value="0"/>
-    <caretSlopeRise value="1"/>
-    <caretSlopeRun value="0"/>
-    <caretOffset value="0"/>
-    <reserved0 value="0"/>
-    <reserved1 value="0"/>
-    <reserved2 value="0"/>
-    <reserved3 value="0"/>
-    <metricDataFormat value="0"/>
-  </hhea>
-
-  <maxp>
-    <tableVersion value="0x10000"/>
-    <maxZones value="0"/>
-    <maxTwilightPoints value="0"/>
-    <maxStorage value="0"/>
-    <maxFunctionDefs value="0"/>
-    <maxInstructionDefs value="0"/>
-    <maxStackElements value="0"/>
-    <maxSizeOfInstructions value="0"/>
-    <maxComponentElements value="0"/>
-  </maxp>
-
-  <OS_2>
-    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
-         will be recalculated by the compiler -->
-    <version value="3"/>
-    <xAvgCharWidth value="594"/>
-    <usWeightClass value="400"/>
-    <usWidthClass value="5"/>
-    <fsType value="00000000 00001000"/>
-    <ySubscriptXSize value="650"/>
-    <ySubscriptYSize value="600"/>
-    <ySubscriptXOffset value="0"/>
-    <ySubscriptYOffset value="75"/>
-    <ySuperscriptXSize value="650"/>
-    <ySuperscriptYSize value="600"/>
-    <ySuperscriptXOffset value="0"/>
-    <ySuperscriptYOffset value="350"/>
-    <yStrikeoutSize value="50"/>
-    <yStrikeoutPosition value="300"/>
-    <sFamilyClass value="0"/>
-    <panose>
-      <bFamilyType value="0"/>
-      <bSerifStyle value="0"/>
-      <bWeight value="5"/>
-      <bProportion value="0"/>
-      <bContrast value="0"/>
-      <bStrokeVariation value="0"/>
-      <bArmStyle value="0"/>
-      <bLetterForm value="0"/>
-      <bMidline value="0"/>
-      <bXHeight value="0"/>
-    </panose>
-    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
-    <achVendID value="UKWN"/>
-    <fsSelection value="00000000 01000000"/>
-    <usFirstCharIndex value="32"/>
-    <usLastCharIndex value="122"/>
-    <sTypoAscender value="800"/>
-    <sTypoDescender value="-200"/>
-    <sTypoLineGap value="200"/>
-    <usWinAscent value="1000"/>
-    <usWinDescent value="200"/>
-    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
-    <sxHeight value="500"/>
-    <sCapHeight value="700"/>
-    <usDefaultChar value="0"/>
-    <usBreakChar value="32"/>
-    <usMaxContext value="0"/>
-  </OS_2>
-
-  <hmtx>
-    <mtx name=".notdef" width="500" lsb="93"/>
-    <mtx name="3em" width="3000" lsb="93"/>
-  </hmtx>
-
-  <cmap>
-    <tableVersion version="0"/>
-    <cmap_format_12 format="12" reserved="0" length="0" nGroups="0" platformID="3" platEncID="10" language="0">
-      <!-- Note that following hexcode is pseudo ttx source.
-           You may want to see hexdump of the unsorted_cmap12.ttf -->
-      <hexdata>
-        00 0c  <!-- format: 12 -->
-        00 00  <!-- reserved -->
-        00 00 00 28  <!-- length: 40 bytes -->
-        00 00 00 00  <!-- langauge -->
-        00 00 00 02  <!-- num of groups -->
-
-        <!-- Bad font: cmap entries must be sorted in ascending order. -->
-        <!-- start of the first group -->
-        00 00 04 00  <!-- start code point -->
-        00 00 04 00  <!-- end code point -->
-        00 00 00 01  <!-- start glyph ID -->
-
-        <!-- start of the second group -->
-        00 00 01 00  <!-- start code point -->
-        00 00 01 00  <!-- end code point -->
-        00 00 00 01  <!-- start glyph ID -->
-      </hexdata>
-    </cmap_format_12>
-  </cmap>
-
-  <loca>
-    <!-- The 'loca' table will be calculated by the compiler -->
-  </loca>
-
-  <glyf>
-    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
-    <TTGlyph name="3em" xMin="0" yMin="0" xMax="0" yMax="0" />
-  </glyf>
-
-  <name>
-    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
-      Copyright (C) 2017 The Android Open Source Project
-    </namerecord>
-    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format12 Font
-    </namerecord>
-    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
-      Regular
-    </namerecord>
-    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format12 Font
-    </namerecord>
-    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
-      BrokenCmapFormat12Font-Regular
-    </namerecord>
-    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
-      Licensed under the Apache License, Version 2.0 (the "License");
-      you may not use this file except in compliance with the License.
-      Unless required by applicable law or agreed to in writing, software
-      distributed under the License is distributed on an "AS IS" BASIS
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-      See the License for the specific language governing permissions and
-      limitations under the License.
-    </namerecord>
-    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
-      http://www.apache.org/licenses/LICENSE-2.0
-    </namerecord>
-  </name>
-
-  <post>
-    <formatType value="3.0"/>
-    <italicAngle value="0.0"/>
-    <underlinePosition value="-75"/>
-    <underlineThickness value="50"/>
-    <isFixedPitch value="0"/>
-    <minMemType42 value="0"/>
-    <maxMemType42 value="0"/>
-    <minMemType1 value="0"/>
-    <maxMemType1 value="0"/>
-  </post>
-
-</ttFont>
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttf b/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttf
deleted file mode 100644
index 83801fc..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttf
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttx b/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttx
deleted file mode 100644
index 310a487..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttx
+++ /dev/null
@@ -1,197 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
-
-  <GlyphOrder>
-    <GlyphID id="0" name=".notdef"/>
-  </GlyphOrder>
-
-  <head>
-    <tableVersion value="1.0"/>
-    <fontRevision value="1.0"/>
-    <checkSumAdjustment value="0x640cdb2f"/>
-    <magicNumber value="0x5f0f3cf5"/>
-    <flags value="00000000 00000011"/>
-    <unitsPerEm value="1000"/>
-    <created value="Fri Mar 17 07:26:00 2017"/>
-    <macStyle value="00000000 00000000"/>
-    <lowestRecPPEM value="7"/>
-    <fontDirectionHint value="2"/>
-    <glyphDataFormat value="0"/>
-  </head>
-
-  <hhea>
-    <tableVersion value="0x00010000"/>
-    <ascent value="1000"/>
-    <descent value="-200"/>
-    <lineGap value="0"/>
-    <caretSlopeRise value="1"/>
-    <caretSlopeRun value="0"/>
-    <caretOffset value="0"/>
-    <reserved0 value="0"/>
-    <reserved1 value="0"/>
-    <reserved2 value="0"/>
-    <reserved3 value="0"/>
-    <metricDataFormat value="0"/>
-  </hhea>
-
-  <maxp>
-    <tableVersion value="0x10000"/>
-    <maxZones value="0"/>
-    <maxTwilightPoints value="0"/>
-    <maxStorage value="0"/>
-    <maxFunctionDefs value="0"/>
-    <maxInstructionDefs value="0"/>
-    <maxStackElements value="0"/>
-    <maxSizeOfInstructions value="0"/>
-    <maxComponentElements value="0"/>
-  </maxp>
-
-  <OS_2>
-    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
-         will be recalculated by the compiler -->
-    <version value="3"/>
-    <xAvgCharWidth value="594"/>
-    <usWeightClass value="400"/>
-    <usWidthClass value="5"/>
-    <fsType value="00000000 00001000"/>
-    <ySubscriptXSize value="650"/>
-    <ySubscriptYSize value="600"/>
-    <ySubscriptXOffset value="0"/>
-    <ySubscriptYOffset value="75"/>
-    <ySuperscriptXSize value="650"/>
-    <ySuperscriptYSize value="600"/>
-    <ySuperscriptXOffset value="0"/>
-    <ySuperscriptYOffset value="350"/>
-    <yStrikeoutSize value="50"/>
-    <yStrikeoutPosition value="300"/>
-    <sFamilyClass value="0"/>
-    <panose>
-      <bFamilyType value="0"/>
-      <bSerifStyle value="0"/>
-      <bWeight value="5"/>
-      <bProportion value="0"/>
-      <bContrast value="0"/>
-      <bStrokeVariation value="0"/>
-      <bArmStyle value="0"/>
-      <bLetterForm value="0"/>
-      <bMidline value="0"/>
-      <bXHeight value="0"/>
-    </panose>
-    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
-    <achVendID value="UKWN"/>
-    <fsSelection value="00000000 01000000"/>
-    <usFirstCharIndex value="32"/>
-    <usLastCharIndex value="122"/>
-    <sTypoAscender value="800"/>
-    <sTypoDescender value="-200"/>
-    <sTypoLineGap value="200"/>
-    <usWinAscent value="1000"/>
-    <usWinDescent value="200"/>
-    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
-    <sxHeight value="500"/>
-    <sCapHeight value="700"/>
-    <usDefaultChar value="0"/>
-    <usBreakChar value="32"/>
-    <usMaxContext value="0"/>
-  </OS_2>
-
-  <hmtx>
-    <mtx name=".notdef" width="500" lsb="93"/>
-  </hmtx>
-
-  <cmap>
-    <tableVersion version="0"/>
-    <cmap_format_14 format="14" platformID="0" platEncID="5" length="0" numVarSelectorRecords="1">
-      <!-- Note that following hexcode is pseudo ttx source.
-           You may want to see hexdump of the unsorted_cmap14_default_uvs.ttf -->
-      <hexdata>
-        00 0e  <!-- format: 14 -->
-        00 00 00 21  <!-- length: 33 bytes -->
-        00 00 00 01  <!-- number of variation selectors -->
-
-        <!-- 1st variation selector record -->
-        00 fe 00  <!-- variation selector -->
-        00 00 00 15  <!-- the offset to the default UVS table -->
-        00 00 00 00  <!-- the offset to the non default UVS table (no table) -->
-
-        <!-- start of default UVS table -->
-        00 00 00 02  <!-- number of range record -->
-
-        <!-- Bad font: cmap entries must be sorted in ascending order. -->
-        00 04 00  <!-- Unicode code point. -->
-        00  <!-- number of additional following code points -->
-        00 01 00  <!-- Unicode code point. -->
-        00  <!-- number of additional following code points -->
-      </hexdata>
-    </cmap_format_14>
-  </cmap>
-
-  <loca>
-    <!-- The 'loca' table will be calculated by the compiler -->
-  </loca>
-
-  <glyf>
-    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
-  </glyf>
-
-  <name>
-    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
-      Copyright (C) 2017 The Android Open Source Project
-    </namerecord>
-    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format14 Default UVS Table Font
-    </namerecord>
-    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
-      Regular
-    </namerecord>
-    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format14 Default UVS Table Font
-    </namerecord>
-    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
-      BrokenCmapFormat14DefaultUVSTableFont-Regular
-    </namerecord>
-    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
-      Licensed under the Apache License, Version 2.0 (the "License");
-      you may not use this file except in compliance with the License.
-      Unless required by applicable law or agreed to in writing, software
-      distributed under the License is distributed on an "AS IS" BASIS
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-      See the License for the specific language governing permissions and
-      limitations under the License.
-    </namerecord>
-    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
-      http://www.apache.org/licenses/LICENSE-2.0
-    </namerecord>
-  </name>
-
-  <post>
-    <formatType value="3.0"/>
-    <italicAngle value="0.0"/>
-    <underlinePosition value="-75"/>
-    <underlineThickness value="50"/>
-    <isFixedPitch value="0"/>
-    <minMemType42 value="0"/>
-    <maxMemType42 value="0"/>
-    <minMemType1 value="0"/>
-    <maxMemType1 value="0"/>
-  </post>
-
-</ttFont>
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttf b/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttf
deleted file mode 100644
index 92aadc2..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttf
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttx b/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttx
deleted file mode 100644
index 0c0cb77..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttx
+++ /dev/null
@@ -1,200 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
-
-  <GlyphOrder>
-    <GlyphID id="0" name=".notdef"/>
-    <GlyphID id="1" name="3em"/>
-  </GlyphOrder>
-
-  <head>
-    <tableVersion value="1.0"/>
-    <fontRevision value="1.0"/>
-    <checkSumAdjustment value="0x640cdb2f"/>
-    <magicNumber value="0x5f0f3cf5"/>
-    <flags value="00000000 00000011"/>
-    <unitsPerEm value="1000"/>
-    <created value="Fri Mar 17 07:26:00 2017"/>
-    <macStyle value="00000000 00000000"/>
-    <lowestRecPPEM value="7"/>
-    <fontDirectionHint value="2"/>
-    <glyphDataFormat value="0"/>
-  </head>
-
-  <hhea>
-    <tableVersion value="0x00010000"/>
-    <ascent value="1000"/>
-    <descent value="-200"/>
-    <lineGap value="0"/>
-    <caretSlopeRise value="1"/>
-    <caretSlopeRun value="0"/>
-    <caretOffset value="0"/>
-    <reserved0 value="0"/>
-    <reserved1 value="0"/>
-    <reserved2 value="0"/>
-    <reserved3 value="0"/>
-    <metricDataFormat value="0"/>
-  </hhea>
-
-  <maxp>
-    <tableVersion value="0x10000"/>
-    <maxZones value="0"/>
-    <maxTwilightPoints value="0"/>
-    <maxStorage value="0"/>
-    <maxFunctionDefs value="0"/>
-    <maxInstructionDefs value="0"/>
-    <maxStackElements value="0"/>
-    <maxSizeOfInstructions value="0"/>
-    <maxComponentElements value="0"/>
-  </maxp>
-
-  <OS_2>
-    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
-         will be recalculated by the compiler -->
-    <version value="3"/>
-    <xAvgCharWidth value="594"/>
-    <usWeightClass value="400"/>
-    <usWidthClass value="5"/>
-    <fsType value="00000000 00001000"/>
-    <ySubscriptXSize value="650"/>
-    <ySubscriptYSize value="600"/>
-    <ySubscriptXOffset value="0"/>
-    <ySubscriptYOffset value="75"/>
-    <ySuperscriptXSize value="650"/>
-    <ySuperscriptYSize value="600"/>
-    <ySuperscriptXOffset value="0"/>
-    <ySuperscriptYOffset value="350"/>
-    <yStrikeoutSize value="50"/>
-    <yStrikeoutPosition value="300"/>
-    <sFamilyClass value="0"/>
-    <panose>
-      <bFamilyType value="0"/>
-      <bSerifStyle value="0"/>
-      <bWeight value="5"/>
-      <bProportion value="0"/>
-      <bContrast value="0"/>
-      <bStrokeVariation value="0"/>
-      <bArmStyle value="0"/>
-      <bLetterForm value="0"/>
-      <bMidline value="0"/>
-      <bXHeight value="0"/>
-    </panose>
-    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
-    <achVendID value="UKWN"/>
-    <fsSelection value="00000000 01000000"/>
-    <usFirstCharIndex value="32"/>
-    <usLastCharIndex value="122"/>
-    <sTypoAscender value="800"/>
-    <sTypoDescender value="-200"/>
-    <sTypoLineGap value="200"/>
-    <usWinAscent value="1000"/>
-    <usWinDescent value="200"/>
-    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
-    <sxHeight value="500"/>
-    <sCapHeight value="700"/>
-    <usDefaultChar value="0"/>
-    <usBreakChar value="32"/>
-    <usMaxContext value="0"/>
-  </OS_2>
-
-  <hmtx>
-    <mtx name=".notdef" width="500" lsb="93"/>
-    <mtx name="3em" width="3000" lsb="93"/>
-  </hmtx>
-
-  <cmap>
-    <tableVersion version="0"/>
-    <cmap_format_14 format="14" platformID="0" platEncID="5" length="0" numVarSelectorRecords="1">
-      <!-- Note that following hexcode is pseudo ttx source.
-           You may want to see hexdump of the unsorted_cmap14_non_default_uvs.ttf -->
-      <hexdata>
-        00 0e <!-- format: 14 -->
-        00 00 00 23  <!-- length: 35 bytes -->
-        00 00 00 01  <!-- number of variation selectors -->
-
-        <!-- 1st variation selector record -->
-        00 fe 00  <!-- variation selector -->
-        00 00 00 00  <!-- the offset to the default UVS table (no table) -->
-        00 00 00 15  <!-- the offset to the non default UVS table -->
-
-        <!-- start of default UVS table -->
-        00 00 00 02  <!-- number of mapping record -->
-
-        <!-- Bad font: cmap entries must be sorted in ascending order. -->
-        00 04 00  <!-- Unicode code point. -->
-        00 01  <!-- glyph ID -->
-        00 01 00  <!-- Unicode code point. -->
-        00 01  <!-- glyph ID -->
-      </hexdata>
-    </cmap_format_14>
-  </cmap>
-
-  <loca>
-    <!-- The 'loca' table will be calculated by the compiler -->
-  </loca>
-
-  <glyf>
-    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
-    <TTGlyph name="3em" xMin="0" yMin="0" xMax="0" yMax="0" />
-  </glyf>
-
-  <name>
-    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
-      Copyright (C) 2017 The Android Open Source Project
-    </namerecord>
-    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format14 Non-Default UVS Table Font
-    </namerecord>
-    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
-      Regular
-    </namerecord>
-    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format14 Non-Default UVS Table Font
-    </namerecord>
-    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
-      BrokenCmapFormat14NonDefaultUVSTableFont-Regular
-    </namerecord>
-    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
-      Licensed under the Apache License, Version 2.0 (the "License");
-      you may not use this file except in compliance with the License.
-      Unless required by applicable law or agreed to in writing, software
-      distributed under the License is distributed on an "AS IS" BASIS
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-      See the License for the specific language governing permissions and
-      limitations under the License.
-    </namerecord>
-    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
-      http://www.apache.org/licenses/LICENSE-2.0
-    </namerecord>
-  </name>
-
-  <post>
-    <formatType value="3.0"/>
-    <italicAngle value="0.0"/>
-    <underlinePosition value="-75"/>
-    <underlineThickness value="50"/>
-    <isFixedPitch value="0"/>
-    <minMemType42 value="0"/>
-    <maxMemType42 value="0"/>
-    <minMemType1 value="0"/>
-    <maxMemType1 value="0"/>
-  </post>
-
-</ttFont>
diff --git a/tests/tests/graphics/assets/unsorted_cmap4.ttf b/tests/tests/graphics/assets/unsorted_cmap4.ttf
deleted file mode 100644
index 8ceeb4e..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap4.ttf
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap4.ttx b/tests/tests/graphics/assets/unsorted_cmap4.ttx
deleted file mode 100644
index 8b16955..0000000
--- a/tests/tests/graphics/assets/unsorted_cmap4.ttx
+++ /dev/null
@@ -1,197 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
-
-  <GlyphOrder>
-    <GlyphID id="0" name=".notdef"/>
-    <GlyphID id="1" name="3em"/>
-  </GlyphOrder>
-
-  <head>
-    <tableVersion value="1.0"/>
-    <fontRevision value="1.0"/>
-    <checkSumAdjustment value="0x640cdb2f"/>
-    <magicNumber value="0x5f0f3cf5"/>
-    <flags value="00000000 00000011"/>
-    <unitsPerEm value="1000"/>
-    <created value="Fri Mar 17 07:26:00 2017"/>
-    <macStyle value="00000000 00000000"/>
-    <lowestRecPPEM value="7"/>
-    <fontDirectionHint value="2"/>
-    <glyphDataFormat value="0"/>
-  </head>
-
-  <hhea>
-    <tableVersion value="0x00010000"/>
-    <ascent value="1000"/>
-    <descent value="-200"/>
-    <lineGap value="0"/>
-    <caretSlopeRise value="1"/>
-    <caretSlopeRun value="0"/>
-    <caretOffset value="0"/>
-    <reserved0 value="0"/>
-    <reserved1 value="0"/>
-    <reserved2 value="0"/>
-    <reserved3 value="0"/>
-    <metricDataFormat value="0"/>
-  </hhea>
-
-  <maxp>
-    <tableVersion value="0x10000"/>
-    <maxZones value="0"/>
-    <maxTwilightPoints value="0"/>
-    <maxStorage value="0"/>
-    <maxFunctionDefs value="0"/>
-    <maxInstructionDefs value="0"/>
-    <maxStackElements value="0"/>
-    <maxSizeOfInstructions value="0"/>
-    <maxComponentElements value="0"/>
-  </maxp>
-
-  <OS_2>
-    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
-         will be recalculated by the compiler -->
-    <version value="3"/>
-    <xAvgCharWidth value="594"/>
-    <usWeightClass value="400"/>
-    <usWidthClass value="5"/>
-    <fsType value="00000000 00001000"/>
-    <ySubscriptXSize value="650"/>
-    <ySubscriptYSize value="600"/>
-    <ySubscriptXOffset value="0"/>
-    <ySubscriptYOffset value="75"/>
-    <ySuperscriptXSize value="650"/>
-    <ySuperscriptYSize value="600"/>
-    <ySuperscriptXOffset value="0"/>
-    <ySuperscriptYOffset value="350"/>
-    <yStrikeoutSize value="50"/>
-    <yStrikeoutPosition value="300"/>
-    <sFamilyClass value="0"/>
-    <panose>
-      <bFamilyType value="0"/>
-      <bSerifStyle value="0"/>
-      <bWeight value="5"/>
-      <bProportion value="0"/>
-      <bContrast value="0"/>
-      <bStrokeVariation value="0"/>
-      <bArmStyle value="0"/>
-      <bLetterForm value="0"/>
-      <bMidline value="0"/>
-      <bXHeight value="0"/>
-    </panose>
-    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
-    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
-    <achVendID value="UKWN"/>
-    <fsSelection value="00000000 01000000"/>
-    <usFirstCharIndex value="32"/>
-    <usLastCharIndex value="122"/>
-    <sTypoAscender value="800"/>
-    <sTypoDescender value="-200"/>
-    <sTypoLineGap value="200"/>
-    <usWinAscent value="1000"/>
-    <usWinDescent value="200"/>
-    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
-    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
-    <sxHeight value="500"/>
-    <sCapHeight value="700"/>
-    <usDefaultChar value="0"/>
-    <usBreakChar value="32"/>
-    <usMaxContext value="0"/>
-  </OS_2>
-
-  <hmtx>
-    <mtx name=".notdef" width="500" lsb="93"/>
-    <mtx name="3em" width="3000" lsb="93"/>
-  </hmtx>
-
-  <cmap>
-    <tableVersion version="0"/>
-    <cmap_format_4 platformID="3" platEncID="10" language="0">
-      <!-- Note that following hexcode is pseudo ttx source.
-           You may want to see hexdump of the unsorted_cmap4.ttf -->
-      <hexdata>
-        00 04  <!-- format: 4 -->
-        00 28  <!-- length: 40 bytes -->
-        00 00  <!-- language -->
-        00 06  <!-- segment count -->
-        00 04  <!-- search range -->
-        00 01  <!-- entry selector -->
-        00 02  <!-- range shift -->
-
-        <!-- Bad font: cmap entries must be sorted in ascending order. -->
-        04 00 01 00 ff ff  <!-- end code points -->
-        00 00  <!-- reserved -->
-        04 00 01 00 ff ff  <!-- start code points -->
-        ff 01 fc 01 00 01  <!-- delta to glyph ID -->
-        00 00 00 00 00 00  <!-- glyph ID range offset -->
-      </hexdata>
-    </cmap_format_4>
-  </cmap>
-
-  <loca>
-    <!-- The 'loca' table will be calculated by the compiler -->
-  </loca>
-
-  <glyf>
-    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
-    <TTGlyph name="3em" xMin="0" yMin="0" xMax="0" yMax="0" />
-  </glyf>
-
-  <name>
-    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
-      Copyright (C) 2017 The Android Open Source Project
-    </namerecord>
-    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format4 Font
-    </namerecord>
-    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
-      Regular
-    </namerecord>
-    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
-      Broken Cmap Format4 Font
-    </namerecord>
-    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
-      BrokenCmapFormat4Font-Regular
-    </namerecord>
-    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
-      Licensed under the Apache License, Version 2.0 (the "License");
-      you may not use this file except in compliance with the License.
-      Unless required by applicable law or agreed to in writing, software
-      distributed under the License is distributed on an "AS IS" BASIS
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-      See the License for the specific language governing permissions and
-      limitations under the License.
-    </namerecord>
-    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
-      http://www.apache.org/licenses/LICENSE-2.0
-    </namerecord>
-  </name>
-
-  <post>
-    <formatType value="3.0"/>
-    <italicAngle value="0.0"/>
-    <underlinePosition value="-75"/>
-    <underlineThickness value="50"/>
-    <isFixedPitch value="0"/>
-    <minMemType42 value="0"/>
-    <maxMemType42 value="0"/>
-    <minMemType1 value="0"/>
-    <maxMemType1 value="0"/>
-  </post>
-
-</ttFont>
diff --git a/tests/tests/graphics/src/android/graphics/cts/ColorTest.java b/tests/tests/graphics/src/android/graphics/cts/ColorTest.java
index a00c45e..4801a1a 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ColorTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ColorTest.java
@@ -15,111 +15,18 @@
  */
 package android.graphics.cts;
 
-import static android.support.test.InstrumentationRegistry.getInstrumentation;
-
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
 
-import android.content.res.Resources;
 import android.graphics.Color;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
-import android.util.TypedValue;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.util.Arrays;
-import java.util.List;
-
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class ColorTest {
-
-    @Test
-    public void resourceColor() {
-        int colors [][] = {
-                { 0xff000000, android.R.color.background_dark  },
-                { 0xffffffff, android.R.color.background_light },
-                { 0xff000000, android.R.color.black },
-                { 0xffaaaaaa, android.R.color.darker_gray },
-                { 0xff00ddff, android.R.color.holo_blue_bright },
-                { 0xff0099cc, android.R.color.holo_blue_dark },
-                { 0xff33b5e5, android.R.color.holo_blue_light },
-                { 0xff669900, android.R.color.holo_green_dark },
-                { 0xff99cc00, android.R.color.holo_green_light },
-                { 0xffff8800, android.R.color.holo_orange_dark },
-                { 0xffffbb33, android.R.color.holo_orange_light },
-                { 0xffaa66cc, android.R.color.holo_purple },
-                { 0xffcc0000, android.R.color.holo_red_dark },
-                { 0xffff4444, android.R.color.holo_red_light },
-                { 0xffffffff, android.R.color.primary_text_dark },
-                { 0xffffffff, android.R.color.primary_text_dark_nodisable },
-                { 0xff000000, android.R.color.primary_text_light },
-                { 0xff000000, android.R.color.primary_text_light_nodisable },
-                { 0xffbebebe, android.R.color.secondary_text_dark },
-                { 0xffbebebe, android.R.color.secondary_text_dark_nodisable },
-                { 0xff323232, android.R.color.secondary_text_light },
-                { 0xffbebebe, android.R.color.secondary_text_light_nodisable },
-                { 0xff808080, android.R.color.tab_indicator_text },
-                { 0xff808080, android.R.color.tertiary_text_dark },
-                { 0xff808080, android.R.color.tertiary_text_light },
-                { 0x00000000, android.R.color.transparent },
-                { 0xffffffff, android.R.color.white },
-                { 0xff000000, android.R.color.widget_edittext_dark },
-        };
-
-        List<Integer> expectedColorStateLists = Arrays.asList(
-                android.R.color.primary_text_dark,
-                android.R.color.primary_text_dark_nodisable,
-                android.R.color.primary_text_light,
-                android.R.color.primary_text_light_nodisable,
-                android.R.color.secondary_text_dark,
-                android.R.color.secondary_text_dark_nodisable,
-                android.R.color.secondary_text_light,
-                android.R.color.secondary_text_light_nodisable,
-                android.R.color.tab_indicator_text,
-                android.R.color.tertiary_text_dark,
-                android.R.color.tertiary_text_light,
-                android.R.color.widget_edittext_dark
-        );
-
-        Resources resources = getInstrumentation().getTargetContext().getResources();
-        for (int[] pair : colors) {
-            final int resourceId = pair[1];
-            final int expectedColor = pair[0];
-
-            // validate color from getColor
-            int observedColor = resources.getColor(resourceId, null);
-            assertEquals("Color = " + Integer.toHexString(observedColor) + ", "
-                            + Integer.toHexString(expectedColor) + " expected",
-                    expectedColor,
-                    observedColor);
-
-            // validate color from getValue
-            TypedValue value = new TypedValue();
-            resources.getValue(resourceId, value, true);
-
-            // colors shouldn't depend on config changes
-            assertEquals(0, value.changingConfigurations);
-
-            if (expectedColorStateLists.contains(resourceId)) {
-                // ColorStateLists are strings
-                assertEquals("CSLs should be strings", TypedValue.TYPE_STRING, value.type);
-            } else {
-                // colors should be raw ints
-                assertTrue("Type should be int",
-                        value.type >= TypedValue.TYPE_FIRST_INT && value.type <= TypedValue.TYPE_LAST_INT);
-
-                // Validate color from getValue
-                assertEquals("Color should be expected value", expectedColor, value.data);
-            }
-        }
-        assertEquals("Test no longer in sync with colors in android.R.color",
-                colors.length,
-                android.R.color.class.getDeclaredFields().length);
-    }
-
     @Test
     public void testAlpha() {
         assertEquals(0xff, Color.alpha(Color.RED));
diff --git a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
index ba90c0f..66b55f2 100644
--- a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
@@ -252,40 +252,6 @@
     }
 
     @Test
-    public void testInvalidCmapFont_unsortedEntries() {
-        // Following two font files have glyph for U+0400 and U+0100 but the fonts must not be used
-        // due to invalid cmap data. For more details, see each ttx source file.
-        final String[] INVALID_CMAP_FONTS = { "unsorted_cmap4.ttf", "unsorted_cmap12.ttf" };
-        for (final String file : INVALID_CMAP_FONTS) {
-            final Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), file);
-            assertNotNull(typeface);
-            final Paint p = new Paint();
-            final String testString = "\u0100\u0400";
-            final float widthDefaultTypeface = p.measureText(testString);
-            p.setTypeface(typeface);
-            final float widthCustomTypeface = p.measureText(testString);
-            assertEquals(widthDefaultTypeface, widthCustomTypeface, 0.0f);
-        }
-
-        // Following two font files have glyph for U+0400 U+FE00 and U+0100 U+FE00 but the fonts
-        // must not be used due to invalid cmap data. For more details, see each ttx source file.
-        final String[] INVALID_CMAP_VS_FONTS = {
-            "unsorted_cmap14_default_uvs.ttf",
-            "unsorted_cmap14_non_default_uvs.ttf"
-        };
-        for (final String file : INVALID_CMAP_VS_FONTS) {
-            final Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), file);
-            assertNotNull(typeface);
-            final Paint p = new Paint();
-            final String testString = "\u0100\uFE00\u0400\uFE00";
-            final float widthDefaultTypeface = p.measureText(testString);
-            p.setTypeface(typeface);
-            final float widthCustomTypeface = p.measureText(testString);
-            assertEquals(widthDefaultTypeface, widthCustomTypeface, 0.0f);
-        }
-    }
-
-    @Test
     public void testCreateFromAsset_cachesTypeface() {
         Typeface typeface1 = Typeface.createFromAsset(mContext.getAssets(), "bombfont2.ttf");
         assertNotNull(typeface1);
diff --git a/tests/tests/icu/AndroidTest.xml b/tests/tests/icu/AndroidTest.xml
index 53a6efd..2f8f611 100644
--- a/tests/tests/icu/AndroidTest.xml
+++ b/tests/tests/icu/AndroidTest.xml
@@ -19,11 +19,25 @@
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsIcuTestCases.apk" />
     </target_preparer>
+    <!-- ICU tests are split into shards to improve reliability, mostly due to unrecoverable heap
+         growth. http://b/62512577 -->
+    <!-- A shard containing a small set of tests that are run separately to avoid polluting the heap
+         of the MainTestShard. -->
     <test class="com.android.compatibility.testtype.LibcoreTest" >
         <option name="package" value="android.icu.cts" />
         <option name="instrumentation-arg" key="filter"
                 value="com.android.cts.core.runner.ExpectationBasedFilter" />
         <option name="core-expectation" value="/android/icu/cts/expectations/icu-known-failures.txt" />
-        <option name="runtime-hint" value="18m30s" />
+        <option name="runtime-hint" value="20s" />
+        <option name="include-annotation" value="android.icu.testsharding.HiMemTestShard" />
+    </test>
+    <!-- The shard used to run most ICU tests. -->
+    <test class="com.android.compatibility.testtype.LibcoreTest" >
+        <option name="package" value="android.icu.cts" />
+        <option name="instrumentation-arg" key="filter"
+                value="com.android.cts.core.runner.ExpectationBasedFilter" />
+        <option name="core-expectation" value="/android/icu/cts/expectations/icu-known-failures.txt" />
+        <option name="runtime-hint" value="18m" />
+        <option name="include-annotation" value="android.icu.testsharding.MainTestShard" />
     </test>
 </configuration>
diff --git a/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt b/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt
index ebcbd78..a2e6dc4 100644
--- a/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt
+++ b/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt
@@ -11,45 +11,16 @@
 },
 */
 {
-  description: "Class cannot be instantiated, cannot find resources android/icu/dev/test/serializable/data",
-  name: "android.icu.dev.test.serializable.CompatibilityTest",
-  bug: "27310873"
-},
-{
-  description: "Cannot find any classes to test because .class files are not treated as resources in APK",
-  name: "android.icu.dev.test.serializable.CoverageTest",
-  bug: "27666677"
-},
-{
   description: "Serialized forms have not been converted to use repackaged classes",
   name: "android.icu.dev.test.format.NumberFormatRegressionTest#TestSerialization",
   bug: "27374606"
 },
 {
-  description: "android.icu.charset package not available in repackaged Android library",
-  names: [
-    "android.icu.dev.test.charset.TestCharset",
-    "android.icu.dev.test.charset.TestConversion",
-    "android.icu.dev.test.charset.TestSelection"
-  ],
-  bug: "27373370"
-},
-{
   description: "Fails on host and on device in same way before and after packaging",
   name: "android.icu.dev.test.bidi.TestCompatibility#testCompatibility",
   bug: "23995372"
 },
 {
-  description: "Problem with negative multiplier, not a regression",
-  name: "android.icu.dev.test.format.NumberFormatTest#TestNonpositiveMultiplier",
-  bug: "19185440"
-},
-{
-  description: "Wrong case for exponent separator",
-  name: "android.icu.dev.test.format.PluralRulesTest#testOverUnderflow",
-  bug: "27566754"
-},
-{
   description: "Checks differences in DecimalFormat classes from ICU4J and JDK but on Android java.text.DecimalFormat is implemented in terms of ICU4J",
   name: "android.icu.dev.test.format.NumberFormatTest#TestDataDrivenJDK",
   bug: "27711713"
diff --git a/tests/tests/jni/libjninamespacea1/namespacea1.cpp b/tests/tests/jni/libjninamespacea1/namespacea1.cpp
index decb4f1..8a79c3c 100644
--- a/tests/tests/jni/libjninamespacea1/namespacea1.cpp
+++ b/tests/tests/jni/libjninamespacea1/namespacea1.cpp
@@ -18,7 +18,7 @@
 
 #include <android/log.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,"namespacea1",__VA_ARGS__)
 
diff --git a/tests/tests/jni/libjninamespacea2/namespacea2.cpp b/tests/tests/jni/libjninamespacea2/namespacea2.cpp
index 809266e..49f055e 100644
--- a/tests/tests/jni/libjninamespacea2/namespacea2.cpp
+++ b/tests/tests/jni/libjninamespacea2/namespacea2.cpp
@@ -18,7 +18,7 @@
 
 #include <android/log.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,"namespacea2",__VA_ARGS__)
 
diff --git a/tests/tests/jni/libjninamespaceb/namespaceb.cpp b/tests/tests/jni/libjninamespaceb/namespaceb.cpp
index b3bedcb..4c48627 100644
--- a/tests/tests/jni/libjninamespaceb/namespaceb.cpp
+++ b/tests/tests/jni/libjninamespaceb/namespaceb.cpp
@@ -18,7 +18,7 @@
 
 #include <android/log.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,"namespaceb",__VA_ARGS__)
 
diff --git a/tests/tests/jni/libjnitest/Android.mk b/tests/tests/jni/libjnitest/Android.mk
index 7140de4..0703722 100644
--- a/tests/tests/jni/libjnitest/Android.mk
+++ b/tests/tests/jni/libjnitest/Android.mk
@@ -42,4 +42,6 @@
 LOCAL_SDK_VERSION := 23
 LOCAL_NDK_STL_VARIANT := c++_static
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_InstanceNonce.c b/tests/tests/jni/libjnitest/android_jni_cts_InstanceNonce.c
index 3fda82a..cb44b42 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_InstanceNonce.c
+++ b/tests/tests/jni/libjnitest/android_jni_cts_InstanceNonce.c
@@ -20,7 +20,7 @@
  */
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <stdbool.h>
 #include <string.h>
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_JniCTest.c b/tests/tests/jni/libjnitest/android_jni_cts_JniCTest.c
index 23278dc..cca5383 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_JniCTest.c
+++ b/tests/tests/jni/libjnitest/android_jni_cts_JniCTest.c
@@ -19,7 +19,7 @@
  */
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 
 /*
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_JniCppTest.cpp b/tests/tests/jni/libjnitest/android_jni_cts_JniCppTest.cpp
index 38829a0..b0937f4 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_JniCppTest.cpp
+++ b/tests/tests/jni/libjnitest/android_jni_cts_JniCppTest.cpp
@@ -19,7 +19,7 @@
  */
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 
 /*
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_JniStaticTest.cpp b/tests/tests/jni/libjnitest/android_jni_cts_JniStaticTest.cpp
index 5e8bea0..aa5651f 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_JniStaticTest.cpp
+++ b/tests/tests/jni/libjnitest/android_jni_cts_JniStaticTest.cpp
@@ -19,7 +19,7 @@
  */
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 extern "C" JNIEXPORT jint JNICALL Java_android_jni_cts_ClassLoaderHelper_nativeGetHashCode(
         JNIEnv* env,
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
index 504ae01..33a9a1d 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
+++ b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
@@ -22,7 +22,6 @@
 #include <dlfcn.h>
 #include <fcntl.h>
 #include <jni.h>
-#include <JNIHelp.h>
 #include <libgen.h>
 #include <stdlib.h>
 #include <sys/types.h>
@@ -34,8 +33,9 @@
 #include <unordered_set>
 #include <vector>
 
-#include "ScopedLocalRef.h"
-#include "ScopedUtfChars.h"
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 #if defined(__LP64__)
 static const std::string kSystemLibraryPath = "/system/lib64";
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_StaticNonce.c b/tests/tests/jni/libjnitest/android_jni_cts_StaticNonce.c
index ada2bf8..4e330e5 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_StaticNonce.c
+++ b/tests/tests/jni/libjnitest/android_jni_cts_StaticNonce.c
@@ -20,7 +20,7 @@
  */
 
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <stdbool.h>
 #include <string.h>
diff --git a/tests/tests/jni/libjnitest/macroized_tests.c b/tests/tests/jni/libjnitest/macroized_tests.c
index 130b378..e8ac08f 100644
--- a/tests/tests/jni/libjnitest/macroized_tests.c
+++ b/tests/tests/jni/libjnitest/macroized_tests.c
@@ -182,13 +182,13 @@
 // TODO: Missing functions:
 //   AllocObject
 
-static char *help_CallBooleanMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallBooleanMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnBoolean", "()Z");
 
     if (method == NULL) {
@@ -287,13 +287,13 @@
     return help_CallBooleanMethod(env, STATIC_VA);
 }
 
-static char *help_CallByteMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallByteMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnByte", "()B");
 
     if (method == NULL) {
@@ -392,13 +392,13 @@
     return help_CallByteMethod(env, STATIC_VA);
 }
 
-static char *help_CallShortMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallShortMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnShort", "()S");
 
     if (method == NULL) {
@@ -497,13 +497,13 @@
     return help_CallShortMethod(env, STATIC_VA);
 }
 
-static char *help_CallCharMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallCharMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnChar", "()C");
 
     if (method == NULL) {
@@ -602,13 +602,13 @@
     return help_CallCharMethod(env, STATIC_VA);
 }
 
-static char *help_CallIntMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallIntMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnInt", "()I");
 
     if (method == NULL) {
@@ -707,13 +707,13 @@
     return help_CallIntMethod(env, STATIC_VA);
 }
 
-static char *help_CallLongMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallLongMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnLong", "()J");
 
     if (method == NULL) {
@@ -812,13 +812,13 @@
     return help_CallLongMethod(env, STATIC_VA);
 }
 
-static char *help_CallFloatMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallFloatMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnFloat", "()F");
 
     if (method == NULL) {
@@ -917,13 +917,13 @@
     return help_CallFloatMethod(env, STATIC_VA);
 }
 
-static char *help_CallDoubleMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallDoubleMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnDouble", "()D");
 
     if (method == NULL) {
@@ -1022,13 +1022,13 @@
     return help_CallDoubleMethod(env, STATIC_VA);
 }
 
-static char *help_CallVoidMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallVoidMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "nop", "()V");
 
     if (method == NULL) {
@@ -1127,13 +1127,13 @@
     return help_CallVoidMethod(env, STATIC_VA);
 }
 
-static char *help_CallObjectMethod(JNIEnv *env, callType ct, ...) {
+static char *help_CallObjectMethod(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "returnString", "()Ljava/lang/String;");
 
     if (method == NULL) {
@@ -1250,13 +1250,13 @@
     return help_CallObjectMethod(env, STATIC_VA);
 }
 
-static char *help_TakeOneOfEach(JNIEnv *env, callType ct, ...) {
+static char *help_TakeOneOfEach(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "takeOneOfEach", "(DFJICSBZLjava/lang/String;)Z");
 
     if (method == NULL) {
@@ -1372,13 +1372,13 @@
             (jboolean) true, biscuits);
 }
 
-static char *help_TakeCoolHandLuke(JNIEnv *env, callType ct, ...) {
+static char *help_TakeCoolHandLuke(JNIEnv *env, int ct, ...) {
     va_list args;
     va_start(args, ct);
 
     char *msg;
     jobject o = getStandardInstance(env);
-    jmethodID method = findAppropriateMethod(env, &msg, ct,
+    jmethodID method = findAppropriateMethod(env, &msg, (callType)ct,
             "takeCoolHandLuke",
             "(IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII)Z");
 
diff --git a/tests/tests/media/libmediandkjni/codec-utils-jni.cpp b/tests/tests/media/libmediandkjni/codec-utils-jni.cpp
index cb4363e..d7bd74e 100644
--- a/tests/tests/media/libmediandkjni/codec-utils-jni.cpp
+++ b/tests/tests/media/libmediandkjni/codec-utils-jni.cpp
@@ -24,8 +24,8 @@
 #include <sys/types.h>
 #include <jni.h>
 
-#include <ScopedLocalRef.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedLocalRef.h>
 
 #include <math.h>
 
diff --git a/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp b/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp
index aa549b2..6cf9a89 100644
--- a/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp
+++ b/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp
@@ -24,7 +24,7 @@
 
 #include <assert.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 
 #include <android/native_window_jni.h>
 
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
new file mode 100644
index 0000000..af2c7ac
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
new file mode 100644
index 0000000..d1c88fe
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
new file mode 100644
index 0000000..ddae12f
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
new file mode 100644
index 0000000..78bad13
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
new file mode 100644
index 0000000..c7d8429
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
new file mode 100644
index 0000000..c8d4afa
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/video_1280x720_mkv_h265_500kbps_25fps_aac_stereo_128kbps_44100hz.mkv b/tests/tests/media/res/raw/video_1280x720_mkv_h265_500kbps_25fps_aac_stereo_128kbps_44100hz.mkv
new file mode 100644
index 0000000..dd6d3ab
--- /dev/null
+++ b/tests/tests/media/res/raw/video_1280x720_mkv_h265_500kbps_25fps_aac_stereo_128kbps_44100hz.mkv
Binary files differ
diff --git a/tests/tests/media/src/android/media/cts/AdaptivePlaybackTest.java b/tests/tests/media/src/android/media/cts/AdaptivePlaybackTest.java
index 4b5b1d7..93f3b66 100644
--- a/tests/tests/media/src/android/media/cts/AdaptivePlaybackTest.java
+++ b/tests/tests/media/src/android/media/cts/AdaptivePlaybackTest.java
@@ -205,7 +205,7 @@
     public void onlyH263SW()  { ex(H263(SW),  allTests); }
 
     public void bytebuffer() { ex(H264(SW), new EarlyEosTest().byteBuffer()); }
-    public void texture() { ex(H264(HW), new EarlyEosTest().texture()); }
+    public void onlyTexture() { ex(H264(HW), new EarlyEosTest().texture()); }
 
     /* inidividual tests */
     public void testH264_adaptiveEarlyEos()  { ex(H264(),  adaptiveEarlyEos); }
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
index e80dcf4..6b15121 100644
--- a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
@@ -1275,6 +1275,11 @@
         mMediaPlayer.stop();
     }
 
+    public void testLocalVideo_MKV_H265_1280x720_500kbps_25fps_AAC_Stereo_128kbps_44100Hz()
+            throws Exception {
+        playVideoTest(
+                R.raw.video_1280x720_mkv_h265_500kbps_25fps_aac_stereo_128kbps_44100hz, 1280, 720);
+    }
     public void testLocalVideo_MP4_H264_480x360_500kbps_25fps_AAC_Stereo_128kbps_44110Hz()
             throws Exception {
         playVideoTest(
diff --git a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
index 71013cc..97b03d8 100644
--- a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
@@ -533,12 +533,16 @@
         if (!hasCamera()) {
             return;
         }
+        mCamera = Camera.open(0);
+        setSupportedResolution(mCamera);
+        mCamera.unlock();
+
         mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
         mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
         mMediaRecorder.setOutputFile(OUTPUT_PATH2);
         mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
         mMediaRecorder.setPreviewDisplay(mActivity.getSurfaceHolder().getSurface());
-        mMediaRecorder.setVideoSize(VIDEO_WIDTH, VIDEO_HEIGHT);
+        mMediaRecorder.setVideoSize(mVideoWidth, mVideoHeight);
 
         FileOutputStream fos = new FileOutputStream(OUTPUT_PATH2);
         FileDescriptor fd = fos.getFD();
@@ -704,12 +708,16 @@
             MediaUtils.skipTest("no microphone, camera, or codecs");
             return;
         }
+        mCamera = Camera.open(0);
+        setSupportedResolution(mCamera);
+        mCamera.unlock();
+
         mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
         mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
         mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
         mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
         mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
-        mMediaRecorder.setVideoSize(VIDEO_WIDTH, VIDEO_HEIGHT);
+        mMediaRecorder.setVideoSize(mVideoWidth, mVideoHeight);
         mMediaRecorder.setVideoEncodingBitRate(256000);
         mMediaRecorder.setPreviewDisplay(mActivity.getSurfaceHolder().getSurface());
         mMediaRecorder.setMaxFileSize(fileSize);
@@ -1075,6 +1083,7 @@
             mCamera = Camera.open(0);
             Camera.Parameters params = mCamera.getParameters();
             frameRate = params.getPreviewFrameRate();
+            setSupportedResolution(mCamera);
             mCamera.unlock();
             mMediaRecorder.setCamera(mCamera);
             mMediaRecorder.setPreviewDisplay(mActivity.getSurfaceHolder().getSurface());
@@ -1092,7 +1101,7 @@
 
         mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
         mMediaRecorder.setVideoFrameRate(frameRate);
-        mMediaRecorder.setVideoSize(VIDEO_WIDTH, VIDEO_HEIGHT);
+        mMediaRecorder.setVideoSize(mVideoWidth, mVideoHeight);
 
         if (hasAudio) {
             mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
diff --git a/tests/tests/media/src/android/media/cts/MediaScannerTest.java b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
index 3a12e3b..137b7cf 100644
--- a/tests/tests/media/src/android/media/cts/MediaScannerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
@@ -470,7 +470,20 @@
             new MediaScanEntry(R.raw.iso88591_13,
                     new String[] {"Michael Bublé", "Crazy Love", "Michael Bublé", "Haven't Met You Yet", null}),
             new MediaScanEntry(R.raw.utf16_1,
-                    new String[] {"Shakira", "Latin Mix USA", "Shakira", "Estoy Aquí", null})
+                    new String[] {"Shakira", "Latin Mix USA", "Shakira", "Estoy Aquí", null}),
+            // Tags are encoded in different charsets.
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_1,
+                    new String[] {"刘昊霖/kidult.", "鱼干铺里", "刘昊霖/kidult.", "Colin Wine's Mailbox", null}),
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_2,
+                    new String[] {"冰块先生/郭美孜", "hey jude", "冰块先生/郭美孜", "Hey Jude", null}),
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_3,
+                    new String[] {"Toy王奕/Tizzy T/满舒克", "1993", "Toy王奕/Tizzy T/满舒克", "Me&Ma Bros", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_1,
+                    new String[] {"张国荣", "钟情张国荣", null, "左右手", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_2,
+                    new String[] {"纵贯线", "Live in Taipei 出发\\/终点站", null, "皇后大道东(Live)", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_3,
+                    new String[] {"谭咏麟", "二十年白金畅销金曲全记录", null, "知心当玩偶", null})
     };
 
     public void testEncodingDetection() throws Exception {
diff --git a/tests/tests/media/src/android/media/cts/MediaSessionTest.java b/tests/tests/media/src/android/media/cts/MediaSessionTest.java
index 58a643d..0515710 100644
--- a/tests/tests/media/src/android/media/cts/MediaSessionTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaSessionTest.java
@@ -419,13 +419,27 @@
      * Tests {@link MediaSession.QueueItem}.
      */
     public void testQueueItem() {
-        QueueItem item = new QueueItem(new MediaDescription.Builder()
-                .setMediaId("media-id").setTitle("title").build(), TEST_QUEUE_ID);
+        MediaDescription.Builder descriptionBuilder = new MediaDescription.Builder()
+                .setMediaId("media-id")
+                .setTitle("title");
+
+        QueueItem item = new QueueItem(descriptionBuilder.build(), TEST_QUEUE_ID);
         assertEquals(TEST_QUEUE_ID, item.getQueueId());
         assertEquals("media-id", item.getDescription().getMediaId());
         assertEquals("title", item.getDescription().getTitle());
         assertEquals(0, item.describeContents());
 
+        QueueItem sameItem = new QueueItem(descriptionBuilder.build(), TEST_QUEUE_ID);
+        assertTrue(item.equals(sameItem));
+
+        QueueItem differentQueueId = new QueueItem(
+            descriptionBuilder.build(), TEST_QUEUE_ID + 1);
+        assertFalse(item.equals(differentQueueId));
+
+        QueueItem differentDescription = new QueueItem(
+            descriptionBuilder.setTitle("title2").build(), TEST_QUEUE_ID);
+        assertFalse(item.equals(differentDescription));
+
         Parcel p = Parcel.obtain();
         item.writeToParcel(p, 0);
         p.setDataPosition(0);
diff --git a/tests/tests/mediastress/jni/Android.mk b/tests/tests/mediastress/jni/Android.mk
index 164e302..6756bc3 100644
--- a/tests/tests/mediastress/jni/Android.mk
+++ b/tests/tests/mediastress/jni/Android.mk
@@ -29,4 +29,6 @@
 LOCAL_SHARED_LIBRARIES := libandroid libnativehelper_compat_libc++ liblog libOpenMAXAL
 LOCAL_CXX_STL := libc++_static
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/mediastress/jni/native-media-jni.cpp b/tests/tests/mediastress/jni/native-media-jni.cpp
index 4a105e1..42fac20 100644
--- a/tests/tests/mediastress/jni/native-media-jni.cpp
+++ b/tests/tests/mediastress/jni/native-media-jni.cpp
@@ -106,7 +106,7 @@
         return JNI_FALSE;
     }
     assert(1 <= nbRead && nbRead <= NB_BUFFERS);
-    ALOGV("Initially queueing %u buffers of %u bytes each", nbRead, BUFFER_SIZE);
+    ALOGV("Initially queueing %zu buffers of %u bytes each", nbRead, BUFFER_SIZE);
 
     /* Enqueue the content of our cache before starting to play,
        we don't want to starve the player */
diff --git a/tests/tests/net/jni/Android.mk b/tests/tests/net/jni/Android.mk
index 0ec8d28..887e95e 100644
--- a/tests/tests/net/jni/Android.mk
+++ b/tests/tests/net/jni/Android.mk
@@ -27,6 +27,9 @@
 
 LOCAL_SHARED_LIBRARIES := libnativehelper_compat_libc++ liblog
 LOCAL_CXX_STL := libc++_static
+
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
 
 include $(CLEAR_VARS)
diff --git a/tests/tests/net/native/Android.mk b/tests/tests/net/native/Android.mk
index 8338432..b798d87 100644
--- a/tests/tests/net/native/Android.mk
+++ b/tests/tests/net/native/Android.mk
@@ -1,2 +1,15 @@
-include $(call all-subdir-makefiles)
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
 
+include $(call all-subdir-makefiles)
diff --git a/tests/tests/net/native/qtaguid/Android.mk b/tests/tests/net/native/qtaguid/Android.mk
index 4f5bf9f..b3eb28b 100644
--- a/tests/tests/net/native/qtaguid/Android.mk
+++ b/tests/tests/net/native/qtaguid/Android.mk
@@ -16,15 +16,8 @@
 
 LOCAL_PATH:= $(call my-dir)
 
-test_executable := CtsNativeNetTestCases
-list_executable := $(test_executable)_list
-
 include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-
-LOCAL_MODULE := $(test_executable)
-LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE := CtsNativeNetTestCases
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
@@ -33,9 +26,6 @@
 LOCAL_SRC_FILES := \
     src/NativeQtaguidTest.cpp
 
-LOCAL_C_INCLUDES := \
-    external/gtest/include \
-
 LOCAL_SHARED_LIBRARIES := \
     libutils \
     liblog \
@@ -45,27 +35,9 @@
     libgtest
 
 LOCAL_CTS_TEST_PACKAGE := android.net.native
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
 LOCAL_CFLAGS := -Werror -Wall
 
 include $(BUILD_CTS_EXECUTABLE)
-
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE := $(list_executable)
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := \
-    src/NativeQtaguidTest.cpp
-
-LOCAL_CFLAGS := \
-    -DBUILD_ONLY \
-
-LOCAL_SHARED_LIBRARIES := \
-    liblog \
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/tests/tests/net/native/qtaguid/src/NativeQtaguidTest.cpp b/tests/tests/net/native/qtaguid/src/NativeQtaguidTest.cpp
index 0301c81..9009c24 100644
--- a/tests/tests/net/native/qtaguid/src/NativeQtaguidTest.cpp
+++ b/tests/tests/net/native/qtaguid/src/NativeQtaguidTest.cpp
@@ -17,16 +17,12 @@
 #include <arpa/inet.h>
 #include <errno.h>
 #include <inttypes.h>
-#include <stdlib.h>
 #include <string.h>
 #include <sys/socket.h>
+
 #include <gtest/gtest.h>
-
-#if !defined(BUILD_ONLY)
 #include <cutils/qtaguid.h>
-#endif
 
-#if !defined(BUILD_ONLY)
 int getCtrlSkInfo(int tag, uid_t uid, uint64_t* sk_addr, int* ref_cnt) {
     FILE *fp;
     fp = fopen("/proc/net/xt_qtaguid/ctrl", "r");
@@ -69,12 +65,35 @@
     EXPECT_EQ(0, qtaguid_tagSocket(sockfd, tag, uid));
     EXPECT_EQ(0, getCtrlSkInfo(tag, uid, &sk_addr, &ref_cnt));
     EXPECT_EQ(expect_addr, sk_addr);
-    EXPECT_EQ(0, qtaguid_untagSocket(sockfd));
+    close(sockfd);
     EXPECT_EQ(-ENOENT, getCtrlSkInfo(tag, uid, &sk_addr, &ref_cnt));
 }
-#else
-void checkNoSocketPointerLeaks(int family) {}
-#endif
+
+TEST (NativeQtaguidTest, close_socket_without_untag) {
+    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
+    uid_t uid = getuid();
+    int tag = arc4random();
+    int ref_cnt;
+    uint64_t dummy_sk;
+    EXPECT_EQ(0, qtaguid_tagSocket(sockfd, tag, uid));
+    EXPECT_EQ(0, getCtrlSkInfo(tag, uid, &dummy_sk, &ref_cnt));
+    EXPECT_EQ(2, ref_cnt);
+    close(sockfd);
+    EXPECT_EQ(-ENOENT, getCtrlSkInfo(tag, uid, &dummy_sk, &ref_cnt));
+}
+
+TEST (NativeQtaguidTest, close_socket_without_untag_ipv6) {
+    int sockfd = socket(AF_INET6, SOCK_STREAM, 0);
+    uid_t uid = getuid();
+    int tag = arc4random();
+    int ref_cnt;
+    uint64_t dummy_sk;
+    EXPECT_EQ(0, qtaguid_tagSocket(sockfd, tag, uid));
+    EXPECT_EQ(0, getCtrlSkInfo(tag, uid, &dummy_sk, &ref_cnt));
+    EXPECT_EQ(2, ref_cnt);
+    close(sockfd);
+    EXPECT_EQ(-ENOENT, getCtrlSkInfo(tag, uid, &dummy_sk, &ref_cnt));
+}
 
 TEST (NativeQtaguidTest, no_socket_addr_leak) {
   checkNoSocketPointerLeaks(AF_INET);
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index cd6dbb2..e98dfcc 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -37,6 +37,7 @@
 import android.net.NetworkInfo.State;
 import android.net.NetworkRequest;
 import android.net.wifi.WifiManager;
+import android.os.Looper;
 import android.os.SystemProperties;
 import android.system.Os;
 import android.system.OsConstants;
@@ -110,6 +111,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
+        Looper.prepare();
         mContext = getContext();
         mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
         mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
@@ -279,11 +281,10 @@
     }
 
     private boolean isSupported(int networkType) {
-        // Change-Id I02eb5f22737720095f646f8db5c87fd66da129d6 added VPN support
-        // to all devices directly in software, independent of any external
-        // configuration.
         return mNetworks.containsKey(networkType) ||
-               (networkType == ConnectivityManager.TYPE_VPN);
+               (networkType == ConnectivityManager.TYPE_VPN) ||
+               (networkType == ConnectivityManager.TYPE_ETHERNET &&
+                       mContext.getSystemService(Context.ETHERNET_SERVICE) != null);
     }
 
     public void testIsNetworkSupported() {
diff --git a/tests/tests/net/src/android/net/cts/IpSecManagerTest.java b/tests/tests/net/src/android/net/cts/IpSecManagerTest.java
new file mode 100644
index 0000000..bcecee1
--- /dev/null
+++ b/tests/tests/net/src/android/net/cts/IpSecManagerTest.java
@@ -0,0 +1,171 @@
+/*
+ * 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.net.cts;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.IpSecAlgorithm;
+import android.net.IpSecManager;
+import android.net.IpSecTransform;
+import android.os.ParcelFileDescriptor;
+import android.system.Os;
+import android.system.OsConstants;
+import android.test.AndroidTestCase;
+import java.io.ByteArrayOutputStream;
+import java.net.DatagramSocket;
+import java.io.FileDescriptor;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+
+public class IpSecManagerTest extends AndroidTestCase {
+
+    private static final String TAG = IpSecManagerTest.class.getSimpleName();
+
+    private IpSecManager mISM;
+
+    private ConnectivityManager mCM;
+
+    private static final InetAddress GOOGLE_DNS_4;
+    private static final InetAddress GOOGLE_DNS_6;
+
+    static {
+        try {
+            // Google Public DNS Addresses;
+            GOOGLE_DNS_4 = InetAddress.getByName("8.8.8.8");
+            GOOGLE_DNS_6 = InetAddress.getByName("2001:4860:4860::8888");
+        } catch (UnknownHostException e) {
+            throw new RuntimeException("Could not resolve DNS Addresses", e);
+        }
+    }
+
+    private static final InetAddress[] GOOGLE_DNS_LIST =
+            new InetAddress[] {GOOGLE_DNS_4, GOOGLE_DNS_6};
+
+    private static final int DROID_SPI = 0xD1201D;
+
+    private static final byte[] CRYPT_KEY =
+            new byte[] {
+                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
+                0x0E, 0x0F
+            };
+    private static final byte[] AUTH_KEY =
+            new byte[] {
+                0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                0x00, 0x7F
+            };
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        mCM = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+        mISM = (IpSecManager) getContext().getSystemService(Context.IPSEC_SERVICE);
+    }
+
+    /*
+     * Allocate a random SPI
+     * Allocate a specific SPI using previous randomly created SPI value
+     * Realloc the same SPI that was specifically created (expect SpiUnavailable)
+     * Close SPIs
+     */
+    public void testAllocSpi() throws Exception {
+        for (InetAddress addr : GOOGLE_DNS_LIST) {
+            IpSecManager.SecurityParameterIndex randomSpi = null, droidSpi = null;
+            randomSpi = mISM.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_OUT, addr);
+            assertTrue(
+                    "Failed to receive a valid SPI",
+                    randomSpi.getSpi() != IpSecManager.INVALID_SECURITY_PARAMETER_INDEX);
+
+            droidSpi =
+                    mISM.reserveSecurityParameterIndex(
+                            IpSecTransform.DIRECTION_IN, addr, DROID_SPI);
+            assertTrue(
+                    "Failed to allocate specified SPI, " + DROID_SPI,
+                    droidSpi.getSpi() == DROID_SPI);
+
+            try {
+                mISM.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_IN, addr, DROID_SPI);
+                fail("Duplicate SPI was allowed to be created");
+            } catch (IpSecManager.SpiUnavailableException expected) {
+                // This is a success case because we expect a dupe SPI to throw
+            }
+
+            randomSpi.close();
+            droidSpi.close();
+        }
+    }
+
+    /*
+     * Alloc outbound SPI
+     * Alloc inbound SPI
+     * Create transport mode transform
+     * open socket
+     * apply transform to socket
+     * send data on socket
+     * release transform
+     * send data (expect exception)
+     */
+    public void testCreateTransform() throws Exception {
+        InetAddress local = InetAddress.getLoopbackAddress();
+        IpSecManager.SecurityParameterIndex outSpi =
+                mISM.reserveSecurityParameterIndex(IpSecTransform.DIRECTION_OUT, local);
+
+        IpSecManager.SecurityParameterIndex inSpi =
+                mISM.reserveSecurityParameterIndex(
+                        IpSecTransform.DIRECTION_IN, local, outSpi.getSpi());
+
+        IpSecTransform transform =
+                new IpSecTransform.Builder(mContext)
+                        .setSpi(IpSecTransform.DIRECTION_OUT, outSpi)
+                        .setEncryption(
+                                IpSecTransform.DIRECTION_OUT,
+                                new IpSecAlgorithm(IpSecAlgorithm.CRYPT_AES_CBC, CRYPT_KEY))
+                        .setAuthentication(
+                                IpSecTransform.DIRECTION_OUT,
+                                new IpSecAlgorithm(
+                                        IpSecAlgorithm.AUTH_HMAC_SHA256,
+                                        AUTH_KEY,
+                                        AUTH_KEY.length * 8))
+                        .setSpi(IpSecTransform.DIRECTION_IN, inSpi)
+                        .setEncryption(
+                                IpSecTransform.DIRECTION_IN,
+                                new IpSecAlgorithm(IpSecAlgorithm.CRYPT_AES_CBC, CRYPT_KEY))
+                        .setAuthentication(
+                                IpSecTransform.DIRECTION_IN,
+                                new IpSecAlgorithm(
+                                        IpSecAlgorithm.AUTH_HMAC_SHA256,
+                                        AUTH_KEY,
+                                        CRYPT_KEY.length * 8))
+                        .buildTransportModeTransform(local);
+
+        // Hack to ensure the socket doesn't block indefinitely on failure
+        DatagramSocket localSocket = new DatagramSocket(8888);
+        localSocket.setSoTimeout(500);
+        ParcelFileDescriptor pin = ParcelFileDescriptor.fromDatagramSocket(localSocket);
+        FileDescriptor udpSocket = pin.getFileDescriptor();
+
+        mISM.applyTransportModeTransform(udpSocket, transform);
+        byte[] data = new String("Best test data ever!").getBytes("UTF-8");
+
+        byte[] in = new byte[data.length];
+        Os.sendto(udpSocket, data, 0, data.length, 0, local, 8888);
+        Os.read(udpSocket, in, 0, in.length);
+        assertTrue("Encapsulated data did not match.", Arrays.equals(data, in));
+        mISM.removeTransportModeTransform(udpSocket, transform);
+        Os.close(udpSocket);
+        transform.close();
+    }
+}
diff --git a/tests/tests/opengl/libopengltest/Android.mk b/tests/tests/opengl/libopengltest/Android.mk
index afa94dc..f05fd8c 100755
--- a/tests/tests/opengl/libopengltest/Android.mk
+++ b/tests/tests/opengl/libopengltest/Android.mk
@@ -39,6 +39,9 @@
 LOCAL_CXX_STL := libc++_static
 
 LOCAL_SHARED_LIBRARIES := libGLESv2 liblog
+
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
 
 
diff --git a/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp b/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp
index fe49b1b..a511f9a 100755
--- a/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp
+++ b/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp
@@ -135,7 +135,7 @@
         jclass obj, jint pCategory, jint pSubCategory, jfloatArray color)
 {
     LOGI("Inside draw %d %d", pCategory, pSubCategory);
-    jfloatArray result;
+    jfloatArray result = nullptr;
     if(pCategory == 3){
         if(pSubCategory == 1){
             result = env->NewFloatArray(4);
@@ -143,8 +143,8 @@
             jfloat *lColor =  env->GetFloatArrayElements(color,0);
 
             float * actualColor = drawColorOne(lColor);
-            for( int i= 0; i < sizeof(actualColor); i++) {
-                LOGI("actualColor[%d] ; %f", i, actualColor[i]);
+            for(unsigned i = 0; i < sizeof(actualColor); i++) {
+                LOGI("actualColor[%u] ; %f", i, actualColor[i]);
             }
             env->SetFloatArrayRegion(result, 0, 4, actualColor);
         }
diff --git a/tests/tests/openglperf/jni/Android.mk b/tests/tests/openglperf/jni/Android.mk
index d6df59b..3fe448a 100644
--- a/tests/tests/openglperf/jni/Android.mk
+++ b/tests/tests/openglperf/jni/Android.mk
@@ -28,4 +28,6 @@
 
 LOCAL_SDK_VERSION := 14
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/os/assets/platform_versions.txt b/tests/tests/os/assets/platform_versions.txt
index ae9a76b..52c184f 100644
--- a/tests/tests/os/assets/platform_versions.txt
+++ b/tests/tests/os/assets/platform_versions.txt
@@ -1 +1 @@
-8.0.0
+P
diff --git a/tests/tests/os/jni/Android.mk b/tests/tests/os/jni/Android.mk
index ffd1b96..6a061a0 100644
--- a/tests/tests/os/jni/Android.mk
+++ b/tests/tests/os/jni/Android.mk
@@ -55,4 +55,15 @@
 	LOCAL_CFLAGS += -DARCH_SUPPORTS_SECCOMP
 endif
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
+# Let's overwrite -mcpu in case it's set to some ARMv8 core by
+# TARGET_2ND_CPU_VARIANT and causes clang to ignore the -march below.
+LOCAL_CPPFLAGS_arm := -mcpu=generic
+
+# The ARM version of this library must be built using ARMv7 ISA (even if it
+# can be run on armv8 cores) since one of the tested instruction, swp, is
+# only supported in ARMv7 (and older) cores, and obsolete in ARMv8.
+LOCAL_CPPFLAGS_arm += -march=armv7-a
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/os/jni/android_os_cts_TaggedPointer.cpp b/tests/tests/os/jni/android_os_cts_TaggedPointer.cpp
index f656f50..dca6ae2 100644
--- a/tests/tests/os/jni/android_os_cts_TaggedPointer.cpp
+++ b/tests/tests/os/jni/android_os_cts_TaggedPointer.cpp
@@ -18,7 +18,6 @@
 #include <inttypes.h>
 #include <setjmp.h>
 #include <signal.h>
-#include <stdbool.h>
 #include <stdlib.h>
 #include <string.h>
 
diff --git a/tests/tests/os/src/android/os/cts/AsyncTaskTest.java b/tests/tests/os/src/android/os/cts/AsyncTaskTest.java
index 335818a..1c2f91e 100644
--- a/tests/tests/os/src/android/os/cts/AsyncTaskTest.java
+++ b/tests/tests/os/src/android/os/cts/AsyncTaskTest.java
@@ -201,7 +201,7 @@
                 try {
                     command.run();
                     fail("Exception not thrown");
-                } catch (Throwable tr) {
+                } catch (Exception tr) {
                     // expected
                 }
             }
diff --git a/tests/tests/os/src/android/os/cts/BuildTest.java b/tests/tests/os/src/android/os/cts/BuildTest.java
index c9650bd..f62b470 100644
--- a/tests/tests/os/src/android/os/cts/BuildTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildTest.java
@@ -241,8 +241,11 @@
                     // should at least be a conscious decision.
                     assertEquals(10000, fieldValue);
                 } else if (fieldName.equals(CODENAME) && !CODENAME.equals("REL")) {
-                    // This is the current development version.
-                    assertEquals(CUR_DEVELOPMENT, fieldValue);
+                    // This is the current development version. Note that fieldName can
+                    // become < CUR_DEVELOPMENT before CODENAME becomes "REL", so we
+                    // can't assertEquals(CUR_DEVELOPMENT, fieldValue) here.
+                    assertTrue("Expected " + fieldName + " value to be <= " + CUR_DEVELOPMENT
+                            + ", got " + fieldValue, fieldValue <= CUR_DEVELOPMENT);
                 } else {
                     assertTrue("Expected " + fieldName + " value to be < " + CUR_DEVELOPMENT
                             + ", got " + fieldValue, fieldValue < CUR_DEVELOPMENT);
diff --git a/tests/tests/os/src/android/os/cts/LooperTest.java b/tests/tests/os/src/android/os/cts/LooperTest.java
index c0a176c..b89f590 100644
--- a/tests/tests/os/src/android/os/cts/LooperTest.java
+++ b/tests/tests/os/src/android/os/cts/LooperTest.java
@@ -97,11 +97,15 @@
     public void testMyQueue() throws Throwable {
         TestThread t = new TestThread(new Runnable() {
             public void run() {
+                boolean didThrow = false;
                 try {
                     assertNull(Looper.myQueue());
-                    fail("should throw exception");
                 } catch (Throwable e) {
                     // expected
+                    didThrow = true;
+                }
+                if (!didThrow) {
+                    fail("should throw exception");
                 }
                 Looper.prepare();
                 MessageQueue mq = Looper.myQueue();
@@ -132,7 +136,7 @@
                 try {
                     Looper.prepare();
                     fail("should throw exception");
-                } catch (Throwable e) {
+                } catch (Exception e) {
                     //expected
                 }
             }
@@ -147,7 +151,7 @@
                 try {
                     Looper.prepareMainLooper();
                     fail("should throw exception because the main thread was already prepared");
-                } catch (Throwable e) {
+                } catch (Exception e) {
                     //expected
                 }
             }
diff --git a/tests/tests/permission/jni/Android.mk b/tests/tests/permission/jni/Android.mk
index 91c0540..e8b3f1a 100644
--- a/tests/tests/permission/jni/Android.mk
+++ b/tests/tests/permission/jni/Android.mk
@@ -30,5 +30,8 @@
 LOCAL_SHARED_LIBRARIES := libnativehelper_compat_libc++ liblog
 LOCAL_SDK_VERSION := 23
 LOCAL_CPPFLAGS := -std=gnu++11
+LOCAL_NDK_STL_VARIANT := c++_static
+
+LOCAL_CFLAGS := -Wno-unused-parameter
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp b/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp
index 0547be4..22dae69 100644
--- a/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp
+++ b/tests/tests/permission/jni/android_permission_cts_FileUtils.cpp
@@ -25,9 +25,9 @@
 #include <grp.h>
 #include <pwd.h>
 #include <string.h>
-#include <ScopedLocalRef.h>
-#include <ScopedPrimitiveArray.h>
-#include <ScopedUtfChars.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+#include <nativehelper/ScopedUtfChars.h>
 
 static jfieldID gFileStatusDevFieldID;
 static jfieldID gFileStatusInoFieldID;
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index c639251..4571556 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -169,6 +169,24 @@
         assertFalse(f.canExecute());
     }
 
+    /* b/26813932 */
+    @MediumTest
+    public void testProcInterruptsNotReadable() throws Exception {
+        File f = new File("/proc/interrupts");
+        assertFalse(f.canRead());
+        assertFalse(f.canWrite());
+        assertFalse(f.canExecute());
+    }
+
+    /* b/26813932 */
+    @MediumTest
+    public void testProcStatNotReadable() throws Exception {
+        File f = new File("/proc/stat");
+        assertFalse(f.canRead());
+        assertFalse(f.canWrite());
+        assertFalse(f.canExecute());
+    }
+
     @MediumTest
     public void testDevMemSane() throws Exception {
         File f = new File("/dev/mem");
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index 4223535..4b83937 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -202,8 +202,8 @@
         android:name="com.android.bluetooth.BluetoothMapContentObserver.action.MESSAGE_DELIVERY" />
     <protected-broadcast
         android:name="android.bluetooth.pan.profile.action.CONNECTION_STATE_CHANGED" />
-    <protected-broadcast android:name="android.bluetooth.pbap.intent.action.PBAP_STATE_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.pbap.profile.action.CONNECTION_STATE_CHANGED" />
+    <protected-broadcast android:name="android.bluetooth.pbapclient.profile.action.CONNECTION_STATE_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.sap.profile.action.CONNECTION_STATE_CHANGED" />
     <protected-broadcast android:name="android.btopp.intent.action.INCOMING_FILE_NOTIFICATION" />
     <protected-broadcast android:name="android.btopp.intent.action.USER_CONFIRMATION_TIMEOUT" />
@@ -2199,6 +2199,22 @@
     <permission android:name="android.permission.UPDATE_CONFIG"
         android:protectionLevel="signature|privileged" />
 
+    <!-- Allows a time zone rule updater application to request
+         the system installs / uninstalls timezone rules.
+         <p>An application requesting this permission is responsible for
+         verifying the source and integrity of the update before passing
+         it off to the installer components.
+         @hide -->
+    <permission android:name="android.permission.UPDATE_TIME_ZONE_RULES"
+                android:protectionLevel="signature|privileged" />
+
+    <!-- Must be required by a time zone rule updater application,
+         to ensure that only the system can trigger it.
+         @hide -->
+    <permission android:name="android.permission.TRIGGER_TIME_ZONE_RULES_CHECK"
+                android:protectionLevel="signature" />
+    <uses-permission android:name="android.permission.TRIGGER_TIME_ZONE_RULES_CHECK"/>
+
     <!-- Allows the system to reset throttling in shortcut manager.
          @hide -->
     <permission android:name="android.permission.RESET_SHORTCUT_MANAGER_THROTTLING"
@@ -2332,6 +2348,24 @@
     <permission android:name="android.permission.INTERNAL_SYSTEM_WINDOW"
         android:protectionLevel="signature" />
 
+    <!-- @SystemApi Allows an application to use
+        {@link android.view.WindowManager.LayoutsParams#PRIVATE_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS}
+        to hide non-system-overlay windows.
+        <p>Not for use by third-party applications.
+        @hide
+    -->
+    <permission android:name="android.permission.HIDE_NON_SYSTEM_OVERLAY_WINDOWS"
+                android:protectionLevel="signature|installer" />
+
+    <!-- @SystemApi Allows an application to use
+        {@link android.view.WindowManager.LayoutsParams#PRIVATE_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS}
+        to hide non-system-overlay windows.
+        <p>Not for use by third-party applications.
+        @hide
+    -->
+    <permission android:name="android.permission.HIDE_NON_SYSTEM_OVERLAY_WINDOWS"
+                android:protectionLevel="signature|installer" />
+
     <!-- @SystemApi Allows an application to manage (create, destroy,
          Z-order) application tokens in the window manager.
          <p>Not for use by third-party applications.
diff --git a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
index 577bb92..58cb166 100644
--- a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
@@ -29,15 +29,24 @@
 
 import java.io.InputStream;
 import java.lang.String;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import static android.os.Build.VERSION.SECURITY_PATCH;
+
 /**
  * Tests for permission policy on the platform.
  */
 public class PermissionPolicyTest extends AndroidTestCase {
+    private static final Date HIDE_NON_SYSTEM_OVERLAY_WINDOWS_PATCH_DATE = parseDate("2017-09-05");
+    private static final String HIDE_NON_SYSTEM_OVERLAY_WINDOWS_PERMISSION
+            = "android.permission.HIDE_NON_SYSTEM_OVERLAY_WINDOWS";
+
     private static final String LOG_TAG = "PermissionProtectionTest";
 
     private static final String PLATFORM_PACKAGE_NAME = "android";
@@ -68,8 +77,12 @@
         Set<String> expectedPermissionGroups = new ArraySet<String>();
 
         for (PermissionInfo expectedPermission : loadExpectedPermissions()) {
-            // OEMs cannot remove permissions
             String expectedPermissionName = expectedPermission.name;
+            if (shouldSkipPermission(expectedPermissionName)) {
+                continue;
+            }
+
+            // OEMs cannot remove permissions
             PermissionInfo declaredPermission = declaredPermissionsMap.get(expectedPermissionName);
             assertNotNull("Permission " + expectedPermissionName
                     + " must be declared", declaredPermission);
@@ -214,4 +227,21 @@
         }
         return protectionLevel;
     }
+
+    private static Date parseDate(String date) {
+        Date patchDate = new Date();
+        try {
+            SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");
+            patchDate = template.parse(date);
+        } catch (ParseException e) {
+        }
+
+        return patchDate;
+    }
+
+    private boolean shouldSkipPermission(String permissionName) {
+        return parseDate(SECURITY_PATCH).before(HIDE_NON_SYSTEM_OVERLAY_WINDOWS_PATCH_DATE) &&
+                HIDE_NON_SYSTEM_OVERLAY_WINDOWS_PERMISSION.equals(permissionName);
+
+    }
 }
diff --git a/tests/tests/provider/Android.mk b/tests/tests/provider/Android.mk
index 2298378..9f1c1da 100644
--- a/tests/tests/provider/Android.mk
+++ b/tests/tests/provider/Android.mk
@@ -28,15 +28,14 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
-LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common
+LOCAL_JAVA_LIBRARIES := android.test.mock legacy-android-test telephony-common
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     android-support-v4 \
     compatibility-device-util \
     ctstestrunner \
     ub-uiautomator \
-    junit \
-    legacy-android-test
+    junit
 
 LOCAL_JNI_SHARED_LIBRARIES := libcts_jni libnativehelper_compat_libc++
 
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/CoreMathVerifier.java b/tests/tests/renderscript/src/android/renderscript/cts/CoreMathVerifier.java
index bc13144..cf535e8 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/CoreMathVerifier.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/CoreMathVerifier.java
@@ -3045,9 +3045,9 @@
         RemquoResult expected = remquo(args.inNumerator, args.inDenominator);
         // If the expected remainder is NaN, we don't validate the quotient.  It's because of
         // a division by zero.
-        if (expected.remainder != expected.remainder) {
+        if (Float.isNaN(expected.remainder)) {
             // Check that the value we got is NaN too.
-            if (args.out == args.out) {
+            if (!Float.isNaN(args.out)) {
                 return "Expected a remainder of NaN but got " +  Float.toString(args.out);
             }
         } else {
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/SingleSourceForEachTest.java b/tests/tests/renderscript/src/android/renderscript/cts/SingleSourceForEachTest.java
index 06eb606..5f17655 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/SingleSourceForEachTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/SingleSourceForEachTest.java
@@ -125,4 +125,11 @@
         baselineOutputAlloc.copyTo(baselineOutputArray);
         checkArray(baselineOutputArray, testOutputArray, Y, X, X);
     }
+
+    public void testConsistency() {
+        s.invoke_testConsistency(testInputAlloc, testOutputAlloc);
+        mRS.finish();
+        waitForMessage();
+        checkForErrors();
+    }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Target.java b/tests/tests/renderscript/src/android/renderscript/cts/Target.java
index 55d3712..3ac4ff8 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Target.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Target.java
@@ -341,7 +341,7 @@
             mHasRange = false;
             mValue = values[0];
             for (double f: values) {
-                if (f != f) {
+                if (Double.isNaN(f)) {
                     mCanBeNan = true;
                     continue;
                 }
@@ -573,7 +573,7 @@
         public boolean couldBe(double a, double extraAllowedError) {
             //Log.w("Floaty.couldBe", "Can " + Double.toString(a) + " be " + toString() + "? ");
             // Handle the input being a NaN.
-            if (a != a) {
+            if (Double.isNaN(a)) {
                 //Log.w("couldBe", "true because is Naan");
                 return mCanBeNan;
             }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/single_source_script.rs b/tests/tests/renderscript/src/android/renderscript/cts/single_source_script.rs
index 5e35aa3..c3e322b 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/single_source_script.rs
+++ b/tests/tests/renderscript/src/android/renderscript/cts/single_source_script.rs
@@ -27,9 +27,9 @@
 }
 
 void RS_KERNEL bar(int x, int y) {
-  int a = rsGetElementAt_int(gAllocOut, x, y);
-  a++;
-  rsSetElementAt_int(gAllocOut, a, x, y);
+    int a = rsGetElementAt_int(gAllocOut, x, y);
+    a++;
+    rsSetElementAt_int(gAllocOut, a, x, y);
 }
 
 void testSingleInput(rs_allocation in, rs_allocation out) {
@@ -58,3 +58,19 @@
     opts.yEnd = dimY;
     rsForEachWithOptions(bar, &opts);
 }
+
+void testConsistency(rs_allocation in, rs_allocation out) {
+    rsForEach(foo, in, out);
+    const uint32_t dimX = rsAllocationGetDimX(in);
+    const uint32_t dimY = rsAllocationGetDimY(in);
+    for (int i = 0; i < dimX; i++) {
+        for (int j = 0; j < dimY; j++) {
+            if (rsGetElementAt_int(out, i, j) != 2 * rsGetElementAt_int(in, i, j)) {
+                rsSendToClientBlocking(RS_MSG_TEST_FAILED);
+                return;
+            }
+        }
+    }
+    rsSendToClientBlocking(RS_MSG_TEST_PASSED);
+}
+
diff --git a/tests/tests/rsblas/libbnnmdata/Android.mk b/tests/tests/rsblas/libbnnmdata/Android.mk
index bbfd289..84fb4e6 100644
--- a/tests/tests/rsblas/libbnnmdata/Android.mk
+++ b/tests/tests/rsblas/libbnnmdata/Android.mk
@@ -14,7 +14,6 @@
 
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
-LOCAL_CLANG := true
 
 LOCAL_MODULE := libbnnmdata_jni
 LOCAL_MODULE_TAGS := optional
diff --git a/tests/tests/rscpp/librscpptest/Android.mk b/tests/tests/rscpp/librscpptest/Android.mk
index 36eafe2..47ab6dd3 100644
--- a/tests/tests/rscpp/librscpptest/Android.mk
+++ b/tests/tests/rscpp/librscpptest/Android.mk
@@ -18,7 +18,6 @@
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-LOCAL_CLANG := true
 LOCAL_MODULE := librscpptest_jni
 LOCAL_MODULE_TAGS := optional
 
@@ -46,6 +45,7 @@
 LOCAL_C_INCLUDES += frameworks/rs
 
 LOCAL_CPPFLAGS := -std=c++11
+LOCAL_CFLAGS := -Wno-unused-parameter
 
 LOCAL_SHARED_LIBRARIES := libdl liblog
 LOCAL_STATIC_LIBRARIES := libRScpp_static
diff --git a/tests/tests/security/jni/Android.mk b/tests/tests/security/jni/Android.mk
index 118744e..dd069fe 100644
--- a/tests/tests/security/jni/Android.mk
+++ b/tests/tests/security/jni/Android.mk
@@ -46,4 +46,6 @@
 LOCAL_C_INCLUDES += ndk/sources/cpufeatures
 LOCAL_STATIC_LIBRARIES := cpufeatures
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/security/jni/android_security_cts_EncryptionTest.cpp b/tests/tests/security/jni/android_security_cts_EncryptionTest.cpp
index 136b52b..47f760a 100644
--- a/tests/tests/security/jni/android_security_cts_EncryptionTest.cpp
+++ b/tests/tests/security/jni/android_security_cts_EncryptionTest.cpp
@@ -18,7 +18,7 @@
 #include <cutils/log.h>
 #include <cutils/properties.h>
 #include <jni.h>
-#include <JNIHelp.h>
+#include <nativehelper/JNIHelp.h>
 #include <openssl/aes.h>
 #include <openssl/cpu.h>
 #include <openssl/evp.h>
diff --git a/tests/tests/security/jni/android_security_cts_LinuxRngTest.cpp b/tests/tests/security/jni/android_security_cts_LinuxRngTest.cpp
index 9b8016e..8514f8b 100644
--- a/tests/tests/security/jni/android_security_cts_LinuxRngTest.cpp
+++ b/tests/tests/security/jni/android_security_cts_LinuxRngTest.cpp
@@ -20,6 +20,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
+#include <sys/sysmacros.h>
 
 /*
  * Native methods used by
diff --git a/tests/tests/security/jni/android_security_cts_SELinuxTest.cpp b/tests/tests/security/jni/android_security_cts_SELinuxTest.cpp
index 1cfde0a..c7975ec 100644
--- a/tests/tests/security/jni/android_security_cts_SELinuxTest.cpp
+++ b/tests/tests/security/jni/android_security_cts_SELinuxTest.cpp
@@ -15,10 +15,10 @@
  */
 
 #include <jni.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
 #include <selinux/selinux.h>
-#include <JNIHelp.h>
-#include <ScopedLocalRef.h>
-#include <ScopedUtfChars.h>
 
 #include <memory>
 
diff --git a/tests/tests/security/src/android/security/cts/CryptoProviderWorkaroundTest.java b/tests/tests/security/src/android/security/cts/CryptoProviderWorkaroundTest.java
deleted file mode 100644
index 861c443..0000000
--- a/tests/tests/security/src/android/security/cts/CryptoProviderWorkaroundTest.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * 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 static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-
-import dalvik.system.VMRuntime;
-import java.security.NoSuchProviderException;
-import java.security.SecureRandom;
-import java.security.Security;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-/**
- * http://b/28550092 : Removal of "Crypto" provider in N caused application compatibility
- * issues for callers of SecureRandom. To improve compatibility the provider is not registered
- * as a JCA Provider obtainable via Security.getProvider() but is made available for
- * SecureRandom.getInstance() iff the application targets API <= 23.
- */
-@RunWith(JUnit4.class)
-public class CryptoProviderWorkaroundTest {
-    @Test
-    public void cryptoProvider_withWorkaround_Success() throws Exception {
-        // Assert that SecureRandom is still using the default value. Sanity check.
-        assertEquals(SecureRandom.DEFAULT_SDK_TARGET_FOR_CRYPTO_PROVIDER_WORKAROUND,
-                SecureRandom.getSdkTargetForCryptoProviderWorkaround());
-
-        try {
-            // Modify the maximum target SDK to apply the workaround, thereby enabling the
-            // workaround for the current SDK and enabling it to be tested.
-            SecureRandom.setSdkTargetForCryptoProviderWorkaround(
-                    VMRuntime.getRuntime().getTargetSdkVersion());
-
-            // Assert that the crypto provider is not installed...
-            assertNull(Security.getProvider("Crypto"));
-            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
-            assertNotNull(sr);
-            // ...but we can get a SecureRandom from it...
-            assertEquals("org.apache.harmony.security.provider.crypto.CryptoProvider",
-                    sr.getProvider().getClass().getName());
-            // ...yet it's not installed. So the workaround worked.
-            assertNull(Security.getProvider("Crypto"));
-        } finally {
-            // Reset the target SDK for the workaround to the default / real value.
-            SecureRandom.setSdkTargetForCryptoProviderWorkaround(
-                    SecureRandom.DEFAULT_SDK_TARGET_FOR_CRYPTO_PROVIDER_WORKAROUND);
-        }
-    }
-
-    @Test
-    public void cryptoProvider_withoutWorkaround_Failure() throws Exception {
-        // Assert that SecureRandom is still using the default value. Sanity check.
-        assertEquals(SecureRandom.DEFAULT_SDK_TARGET_FOR_CRYPTO_PROVIDER_WORKAROUND,
-                SecureRandom.getSdkTargetForCryptoProviderWorkaround());
-
-        try {
-            // We set the limit SDK for the workaround at the previous one, indicating that the
-            // workaround shouldn't be in place.
-            SecureRandom.setSdkTargetForCryptoProviderWorkaround(
-                    VMRuntime.getRuntime().getTargetSdkVersion() - 1);
-
-            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
-            fail("Should throw " + NoSuchProviderException.class.getName());
-        } catch(NoSuchProviderException expected) {
-            // The workaround doesn't work. As expected.
-        } finally {
-            // Reset the target SDK for the workaround to the default / real value.
-            SecureRandom.setSdkTargetForCryptoProviderWorkaround(
-                    SecureRandom.DEFAULT_SDK_TARGET_FOR_CRYPTO_PROVIDER_WORKAROUND);
-        }
-    }
-}
diff --git a/tests/tests/security/testeffect/Android.mk b/tests/tests/security/testeffect/Android.mk
index a7e3cac..7e4ab93 100644
--- a/tests/tests/security/testeffect/Android.mk
+++ b/tests/tests/security/testeffect/Android.mk
@@ -28,5 +28,6 @@
 LOCAL_C_INCLUDES := \
   $(call include-path-for, audio-effects)
 
+LOCAL_CFLAGS := -Wno-unused-parameter
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/selinux/selinuxTargetSdk/Android.mk b/tests/tests/selinux/selinuxTargetSdk/Android.mk
index cfbe04c..fd4aaa3 100755
--- a/tests/tests/selinux/selinuxTargetSdk/Android.mk
+++ b/tests/tests/selinux/selinuxTargetSdk/Android.mk
@@ -19,6 +19,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 LOCAL_COMPATIBILITY_SUITE := cts
 LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner
+LOCAL_JAVA_LIBRARIES := legacy-android-test
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_PACKAGE_NAME := CtsSelinuxTargetSdkTestCases
 LOCAL_SDK_VERSION := current
diff --git a/tests/tests/telecom/Android.mk b/tests/tests/telecom/Android.mk
index 6b12ce8..c81a811 100644
--- a/tests/tests/telecom/Android.mk
+++ b/tests/tests/telecom/Android.mk
@@ -28,7 +28,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_SDK_VERSION := current
+LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
diff --git a/tests/tests/telecom/AndroidManifest.xml b/tests/tests/telecom/AndroidManifest.xml
index 6dcd6ca..f0cad67 100644
--- a/tests/tests/telecom/AndroidManifest.xml
+++ b/tests/tests/telecom/AndroidManifest.xml
@@ -74,6 +74,13 @@
             </intent-filter>
         </receiver>
 
+        <receiver android:name="android.telecom.cts.MockPhoneAccountChangedReceiver">
+            <intent-filter>
+                <action android:name="android.telecom.action.PHONE_ACCOUNT_REGISTERED"/>
+                <action android:name="android.telecom.action.PHONE_ACCOUNT_UNREGISTERED"/>
+            </intent-filter>
+        </receiver>
+
         <activity android:name="android.telecom.cts.MockDialerActivity">
             <intent-filter>
                 <action android:name="android.intent.action.DIAL" />
diff --git a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
index 3a70102..93e4c65 100644
--- a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
+++ b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
@@ -68,6 +68,10 @@
     TestUtils.InvokeCounter mOnConnectionEventCounter;
     TestUtils.InvokeCounter mOnExtrasChangedCounter;
     TestUtils.InvokeCounter mOnPropertiesChangedCounter;
+    TestUtils.InvokeCounter mOnRttModeChangedCounter;
+    TestUtils.InvokeCounter mOnRttStatusChangedCounter;
+    TestUtils.InvokeCounter mOnRttInitiationFailedCounter;
+    TestUtils.InvokeCounter mOnRttRequestCounter;
     Bundle mPreviousExtras;
     int mPreviousProperties = -1;
 
@@ -228,6 +232,27 @@
                 Log.i(TAG, "onSilenceRinger");
                 mOnSilenceRingerCounter.invoke();
             }
+
+            @Override
+            public void onRttModeChanged(Call call, int mode) {
+                mOnRttModeChangedCounter.invoke(call, mode);
+            }
+
+            @Override
+            public void onRttStatusChanged(Call call, boolean enabled, Call.RttCall rttCall) {
+                mOnRttStatusChangedCounter.invoke(call, enabled, rttCall);
+            }
+
+            @Override
+            public void onRttRequest(Call call, int id) {
+                mOnRttRequestCounter.invoke(call, id);
+            }
+
+            @Override
+            public void onRttInitiationFailure(Call call, int reason) {
+                mOnRttInitiationFailedCounter.invoke(call, reason);
+            }
+
         };
 
         MockInCallService.setCallbacks(mInCallCallbacks);
@@ -242,6 +267,11 @@
         mOnConnectionEventCounter = new TestUtils.InvokeCounter("OnConnectionEvent");
         mOnExtrasChangedCounter = new TestUtils.InvokeCounter("OnDetailsChangedCounter");
         mOnPropertiesChangedCounter = new TestUtils.InvokeCounter("OnPropertiesChangedCounter");
+        mOnRttModeChangedCounter = new TestUtils.InvokeCounter("mOnRttModeChangedCounter");
+        mOnRttStatusChangedCounter = new TestUtils.InvokeCounter("mOnRttStatusChangedCounter");
+        mOnRttInitiationFailedCounter =
+                new TestUtils.InvokeCounter("mOnRttInitiationFailedCounter");
+        mOnRttRequestCounter = new TestUtils.InvokeCounter("mOnRttRequestCounter");
     }
 
     /**
diff --git a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
index 1895b0f..0b70f1b 100644
--- a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
@@ -19,6 +19,8 @@
 import static android.telecom.cts.TestUtils.*;
 
 import android.content.ComponentName;
+import android.content.Context;
+import android.media.AudioManager;
 import android.telecom.Call;
 import android.telecom.Connection;
 import android.telecom.ConnectionService;
@@ -27,7 +29,8 @@
 import java.util.Collection;
 
 /**
- * Test some additional {@link ConnectionService} APIs not already covered by other tests.
+ * Test some additional {@link ConnectionService} and {@link Connection} APIs not already covered
+ * by other tests.
  */
 public class ConnectionServiceTest extends BaseTelecomTestWithMockServices {
 
@@ -104,6 +107,23 @@
         assertCallState(call, Call.STATE_DIALING);
     }
 
+    public void testVoipAudioModePropagation() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
+        placeAndVerifyCall();
+        MockConnection connection = verifyConnectionForOutgoingCall();
+        connection.setAudioModeIsVoip(true);
+        waitOnAllHandlers(getInstrumentation());
+
+        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
+        assertEquals(AudioManager.MODE_IN_COMMUNICATION, audioManager.getMode());
+        connection.setAudioModeIsVoip(false);
+        waitOnAllHandlers(getInstrumentation());
+        assertEquals(AudioManager.MODE_IN_CALL, audioManager.getMode());
+    }
+
     public void testGetAllConnections() {
         if (!mShouldTestTelecom) {
             return;
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockConnection.java b/tests/tests/telecom/src/android/telecom/cts/MockConnection.java
index 5183bd4..da4fcf5 100644
--- a/tests/tests/telecom/src/android/telecom/cts/MockConnection.java
+++ b/tests/tests/telecom/src/android/telecom/cts/MockConnection.java
@@ -37,6 +37,9 @@
     public static final int ON_CALL_EVENT = 2;
     public static final int ON_PULL_EXTERNAL_CALL = 3;
     public static final int ON_EXTRAS_CHANGED = 4;
+    public static final int ON_START_RTT = 5;
+    public static final int ON_RTT_REQUEST_RESPONSE = 6;
+    public static final int ON_STOP_RTT = 7;
 
     private CallAudioState mCallAudioState =
             new CallAudioState(false, CallAudioState.ROUTE_EARPIECE, ROUTE_EARPIECE | ROUTE_SPEAKER);
@@ -46,6 +49,7 @@
     private MockVideoProvider mMockVideoProvider;
     private PhoneAccountHandle mPhoneAccountHandle;
     private RemoteConnection mRemoteConnection = null;
+    private RttTextStream mRttTextStream;
 
     private SparseArray<InvokeCounter> mInvokeCounterMap = new SparseArray<>(10);
 
@@ -187,6 +191,36 @@
         }
     }
 
+    @Override
+    public void onStartRtt(RttTextStream rttTextStream) {
+        super.onStartRtt(rttTextStream);
+        if (mInvokeCounterMap.get(ON_START_RTT) != null) {
+            mInvokeCounterMap.get(ON_START_RTT).invoke(rttTextStream);
+        }
+    }
+
+    @Override
+    public void handleRttUpgradeResponse(RttTextStream rttTextStream) {
+        super.handleRttUpgradeResponse(rttTextStream);
+        if (rttTextStream != null) {
+            setRttTextStream(rttTextStream);
+            setConnectionProperties(getConnectionProperties() | PROPERTY_IS_RTT);
+        }
+
+        if (mInvokeCounterMap.get(ON_RTT_REQUEST_RESPONSE) != null) {
+            mInvokeCounterMap.get(ON_RTT_REQUEST_RESPONSE).invoke(rttTextStream);
+        }
+    }
+
+    @Override
+    public void onStopRtt() {
+        super.onStopRtt();
+
+        if (mInvokeCounterMap.get(ON_STOP_RTT) != null) {
+            mInvokeCounterMap.get(ON_STOP_RTT).invoke();
+        }
+    }
+
     public int getCurrentState()  {
         return mState;
     }
@@ -264,6 +298,14 @@
         return mRemoteConnection;
     }
 
+    public void setRttTextStream(RttTextStream rttTextStream) {
+        mRttTextStream = rttTextStream;
+    }
+
+    public RttTextStream getRttTextStream() {
+        return mRttTextStream;
+    }
+
     private static String getCounterLabel(int counterIndex) {
         switch (counterIndex) {
             case ON_POST_DIAL_WAIT:
@@ -274,6 +316,12 @@
                 return "onPullExternalCall";
             case ON_EXTRAS_CHANGED:
                 return "onExtrasChanged";
+            case ON_START_RTT:
+                return "onStartRtt";
+            case ON_RTT_REQUEST_RESPONSE:
+                return "onRttRequestResponse";
+            case ON_STOP_RTT:
+                return "onStopRtt";
             default:
                 return "Callback";
         }
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java b/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java
index 4b9063d..6e022e6 100644
--- a/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/MockConnectionService.java
@@ -65,6 +65,11 @@
         }
         connection.setVideoState(request.getVideoState());
         connection.setInitializing();
+        if (request.isRequestingRtt()) {
+            connection.setRttTextStream(request.getRttTextStream());
+            connection.setConnectionProperties(connection.getConnectionProperties() |
+                    Connection.PROPERTY_IS_RTT);
+        }
 
         outgoingConnections.add(connection);
         lock.release();
@@ -82,6 +87,11 @@
                 | Connection.CAPABILITY_HOLD);
         connection.createMockVideoProvider();
         ((Connection) connection).setVideoState(request.getVideoState());
+        if (request.isRequestingRtt()) {
+            connection.setRttTextStream(request.getRttTextStream());
+            connection.setConnectionProperties(connection.getConnectionProperties() |
+                    Connection.PROPERTY_IS_RTT);
+        }
         connection.setRinging();
 
         incomingConnections.add(connection);
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java b/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
index 4ff3cb6..e13335e 100644
--- a/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
@@ -61,6 +61,10 @@
         public void onCannedTextResponsesLoaded(Call call, List<String> cannedTextResponses) {}
         public void onSilenceRinger() {}
         public void onConnectionEvent(Call call, String event, Bundle extras) {}
+        public void onRttModeChanged(Call call, int mode) {}
+        public void onRttStatusChanged(Call call, boolean enabled, Call.RttCall rttCall) {}
+        public void onRttRequest(Call call, int id) {}
+        public void onRttInitiationFailure(Call call, int reason) {}
 
         final public MockInCallService getService() {
             return mService;
@@ -153,6 +157,38 @@
                 getCallbacks().onConnectionEvent(call, event, extras);
             }
         }
+
+        @Override
+        public void onRttModeChanged(Call call, int mode) {
+            super.onRttModeChanged(call, mode);
+            if (getCallbacks() != null) {
+                getCallbacks().onRttModeChanged(call, mode);
+            }
+        }
+
+        @Override
+        public void onRttStatusChanged(Call call, boolean enabled, Call.RttCall rttCall) {
+            super.onRttStatusChanged(call, enabled, rttCall);
+            if (getCallbacks() != null) {
+                getCallbacks().onRttStatusChanged(call, enabled, rttCall);
+            }
+        }
+
+        @Override
+        public void onRttRequest(Call call, int id) {
+            super.onRttRequest(call, id);
+            if (getCallbacks() != null) {
+                getCallbacks().onRttRequest(call, id);
+            }
+        }
+
+        @Override
+        public void onRttInitiationFailure(Call call, int reason) {
+            super.onRttInitiationFailure(call, reason);
+            if (getCallbacks() != null) {
+                getCallbacks().onRttInitiationFailure(call, reason);
+            }
+        }
     };
 
     private void saveVideoCall(Call call, VideoCall videoCall) {
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockPhoneAccountChangedReceiver.java b/tests/tests/telecom/src/android/telecom/cts/MockPhoneAccountChangedReceiver.java
new file mode 100644
index 0000000..0601d75
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/MockPhoneAccountChangedReceiver.java
@@ -0,0 +1,54 @@
+/*
+ * 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.telecom.cts;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.telecom.PhoneAccountHandle;
+import android.telecom.TelecomManager;
+
+/**
+ * Receives {@link android.telecom.TelecomManager#ACTION_PHONE_ACCOUNT_REGISTERED} and
+ * {@link android.telecom.TelecomManager#ACTION_PHONE_ACCOUNT_UNREGISTERED} intents.
+ */
+public class MockPhoneAccountChangedReceiver extends BroadcastReceiver {
+    public interface IntentListener {
+        void onPhoneAccountRegistered(PhoneAccountHandle handle);
+        void onPhoneAccountUnregistered(PhoneAccountHandle handle);
+    }
+
+    private static IntentListener sIntentListener = null;
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        if (sIntentListener != null) {
+            if (TelecomManager.ACTION_PHONE_ACCOUNT_REGISTERED.equals(intent.getAction())) {
+                sIntentListener.onPhoneAccountRegistered(intent.getParcelableExtra(
+                        TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE));
+            } else if (TelecomManager.ACTION_PHONE_ACCOUNT_UNREGISTERED.equals(
+                    intent.getAction())) {
+                sIntentListener.onPhoneAccountUnregistered(intent.getParcelableExtra(
+                        TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE));
+            }
+        }
+    }
+
+    public static void setIntentListener(IntentListener listener) {
+        sIntentListener = listener;
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/PhoneAccountOperationsTest.java b/tests/tests/telecom/src/android/telecom/cts/PhoneAccountOperationsTest.java
index 4374516..c9b5000 100644
--- a/tests/tests/telecom/src/android/telecom/cts/PhoneAccountOperationsTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/PhoneAccountOperationsTest.java
@@ -43,6 +43,22 @@
     public static final int TEST_LENGTH = 10;
     public static final String TEST_ENCODING = "enUS";
 
+    private TestUtils.InvokeCounter mPhoneAccountRegisteredLatch;
+    private TestUtils.InvokeCounter mPhoneAccountUnRegisteredLatch;
+
+    MockPhoneAccountChangedReceiver.IntentListener mPhoneAccountIntentListener =
+            new MockPhoneAccountChangedReceiver.IntentListener() {
+                @Override
+                public void onPhoneAccountRegistered(PhoneAccountHandle handle) {
+                    mPhoneAccountRegisteredLatch.invoke(handle);
+                }
+
+                @Override
+                public void onPhoneAccountUnregistered(PhoneAccountHandle handle) {
+                    mPhoneAccountUnRegisteredLatch.invoke(handle);
+                }
+            };
+
     private static Bundle createTestBundle() {
         Bundle testBundle = new Bundle();
         testBundle.putInt(PhoneAccount.EXTRA_CALL_SUBJECT_MAX_LENGTH, TEST_LENGTH);
@@ -96,6 +112,8 @@
             return;
         }
         mTelecomManager = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
+        mPhoneAccountRegisteredLatch = new TestUtils.InvokeCounter("registerPhoneAcct");
+        mPhoneAccountUnRegisteredLatch = new TestUtils.InvokeCounter("unRegisterPhoneAcct");
     }
 
     @Override
@@ -225,4 +243,38 @@
         assertTrue("Phone account should support voicemail URI scheme.",
                 retrievedPhoneAccount.supportsUriScheme(PhoneAccount.SCHEME_VOICEMAIL));
     }
+
+    /**
+     * Verifies that the {@link TelecomManager#ACTION_PHONE_ACCOUNT_REGISTERED} intent is sent to
+     * the default dialer when a phone account is registered and,
+     * {@link TelecomManager#ACTION_PHONE_ACCOUNT_UNREGISTERED} is sent when a phone account is
+     * unregistered.
+     * @throws Exception
+     */
+    public void testRegisterUnregisterPhoneAccountIntent() throws Exception {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+
+        MockPhoneAccountChangedReceiver.setIntentListener(mPhoneAccountIntentListener);
+        String previousDefaultDialer = TestUtils.getDefaultDialer(getInstrumentation());
+        try {
+            TestUtils.setDefaultDialer(getInstrumentation(), TestUtils.PACKAGE);
+
+            mTelecomManager.registerPhoneAccount(TEST_NO_SIM_PHONE_ACCOUNT);
+
+            mPhoneAccountRegisteredLatch.waitForCount(1);
+            PhoneAccountHandle handle =
+                    (PhoneAccountHandle) mPhoneAccountRegisteredLatch.getArgs(0)[0];
+            assertEquals(TEST_PHONE_ACCOUNT_HANDLE, handle);
+
+            mTelecomManager.unregisterPhoneAccount(TEST_PHONE_ACCOUNT_HANDLE);
+            mPhoneAccountUnRegisteredLatch.waitForCount(1);
+            PhoneAccountHandle handle2 =
+                    (PhoneAccountHandle) mPhoneAccountUnRegisteredLatch.getArgs(0)[0];
+            assertEquals(TEST_PHONE_ACCOUNT_HANDLE, handle2);
+        } finally {
+            TestUtils.setDefaultDialer(getInstrumentation(), previousDefaultDialer);
+        }
+    }
 }
diff --git a/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java b/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
new file mode 100644
index 0000000..a11079f
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
@@ -0,0 +1,255 @@
+/*
+ * 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.telecom.cts;
+
+import android.os.Bundle;
+import android.telecom.Call;
+import android.telecom.Connection;
+import android.telecom.TelecomManager;
+
+import java.io.IOException;
+
+public class RttOperationsTest extends BaseTelecomTestWithMockServices {
+    private static final int RTT_SEND_TIMEOUT_MILLIS = 1000;
+    private static final String[] TEST_STRINGS = {
+            "A",
+            "AB",
+            "ABCDEFG",
+            "お疲れ様でした",
+            "😂😂😂💯"
+    };
+    private static final int RTT_FAILURE_REASON = 2;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        if (mShouldTestTelecom) {
+            setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE);
+        }
+    }
+
+    public void testOutgoingRttCall() throws Exception {
+        placeRttCall(false);
+        final MockConnection connection = verifyConnectionForOutgoingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        verifyRttEnabled(call, connection);
+    }
+
+    public void testIncomingRttCall() throws Exception {
+        placeRttCall(true);
+        final MockConnection connection = verifyConnectionForIncomingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        verifyRttEnabled(call, connection);
+    }
+
+    public void testLocalRttUpgradeAccepted() throws Exception {
+        placeAndVerifyCall();
+        final MockConnection connection = verifyConnectionForOutgoingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+        verifyRttDisabled(call);
+
+        TestUtils.InvokeCounter startRttCounter =
+                connection.getInvokeCounter(MockConnection.ON_START_RTT);
+        call.sendRttRequest();
+        startRttCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+
+        connection.setRttTextStream((Connection.RttTextStream) startRttCounter.getArgs(0)[0]);
+        connection.sendRttInitiationSuccess();
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        verifyRttEnabled(call, connection);
+    }
+
+    public void testLocalRttUpgradeRejected() throws Exception {
+        placeAndVerifyCall();
+        final MockConnection connection = verifyConnectionForOutgoingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+        verifyRttDisabled(call);
+
+        TestUtils.InvokeCounter startRttCounter =
+                connection.getInvokeCounter(MockConnection.ON_START_RTT);
+        call.sendRttRequest();
+        startRttCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+
+        connection.sendRttInitiationFailure(RTT_FAILURE_REASON);
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        mOnRttInitiationFailedCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        assertEquals(call, mOnRttInitiationFailedCounter.getArgs(0)[0]);
+        assertEquals(RTT_FAILURE_REASON, mOnRttInitiationFailedCounter.getArgs(0)[1]);
+        verifyRttDisabled(call);
+    }
+
+    public void testAcceptRemoteRttUpgrade() throws Exception {
+        placeAndVerifyCall();
+        final MockConnection connection = verifyConnectionForOutgoingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+        verifyRttDisabled(call);
+
+        TestUtils.InvokeCounter rttRequestResponseCounter =
+                connection.getInvokeCounter(MockConnection.ON_RTT_REQUEST_RESPONSE);
+        connection.sendRemoteRttRequest();
+        mOnRttRequestCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        int requestId = (Integer) mOnRttRequestCounter.getArgs(0)[1];
+        call.respondToRttRequest(requestId, true /* accept */);
+
+        rttRequestResponseCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        verifyRttEnabled(call, connection);
+    }
+
+    public void testRejectRemoteRttRequest() throws Exception {
+        placeAndVerifyCall();
+        final MockConnection connection = verifyConnectionForOutgoingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+        verifyRttDisabled(call);
+
+        TestUtils.InvokeCounter rttRequestResponseCounter =
+                connection.getInvokeCounter(MockConnection.ON_RTT_REQUEST_RESPONSE);
+        connection.sendRemoteRttRequest();
+        mOnRttRequestCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        int requestId = (Integer) mOnRttRequestCounter.getArgs(0)[1];
+        call.respondToRttRequest(requestId, false /* accept */);
+
+        rttRequestResponseCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        assertNull(rttRequestResponseCounter.getArgs(0)[0]);
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        verifyRttDisabled(call);
+    }
+
+    public void testLocalRttTermination() throws Exception {
+        placeRttCall(false);
+        final MockConnection connection = verifyConnectionForOutgoingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+
+        // Skipping RTT verification since that's tested by another test
+        TestUtils.InvokeCounter stopRttCounter =
+                connection.getInvokeCounter(MockConnection.ON_STOP_RTT);
+        call.stopRtt();
+        stopRttCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        verifyRttDisabled(call);
+    }
+
+    public void testRemoteRttTermination() throws Exception {
+        placeRttCall(false);
+        final MockConnection connection = verifyConnectionForOutgoingCall();
+        final MockInCallService inCallService = mInCallCallbacks.getService();
+        final Call call = inCallService.getLastCall();
+
+        // Skipping RTT verification since that's tested by another test
+        connection.sendRttSessionRemotelyTerminated();
+        TestUtils.InvokeCounter stopRttCounter =
+                connection.getInvokeCounter(MockConnection.ON_STOP_RTT);
+        call.stopRtt();
+        stopRttCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        TestUtils.waitOnAllHandlers(getInstrumentation());
+        verifyRttDisabled(call);
+    }
+
+    private void verifyRttDisabled(Call call) {
+        TestUtils.waitOnLocalMainLooper(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        assertFalse(call.isRttActive());
+        assertNull(call.getRttCall());
+    }
+
+    private void verifyRttEnabled(Call call, MockConnection connection) {
+        TestUtils.waitOnLocalMainLooper(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        Connection.RttTextStream connectionSideRtt = connection.getRttTextStream();
+        Call.RttCall inCallSideRtt = call.getRttCall();
+        assertNotNull(connectionSideRtt);
+        assertTrue(call.isRttActive());
+        assertNotNull(inCallSideRtt);
+
+        verifyRttPipeIntegrity(inCallSideRtt, connectionSideRtt);
+    }
+
+    private void verifyRttPipeIntegrity(Call.RttCall inCallSide, Connection.RttTextStream
+            connectionSide) {
+        for (String s : TEST_STRINGS) {
+            try {
+                inCallSide.write(s);
+                waitUntilConditionIsTrueOrTimeout(new Condition() {
+                    String readSoFar = "";
+                    @Override
+                    public Object expected() {
+                        return s;
+                    }
+
+                    @Override
+                    public Object actual() {
+                        try {
+                            String newRead = connectionSide.readImmediately();
+                            if (newRead != null) {
+                                readSoFar += newRead;
+                            }
+                            return readSoFar;
+                        } catch (IOException e) {
+                            fail("IOException while reading from connection side");
+                            return null;
+                        }
+                    }
+                }, RTT_SEND_TIMEOUT_MILLIS, String.format("%s failed to send correctly.", s));
+
+                connectionSide.write(s);
+                waitUntilConditionIsTrueOrTimeout(new Condition() {
+                    String readSoFar = "";
+                    @Override
+                    public Object expected() {
+                        return s;
+                    }
+
+                    @Override
+                    public Object actual() {
+                        try {
+                            String newRead = inCallSide.readImmediately();
+                            if (newRead != null) {
+                                readSoFar += newRead;
+                            }
+                            return readSoFar;
+                        } catch (IOException e) {
+                            fail("IOException while reading from incall side");
+                            return null;
+                        }
+                    }
+                }, RTT_SEND_TIMEOUT_MILLIS, String.format("%s failed to send correctly.", s));
+            } catch (IOException e) {
+                fail(String.format(
+                        "Caught IOException when verifying %s", s));
+            }
+
+        }
+    }
+    private void placeRttCall(boolean incoming) {
+        Bundle extras = new Bundle();
+        extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_RTT, true);
+        if (incoming) {
+            addAndVerifyNewIncomingCall(createTestNumber(), extras);
+        } else {
+            Bundle outgoingCallExtras = new Bundle();
+            outgoingCallExtras.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, extras);
+            placeAndVerifyCall(outgoingCallExtras);
+        }
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/TestUtils.java b/tests/tests/telecom/src/android/telecom/cts/TestUtils.java
index eea7284..5c67190 100644
--- a/tests/tests/telecom/src/android/telecom/cts/TestUtils.java
+++ b/tests/tests/telecom/src/android/telecom/cts/TestUtils.java
@@ -25,6 +25,8 @@
 import android.net.Uri;
 import android.os.Build;
 import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.os.SystemClock;
@@ -79,6 +81,7 @@
             .setSubscriptionAddress(Uri.parse("tel:555-TEST"))
             .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
                     PhoneAccount.CAPABILITY_VIDEO_CALLING |
+                    PhoneAccount.CAPABILITY_RTT |
                     PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
             .setHighlightColor(Color.RED)
             .setShortDescription(ACCOUNT_LABEL)
@@ -170,6 +173,19 @@
         executeShellCommand(instrumentation, COMMAND_WAIT_ON_HANDLERS);
     }
 
+    public static void waitOnLocalMainLooper(long timeoutMs) {
+        Handler mainHandler = new Handler(Looper.getMainLooper());
+        final CountDownLatch lock = new CountDownLatch(1);
+        mainHandler.post(lock::countDown);
+        while (lock.getCount() > 0) {
+            try {
+                lock.await(timeoutMs, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                // do nothing
+            }
+        }
+    }
+
     /**
      * Executes the given shell command and returns the output in a string. Note that even
      * if we don't care about the output, we have to read the stream completely to make the
diff --git a/tests/tests/telecom3/Android.mk b/tests/tests/telecom3/Android.mk
index 29bccc3..7400fb5 100644
--- a/tests/tests/telecom3/Android.mk
+++ b/tests/tests/telecom3/Android.mk
@@ -29,8 +29,7 @@
 src_dirs := src \
     ../telecom/src/android/telecom/cts/SelfManagedConnection.java \
     ../telecom/src/android/telecom/cts/CtsSelfManagedConnectionService.java \
-    ../telecom/src/android/telecom/cts/TestUtils.java \
-    ../telecom/src/android/telecom/cts/MockDialerActivity.java
+    ../telecom/src/android/telecom/cts/TestUtils.java
 
 res_dirs := ../telecom/res
 
diff --git a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
index 2dffd4d..a1423af 100644
--- a/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/CellInfoTest.java
@@ -187,9 +187,12 @@
         assertTrue("getLevel() out of range [0,4], level=" + level, level >=0 && level <= 4);
 
         int bsic = gsm.getCellIdentity().getBsic();
-        // TODO(b/32774471) - Bsic should always be valid, so Integer.MAX_VALUE shouldn't be needed
-        assertTrue("getBsic() out of range [0,63]",
-                (bsic >= 0 && bsic <= 63) || bsic == Integer.MAX_VALUE);
+        // TODO(b/32774471) - Bsic should always be valid
+        //assertTrue("getBsic() out of range [0,63]", bsic >=0 && bsic <=63);
+
+        int ta = gsm.getCellSignalStrength().getTimingAdvance();
+        assertTrue("getTimingAdvance() out of range [0,219] | Integer.MAX_VALUE, ta=" + ta,
+                ta == Integer.MAX_VALUE || (ta >= 0 && ta <= 219));
     }
 
     // Rssi(in dbm) should be within [MIN_RSSI, MAX_RSSI].
diff --git a/tests/tests/telephony/src/android/telephony/cts/PhoneNumberUtilsTest.java b/tests/tests/telephony/src/android/telephony/cts/PhoneNumberUtilsTest.java
index 873e496..c8718b6 100644
--- a/tests/tests/telephony/src/android/telephony/cts/PhoneNumberUtilsTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/PhoneNumberUtilsTest.java
@@ -305,31 +305,6 @@
         assertFalse(PhoneNumberUtils.isWellFormedSmsAddress("android"));
     }
 
-    public void testIsUriNumber() {
-        assertTrue(PhoneNumberUtils.isUriNumber("foo@google.com"));
-        assertTrue(PhoneNumberUtils.isUriNumber("xyz@zzz.org"));
-        assertFalse(PhoneNumberUtils.isUriNumber("+15103331245"));
-        assertFalse(PhoneNumberUtils.isUriNumber("+659231235"));
-    }
-
-    public void testGetUsernameFromUriNumber() {
-        assertEquals("john", PhoneNumberUtils.getUsernameFromUriNumber("john@myorg.com"));
-        assertEquals("tim_123", PhoneNumberUtils.getUsernameFromUriNumber("tim_123@zzz.org"));
-        assertEquals("5103331245", PhoneNumberUtils.getUsernameFromUriNumber("5103331245"));
-    }
-
-    public void testConvertAndStrip() {
-        // Untouched number.
-        assertEquals("123456789", PhoneNumberUtils.convertAndStrip("123456789"));
-        // Dashes should be stripped, legal separators (i.e. wild character remain untouched)
-        assertEquals("+15103331245*123", PhoneNumberUtils.convertAndStrip("+1-510-333-1245*123"));
-        // Arabic digits should be converted
-        assertEquals("5567861616", PhoneNumberUtils.convertAndStrip("٥‎٥‎٦‎٧‎٨‎٦‎١‎٦‎١‎٦‎"));
-        // Arabic digits converted and spaces stripped
-        assertEquals("5567861616", PhoneNumberUtils.convertAndStrip("٥‎ ٥‎٦‎ ٧‎ ٨‎ ٦‎ ١‎ ٦‎ ١‎ ٦‎"));
-
-    }
-
     public void testGetPhoneTtsSpan() {
         // Setup: phone number without a country code. Lets keep coverage minimal to avoid
         // exercising the underlying PhoneNumberUtil or constraining localization changes.
diff --git a/tests/tests/uirendering/res/drawable-nodpi/edge_effect_color.png b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_color.png
new file mode 100644
index 0000000..7ca4067
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_color.png
Binary files differ
diff --git a/tests/tests/uirendering/res/drawable-nodpi/edge_effect_displacement_0.png b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_displacement_0.png
new file mode 100644
index 0000000..e315dfd
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_displacement_0.png
Binary files differ
diff --git a/tests/tests/uirendering/res/drawable-nodpi/edge_effect_displacement_1.png b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_displacement_1.png
new file mode 100644
index 0000000..5e719b2
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_displacement_1.png
Binary files differ
diff --git a/tests/tests/uirendering/res/drawable-nodpi/edge_effect_green.png b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_green.png
new file mode 100644
index 0000000..321250b
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_green.png
Binary files differ
diff --git a/tests/tests/uirendering/res/drawable-nodpi/edge_effect_red.png b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_red.png
new file mode 100644
index 0000000..6429808
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_red.png
Binary files differ
diff --git a/tests/tests/uirendering/res/drawable-nodpi/edge_effect_size.png b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_size.png
new file mode 100644
index 0000000..d2af211
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable-nodpi/edge_effect_size.png
Binary files differ
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java
index 25abcbf..a871f49 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java
@@ -34,7 +34,8 @@
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
 import android.uirendering.cts.R;
-import android.uirendering.cts.bitmapverifiers.PerPixelBitmapVerifier;
+import android.uirendering.cts.bitmapcomparers.MSSIMComparer;
+import android.uirendering.cts.bitmapverifiers.GoldenImageVerifier;
 import android.uirendering.cts.testinfrastructure.MaterialActivity;
 import android.uirendering.cts.util.BitmapAsserter;
 import android.widget.EdgeEffect;
@@ -76,76 +77,62 @@
         mBitmapAsserter.setUp(getActivity());
     }
 
-    private static class EdgeEffectValidator extends PerPixelBitmapVerifier {
-        public int matchedColorCount;
-
-        private int mInverseColorMask;
-        private int mColorMask;
-
-        public EdgeEffectValidator(int drawColor) {
-            mColorMask = drawColor & 0x00FFFFFF;
-            mInverseColorMask = ~(drawColor & 0x00FFFFFF);
-        }
-
-        @Override
-        protected boolean verifyPixel(int x, int y, int observedColor) {
-            if ((observedColor & mColorMask) != 0) {
-                matchedColorCount++;
-            }
-            return (observedColor & mInverseColorMask) == 0xFF000000;
-        }
-    }
-
-    private void assertEdgeEffect(EdgeEffectInitializer initializer) {
+    private void assertEdgeEffect(EdgeEffectInitializer initializer, int goldenId) {
         Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
         Canvas canvas = new Canvas(bitmap);
-        canvas.drawColor(Color.BLACK);
+        canvas.drawColor(Color.WHITE);
         EdgeEffect edgeEffect = new EdgeEffect(getActivity());
         edgeEffect.setSize(WIDTH, HEIGHT);
         edgeEffect.setColor(Color.RED);
-        assertEquals(Color.RED, edgeEffect.getColor());
         initializer.initialize(edgeEffect);
         edgeEffect.draw(canvas);
 
-        EdgeEffectValidator verifier = new EdgeEffectValidator(edgeEffect.getColor());
+        GoldenImageVerifier verifier = new GoldenImageVerifier(getActivity(), goldenId,
+                new MSSIMComparer(0.99));
         mBitmapAsserter.assertBitmapIsVerified(bitmap, verifier,
                 name.getMethodName(), "EdgeEffect doesn't match expected");
-        assertTrue(verifier.matchedColorCount > 0);
     }
 
+    //b/63010438
+    @Suppress
     @Test
     public void testOnPull() {
         assertEdgeEffect(edgeEffect -> {
             edgeEffect.onPull(1);
-        });
+        }, R.drawable.edge_effect_red);
     }
 
+    //b/63010438
+    @Suppress
     @Test
     public void testSetSize() {
         assertEdgeEffect(edgeEffect -> {
             edgeEffect.setSize(70, 70);
             edgeEffect.onPull(1);
-        });
+        }, R.drawable.edge_effect_size);
     }
 
+    //b/63010438
+    @Suppress
     @Test
     public void testSetColor() {
         assertEdgeEffect(edgeEffect -> {
             edgeEffect.setColor(Color.GREEN);
-            assertEquals(Color.GREEN, edgeEffect.getColor());
             edgeEffect.onPull(1);
-        });
+        }, R.drawable.edge_effect_green);
     }
 
+    //b/63010438
+    @Suppress
     @Test
     public void testOnPullWithDisplacement() {
         assertEdgeEffect(edgeEffect -> {
             edgeEffect.onPull(1, 0);
-        });
+        }, R.drawable.edge_effect_displacement_0);
 
         assertEdgeEffect(edgeEffect -> {
             edgeEffect.onPull(1, 1);
-        });
+        }, R.drawable.edge_effect_displacement_1);
     }
 
     @Test
diff --git a/tests/tests/view/jni/Android.mk b/tests/tests/view/jni/Android.mk
index 288e250..f1aad68 100644
--- a/tests/tests/view/jni/Android.mk
+++ b/tests/tests/view/jni/Android.mk
@@ -32,6 +32,4 @@
 
 LOCAL_CXX_STL := libc++_static
 
-LOCAL_CLANG := true
-
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/wrap/nowrap/Android.mk b/tests/tests/wrap/nowrap/Android.mk
index 81d315f..877c730 100644
--- a/tests/tests/wrap/nowrap/Android.mk
+++ b/tests/tests/wrap/nowrap/Android.mk
@@ -29,4 +29,7 @@
 LOCAL_PACKAGE_NAME := CtsWrapNoWrapTestCases
 LOCAL_MANIFEST_FILE := AndroidManifest.xml
 
+# Jarjar to make WrapTest unique.
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+
 include $(BUILD_PACKAGE)
diff --git a/tests/tests/wrap/nowrap/jarjar-rules.txt b/tests/tests/wrap/nowrap/jarjar-rules.txt
new file mode 100644
index 0000000..91e7454
--- /dev/null
+++ b/tests/tests/wrap/nowrap/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.wrap.cts.WrapTest** android.wrap.cts.WrapTestNoWrap@1
diff --git a/tests/tests/wrap/wrap_debug/Android.mk b/tests/tests/wrap/wrap_debug/Android.mk
index 2bfb7a5..4fcdbee 100644
--- a/tests/tests/wrap/wrap_debug/Android.mk
+++ b/tests/tests/wrap/wrap_debug/Android.mk
@@ -36,6 +36,9 @@
 LOCAL_PACKAGE_NAME := CtsWrapWrapDebugTestCases
 LOCAL_MANIFEST_FILE := AndroidManifest.xml
 
+# Jarjar to make WrapTest unique.
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+
 include $(BUILD_PACKAGE)
 
 include $(CLEAR_VARS)
diff --git a/tests/tests/wrap/wrap_debug/jarjar-rules.txt b/tests/tests/wrap/wrap_debug/jarjar-rules.txt
new file mode 100644
index 0000000..3020934
--- /dev/null
+++ b/tests/tests/wrap/wrap_debug/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.wrap.cts.WrapTest** android.wrap.cts.WrapTestWrapDebug@1
diff --git a/tests/tests/wrap/wrap_debug_malloc_debug/Android.mk b/tests/tests/wrap/wrap_debug_malloc_debug/Android.mk
new file mode 100644
index 0000000..bc6240d
--- /dev/null
+++ b/tests/tests/wrap/wrap_debug_malloc_debug/Android.mk
@@ -0,0 +1,47 @@
+# 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_MULTILIB := both
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_STATIC_JAVA_LIBRARIES := \
+	compatibility-device-util \
+	android-support-test \
+	legacy-android-test
+LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_SDK_VERSION := current
+
+LOCAL_PREBUILT_JNI_LIBS_arm := wrap.sh
+LOCAL_PREBUILT_JNI_LIBS_arm64 := wrap.sh
+LOCAL_PREBUILT_JNI_LIBS_mips := wrap.sh
+LOCAL_PREBUILT_JNI_LIBS_mips64 := wrap.sh
+LOCAL_PREBUILT_JNI_LIBS_x86 := wrap.sh
+LOCAL_PREBUILT_JNI_LIBS_x86_64 := wrap.sh
+
+LOCAL_PACKAGE_NAME := CtsWrapWrapDebugMallocDebugTestCases
+LOCAL_MANIFEST_FILE := AndroidManifest.xml
+
+# Jarjar to make WrapTest unique.
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+
+include $(BUILD_PACKAGE)
+
+include $(CLEAR_VARS)
diff --git a/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml b/tests/tests/wrap/wrap_debug_malloc_debug/AndroidManifest.xml
similarity index 66%
copy from hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
copy to tests/tests/wrap/wrap_debug_malloc_debug/AndroidManifest.xml
index a0e898a..a359f17 100644
--- a/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
+++ b/tests/tests/wrap/wrap_debug_malloc_debug/AndroidManifest.xml
@@ -16,20 +16,24 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.jvmti.cts.run_test_981">
+    package="android.wrap.wrap_debug_malloc_debug.cts">
 
     <application android:debuggable="true">
         <uses-library android:name="android.test.runner" />
-        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="981" />
-        <activity android:name="android.jvmti.JvmtiActivity" >
+        <meta-data android:name="android.wrap.cts.expext_env" android:value="true" />
+        <activity android:name="android.wrap.WrapActivity" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
         </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_981" >
+        android:label="CTS tests for wrap.sh"
+        android:targetPackage="android.wrap.wrap_debug_malloc_debug.cts" >
     </instrumentation>
 </manifest>
 
diff --git a/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml b/tests/tests/wrap/wrap_debug_malloc_debug/AndroidTest.xml
similarity index 61%
copy from hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
copy to tests/tests/wrap/wrap_debug_malloc_debug/AndroidTest.xml
index e6351d3..0c740e4 100644
--- a/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
+++ b/tests/tests/wrap/wrap_debug_malloc_debug/AndroidTest.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 The Android Open Source Project
+<!-- Copyright (C) 2017 The Android Open Source Project
 
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
@@ -13,15 +13,13 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Config for CTS JVMTI test cases">
+<configuration description="Config for CTS Debug Wrap (Malloc Debug) test cases">
     <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="CtsJvmtiRunTest981DeviceApp.apk" />
+        <option name="test-file-name" value="CtsWrapWrapDebugMallocDebugTestCases.apk" />
     </target_preparer>
-    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
-        <option name="jar" value="CtsJvmtiRunTest981HostTestCases.jar" />
-        <option name="set-option" value="test-file-name:CtsJvmtiRunTest981DeviceApp.apk" />
-        <option name="set-option" value="package-name:android.jvmti.cts.run_test_981" />
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.wrap.wrap_debug_malloc_debug.cts" />
     </test>
 </configuration>
diff --git a/tests/tests/wrap/wrap_debug_malloc_debug/jarjar-rules.txt b/tests/tests/wrap/wrap_debug_malloc_debug/jarjar-rules.txt
new file mode 100644
index 0000000..286029b
--- /dev/null
+++ b/tests/tests/wrap/wrap_debug_malloc_debug/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.wrap.cts.WrapTest** android.wrap.cts.WrapTestDebugMalloc@1
diff --git a/hostsidetests/jvmti/run-tests/test-981/Android.mk b/tests/tests/wrap/wrap_debug_malloc_debug/wrap.sh
old mode 100644
new mode 100755
similarity index 60%
copy from hostsidetests/jvmti/run-tests/test-981/Android.mk
copy to tests/tests/wrap/wrap_debug_malloc_debug/wrap.sh
index 4bbc20a..f00a554
--- a/hostsidetests/jvmti/run-tests/test-981/Android.mk
+++ b/tests/tests/wrap/wrap_debug_malloc_debug/wrap.sh
@@ -1,4 +1,5 @@
-# Copyright (C) 2014 The Android Open Source Project
+#!/system/bin/sh
+# 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.
@@ -11,16 +12,4 @@
 # 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 := CtsJvmtiRunTest981HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
+LIBC_DEBUG_MALLOC_OPTIONS=backtrace=1 WRAP_PROPERTY=test $@
diff --git a/tests/tests/wrap/wrap_nodebug/Android.mk b/tests/tests/wrap/wrap_nodebug/Android.mk
index 799030d..3c0e080 100644
--- a/tests/tests/wrap/wrap_nodebug/Android.mk
+++ b/tests/tests/wrap/wrap_nodebug/Android.mk
@@ -36,6 +36,9 @@
 LOCAL_PACKAGE_NAME := CtsWrapWrapNoDebugTestCases
 LOCAL_MANIFEST_FILE := AndroidManifest.xml
 
+# Jarjar to make WrapTest unique.
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+
 include $(BUILD_PACKAGE)
 
 include $(CLEAR_VARS)
diff --git a/tests/tests/wrap/wrap_nodebug/jarjar-rules.txt b/tests/tests/wrap/wrap_nodebug/jarjar-rules.txt
new file mode 100644
index 0000000..11a43f1
--- /dev/null
+++ b/tests/tests/wrap/wrap_nodebug/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.wrap.cts.WrapTest** android.wrap.cts.WrapTestWrapNoDebug@1
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
index 2b57c76..06aa6fa 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
@@ -19,8 +19,7 @@
 import com.android.compatibility.common.util.CddTest;
 
 import org.jf.dexlib2.DexFileFactory;
-import org.jf.dexlib2.DexFileFactory.DexFileNotFound;
-import org.jf.dexlib2.DexFileFactory.MultipleDexFilesException;
+import org.jf.dexlib2.DexFileFactory.DexFileNotFoundException;
 import org.jf.dexlib2.Opcodes;
 import org.jf.dexlib2.iface.Annotation;
 import org.jf.dexlib2.iface.AnnotationElement;
@@ -44,6 +43,7 @@
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
+import java.util.Locale;
 import java.util.Set;
 
 import javax.xml.transform.TransformerException;
@@ -104,6 +104,8 @@
         String reportTitle = "CTS API Coverage";
         int apiLevel = Integer.MAX_VALUE;
 
+        List<File> notFoundTestApks = new ArrayList<File>();
+        int numTestApkArgs = 0;
         for (int i = 0; i < args.length; i++) {
             if (args[i].startsWith("-")) {
                 if ("-o".equals(args[i])) {
@@ -134,14 +136,23 @@
                 }
             } else {
                 File file = new File(args[i]);
+                numTestApkArgs++;
                 if (file.isDirectory()) {
                     testApks.addAll(Arrays.asList(file.listFiles(SUPPORTED_FILE_NAME_FILTER)));
-                } else {
+                } else if (file.isFile()) {
                     testApks.add(file);
+                } else {
+                    notFoundTestApks.add(file);
                 }
             }
         }
 
+        if (!notFoundTestApks.isEmpty()) {
+            String msg = String.format(Locale.US, "%d/%d testApks not found: %s",
+                    notFoundTestApks.size(), numTestApkArgs, notFoundTestApks);
+            throw new IllegalArgumentException(msg);
+        }
+
         /*
          * 1. Create an ApiCoverage object that is a tree of Java objects representing the API
          *    in current.xml. The object will have no information about the coverage for each
@@ -264,9 +275,8 @@
 
         DexFile dexFile = null;
         try {
-            dexFile = DexFileFactory.loadDexFile(
-                testSource, null /*dexEntry*/, Opcodes.forApi(api));
-        } catch (IOException | DexFileFactory.DexFileNotFound e) {
+            dexFile = DexFileFactory.loadDexFile(testSource, Opcodes.forApi(api));
+        } catch (IOException | DexFileFactory.DexFileNotFoundException e) {
             System.err.println("Unable to load dex file: " + testSource.getPath());
             return;
         }
diff --git a/tools/cts-tradefed/Android.mk b/tools/cts-tradefed/Android.mk
index e278a77..a539e5b 100644
--- a/tools/cts-tradefed/Android.mk
+++ b/tools/cts-tradefed/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_SUITE_TARGET_ARCH := $(TARGET_ARCH)
 LOCAL_SUITE_NAME := CTS
 LOCAL_SUITE_FULLNAME := "Compatibility Test Suite"
-LOCAL_SUITE_VERSION := 8.0_r2
+LOCAL_SUITE_VERSION := 8.0_r1
 
 LOCAL_MODULE := cts-tradefed
 LOCAL_COMPATIBILITY_SUITE := general-tests
diff --git a/tools/cts-tradefed/etc/cts-tradefed b/tools/cts-tradefed/etc/cts-tradefed
index 15249c3..7560b62 100755
--- a/tools/cts-tradefed/etc/cts-tradefed
+++ b/tools/cts-tradefed/etc/cts-tradefed
@@ -36,10 +36,18 @@
 checkPath java
 
 # check java version
-JAVA_VERSION=$(java -version 2>&1 | head -n 2 | grep '[ "]1\.[678][\. "$$]')
-if [ "${JAVA_VERSION}" == "" ]; then
-    echo "Wrong java version. 1.6, 1.7 or 1.8 is required."
-    exit
+if [ "${EXPERIMENTAL_USE_OPENJDK9}" == "" ]; then
+    JAVA_VERSION=$(java -version 2>&1 | head -n 2 | grep '[ "]1\.[678][\. "$$]')
+    if [ "${JAVA_VERSION}" == "" ]; then
+        echo "Wrong java version. 1.6, 1.7 or 1.8 is required."
+        exit
+    fi
+else
+    JAVA_VERSION=$(java -version 2>&1 | head -n 2 | grep '^java .* "9.*')
+    if [ "${JAVA_VERSION}" == "" ]; then
+        echo "Wrong java version. Version 9 is required."
+        exit
+    fi
 fi
 
 # check debug flag and set up remote debugging
@@ -76,7 +84,7 @@
 
 if [ -z ${CTS_ROOT} ]; then
     # assume we're in an extracted cts install
-    CTS_ROOT="$(dirname $0)/../.."
+    CTS_ROOT="$(dirname $(readlink -e $0))/../.."
 fi;
 
 JAR_DIR=${CTS_ROOT}/android-cts/tools
diff --git a/tools/cts-tradefed/res/config/cts-known-failures.xml b/tools/cts-tradefed/res/config/cts-known-failures.xml
index 98b9c62..1d2486f 100644
--- a/tools/cts-tradefed/res/config/cts-known-failures.xml
+++ b/tools/cts-tradefed/res/config/cts-known-failures.xml
@@ -238,7 +238,7 @@
     <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VideoDecoderPerfTest#testVp8Goog0Perf1280x0720" />
 
     <!-- b/63566721 -->
-    <option name="compatibility:exclude-filter" value="CtsWrapWrapDebugTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsWrapWrapDebugTestCases android.wrap.cts.WrapTest" />
 
     <!-- b/38420898 -->
     <option name="compatibility:exclude-filter" value="CtsSensorTestCases android.hardware.cts.SensorDirectReportTest#testRateIndependencyAccelMultiChannel" />
diff --git a/tools/selinux/SELinuxNeverallowTestFrame.py b/tools/selinux/SELinuxNeverallowTestFrame.py
index f84f2ec..20e1ed4 100644
--- a/tools/selinux/SELinuxNeverallowTestFrame.py
+++ b/tools/selinux/SELinuxNeverallowTestFrame.py
@@ -68,10 +68,7 @@
         sepolicyAnalyze = buildHelper.getTestFile("sepolicy-analyze");
         sepolicyAnalyze.setExecutable(true);
 
-        /* obtain sepolicy file from running device */
-        devicePolicyFile = File.createTempFile("sepolicy", ".tmp");
-        devicePolicyFile.deleteOnExit();
-        mDevice.pullFile("/sys/fs/selinux/policy", devicePolicyFile);
+        devicePolicyFile = android.security.cts.SELinuxHostTest.getDevicePolicyFile(mDevice);
     }
 
     private boolean isFullTrebleDevice() throws Exception {
diff --git a/tools/utils/monsoon.py b/tools/utils/monsoon.py
index f3d63c5..d13cf3a 100755
--- a/tools/utils/monsoon.py
+++ b/tools/utils/monsoon.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python2.6
+#!/usr/bin/python
 
 # Copyright (C) 2014 The Android Open Source Project
 #
@@ -23,16 +23,25 @@
 
 Example usages:
   Set the voltage of the device 7536 to 4.0V
-  python2.6 monsoon.py --voltage=4.0 --serialno 7536
+  python monsoon.py --voltage=4.0 --serialno 7536
 
   Get 5000hz data from device number 7536, with unlimited number of samples
-  python2.6 monsoon.py --samples -1 --hz 5000 --serialno 7536
+  python monsoon.py --samples -1 --hz 5000 --serialno 7536
 
   Get 200Hz data for 5 seconds (1000 events) from default device
-  python2.6 monsoon.py --samples 100 --hz 200
+  python monsoon.py --samples 100 --hz 200
 
   Get unlimited 200Hz data from device attached at /dev/ttyACM0
-  python2.6 monsoon.py --samples -1 --hz 200 --device /dev/ttyACM0
+  python monsoon.py --samples -1 --hz 200 --device /dev/ttyACM0
+
+Output columns for collection with --samples, separated by space:
+
+  TIMESTAMP OUTPUT OUTPUT_AVG USB USB_AVG
+   |                |          |   |
+   |                |          |   ` (if --includeusb and --avg)
+   |                |          ` (if --includeusb)
+   |                ` (if --avg)
+   ` (if --timestamp)
 """
 
 import fcntl
@@ -232,13 +241,18 @@
           print >>sys.stderr, "waiting for calibration, dropped data packet"
           continue
 
-        out = []
-        for main, usb, aux, voltage in data:
-          if main & 1:
-            out.append(((main & ~1) - self._coarse_zero) * self._coarse_scale)
+        def scale(val):
+          if val & 1:
+            return ((val & ~1) - self._coarse_zero) * self._coarse_scale
           else:
-            out.append((main - self._fine_zero) * self._fine_scale)
-        return out
+            return (val - self._fine_zero) * self._fine_scale
+
+        out_main = []
+        out_usb = []
+        for main, usb, aux, voltage in data:
+          out_main.append(scale(main))
+          out_usb.append(scale(usb))
+        return (out_main, out_usb)
 
       elif type == 1:
         self._fine_zero = data[0][0]
@@ -317,6 +331,11 @@
     print FLAGS.MainModuleHelp()
     return
 
+  if FLAGS.includeusb:
+    num_channels = 2
+  else:
+    num_channels = 1
+
   if FLAGS.avg and FLAGS.avg < 0:
     print "--avg must be greater than 0"
     return
@@ -359,39 +378,50 @@
     # 'offset' = (consumed samples) * FLAGS.hz - (emitted samples) * native_hz
     # This is the error accumulator in a variation of Bresenham's algorithm.
     emitted = offset = 0
-    collected = []
-    history_deque = collections.deque() # past n samples for rolling average
+    chan_buffers = tuple([] for _ in range(num_channels))
+    # past n samples for rolling average
+    history_deques = tuple(collections.deque() for _ in range(num_channels))
 
     try:
       last_flush = time.time()
       while emitted < FLAGS.samples or FLAGS.samples == -1:
         # The number of raw samples to consume before emitting the next output
         need = (native_hz - offset + FLAGS.hz - 1) / FLAGS.hz
-        if need > len(collected):     # still need more input samples
-          samples = mon.CollectData()
-          if not samples: break
-          collected.extend(samples)
+        if need > len(chan_buffers[0]):     # still need more input samples
+          chans_samples = mon.CollectData()
+          if not all(chans_samples): break
+          for chan_buffer, chan_samples in zip(chan_buffers, chans_samples):
+            chan_buffer.extend(chan_samples)
         else:
           # Have enough data, generate output samples.
           # Adjust for consuming 'need' input samples.
           offset += need * FLAGS.hz
           while offset >= native_hz:  # maybe multiple, if FLAGS.hz > native_hz
-            this_sample = sum(collected[:need]) / need
+            this_sample = [sum(chan[:need]) / need for chan in chan_buffers]
 
             if FLAGS.timestamp: print int(time.time()),
 
             if FLAGS.avg:
-              history_deque.appendleft(this_sample)
-              if len(history_deque) > FLAGS.avg: history_deque.pop()
-              print "%f %f" % (this_sample,
-                               sum(history_deque) / len(history_deque))
+              chan_avgs = []
+              for chan_deque, chan_sample in zip(history_deques, this_sample):
+                chan_deque.appendleft(chan_sample)
+                if len(chan_deque) > FLAGS.avg: chan_deque.pop()
+                chan_avgs.append(sum(chan_deque) / len(chan_deque))
+              # Interleave channel rolling avgs with latest channel data
+              data_to_print = [datum
+                               for pair in zip(this_sample, chan_avgs)
+                               for datum in pair]
             else:
-              print "%f" % this_sample
+              data_to_print = this_sample
+
+            fmt = ' '.join('%f' for _ in data_to_print)
+            print fmt % tuple(data_to_print)
+
             sys.stdout.flush()
 
             offset -= native_hz
             emitted += 1              # adjust for emitting 1 output sample
-          collected = collected[need:]
+          chan_buffers = tuple(c[need:] for c in chan_buffers)
           now = time.time()
           if now - last_flush >= 0.99:  # flush every second
             sys.stdout.flush()
@@ -410,7 +440,9 @@
   flags.DEFINE_float("voltage", None, "Set output voltage (0 for off)")
   flags.DEFINE_float("current", None, "Set max output current")
   flags.DEFINE_string("usbpassthrough", None, "USB control (on, off, auto)")
-  flags.DEFINE_integer("samples", None, "Collect and print this many samples")
+  flags.DEFINE_integer("samples", None,
+                       "Collect and print this many samples. "
+                       "-1 means collect indefinitely.")
   flags.DEFINE_integer("hz", 5000, "Print this many samples/sec")
   flags.DEFINE_string("device", None,
                       "Path to the device in /dev/... (ex:/dev/ttyACM1)")
@@ -418,5 +450,6 @@
   flags.DEFINE_boolean("timestamp", None,
                        "Also print integer (seconds) timestamp on each line")
   flags.DEFINE_boolean("ramp", True, "Gradually increase voltage")
+  flags.DEFINE_boolean("includeusb", False, "Include measurements from USB channel")
 
   main(FLAGS(sys.argv))
diff --git a/tools/vm-tests-tf/Android.mk b/tools/vm-tests-tf/Android.mk
index d5811c3..774711c 100644
--- a/tools/vm-tests-tf/Android.mk
+++ b/tools/vm-tests-tf/Android.mk
@@ -28,7 +28,7 @@
 
 include $(BUILD_JAVA_LIBRARY)
 
-cts-tf-dalvik-lib.jack := $(full_classes_jack)
+cts-tf-dalvik-lib.jar := $(full_classes_jar)
 
 # buildutil java library
 # ============================================================
@@ -55,8 +55,6 @@
 #
 include $(CLEAR_VARS)
 
-include $(BUILD_SYSTEM)/configure_local_jack.mk
-
 LOCAL_MODULE := vm-tests-tf
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 LOCAL_MODULE_SUFFIX := $(COMMON_JAVA_PACKAGE_SUFFIX)
@@ -72,13 +70,10 @@
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
-vmteststf_dep_jars := $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/, cts-tf-dalvik-buildutil.jar dasm.jar dx.jar cfassembler.jar junit-host.jar)
-
-$(LOCAL_BUILT_MODULE): PRIVATE_JACK_EXTRA_ARGS := $(LOCAL_JACK_EXTRA_ARGS)
-
-ifdef LOCAL_JACK_ENABLED
-    vmteststf_dep_jars += $(cts-tf-dalvik-lib.jack)
-endif
+vmteststf_dep_jars := \
+    $(HOST_JDK_TOOLS_JAR) \
+    $(cts-tf-dalvik-lib.jar) \
+    $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/, cts-tf-dalvik-buildutil.jar dasm.jar dx.jar cfassembler.jar junit-host.jar)
 
 $(LOCAL_BUILT_MODULE): PRIVATE_SRC_FOLDER := $(LOCAL_PATH)/src
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_CLASSES := $(call intermediates-dir-for,JAVA_LIBRARIES,cts-tf-dalvik-buildutil,HOST)/classes
@@ -86,49 +81,30 @@
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_DEXCORE_JAR := $(intermediates)/tests/dot/junit/dexcore.jar
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_MAIN_FILES := $(intermediates)/main_files
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES := $(intermediates)/hostjunit_files
-$(LOCAL_BUILT_MODULE): PRIVATE_CLASS_PATH := $(subst $(space),:,$(vmteststf_dep_jars)):$(HOST_JDK_TOOLS_JAR)
-$(LOCAL_BUILT_MODULE): PRIVATE_JACK_VERSION := $(LOCAL_JACK_VERSION)
-ifndef LOCAL_JACK_ENABLED
-$(LOCAL_BUILT_MODULE) : $(vmteststf_dep_jars) $(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar
+$(LOCAL_BUILT_MODULE): PRIVATE_CLASS_PATH := $(call normalize-path-list, $(vmteststf_dep_jars))
+oj_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,core-oj,,COMMON)/classes.jar
+libart_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,core-libart,,COMMON)/classes.jar
+$(LOCAL_BUILT_MODULE): PRIVATE_DALVIK_SUITE_CLASSPATH := $(oj_jar):$(libart_jar):$(cts-tf-dalvik-lib.jar):$(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar:
+$(LOCAL_BUILT_MODULE) : $(vmteststf_dep_jars) $(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar $(DX)
 	$(hide) rm -rf $(dir $@) && mkdir -p $(dir $@)
 	$(hide) mkdir -p $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/dot/junit $(dir $(PRIVATE_INTERMEDIATES_DEXCORE_JAR))
 	# generated and compile the host side junit tests
 	@echo "Write generated Main_*.java files to $(PRIVATE_INTERMEDIATES_MAIN_FILES)"
-	$(hide) java -cp $(PRIVATE_CLASS_PATH) util.build.BuildDalvikSuite $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
-		$(HOST_OUT_JAVA_LIBRARIES)/cts-tf-dalvik-buildutil.jar:$(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar \
-		$(PRIVATE_INTERMEDIATES_MAIN_FILES) $(PRIVATE_INTERMEDIATES_CLASSES) $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES) $$RUN_VM_TESTS_RTO
-	@echo "Generate $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)"
-	$(hide) jar -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar \
-		$(addprefix -C $(PRIVATE_INTERMEDIATES_CLASSES) , dot/junit/DxUtil.class dot/junit/DxAbstractMain.class)
-	$(hide) $(DX) -JXms16M -JXmx768M --dex --output=$(PRIVATE_INTERMEDIATES_DEXCORE_JAR) \
-		$(if $(NO_OPTIMIZE_DX), --no-optimize) $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar && rm -f $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar
-	$(hide) cd $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/classes && zip -q -r ../../$(notdir $@).jar .
-	$(hide) cd $(dir $@) && zip -q -r $(notdir $@) tests
-else # LOCAL_JACK_ENABLED
-oj_jack := $(call intermediates-dir-for,JAVA_LIBRARIES,core-oj,,COMMON)/classes.jack
-libart_jack := $(call intermediates-dir-for,JAVA_LIBRARIES,core-libart,,COMMON)/classes.jack
-$(LOCAL_BUILT_MODULE): PRIVATE_DALVIK_SUITE_CLASSPATH := $(oj_jack):$(libart_jack):$(cts-tf-dalvik-lib.jack):$(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar
-$(LOCAL_BUILT_MODULE) : $(vmteststf_dep_jars) $(JACK) $(oj_jack) $(libart_jack) $(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar | setup-jack-server
-	$(hide) rm -rf $(dir $@) && mkdir -p $(dir $@)
-	$(hide) mkdir -p $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/dot/junit $(dir $(PRIVATE_INTERMEDIATES_DEXCORE_JAR))
-	# generated and compile the host side junit tests
-	@echo "Write generated Main_*.java files to $(PRIVATE_INTERMEDIATES_MAIN_FILES)"
-	$(hide) JACK_VERSION=$(PRIVATE_JACK_VERSION) java -cp $(PRIVATE_CLASS_PATH) util.build.JackBuildDalvikSuite $(JACK) $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
+	$(hide) $(JAVA) \
+	    -cp $(PRIVATE_CLASS_PATH) util.build.BuildDalvikSuite $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
 		$(PRIVATE_DALVIK_SUITE_CLASSPATH) \
 		$(PRIVATE_INTERMEDIATES_MAIN_FILES) $(PRIVATE_INTERMEDIATES_CLASSES) $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES) $$RUN_VM_TESTS_RTO
 	@echo "Generate $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)"
-	$(hide) jar -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar \
-		$(addprefix -C $(PRIVATE_INTERMEDIATES_CLASSES) , dot/junit/DxUtil.class dot/junit/DxAbstractMain.class)
-	$(hide) $(call call-jack) --import $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar --output-jack $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jack
+	$(hide) $(JAR) -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar \
+		$(addprefix -C $(PRIVATE_INTERMEDIATES_CLASSES) , dot/junit/DxUtil.class dot/junit/DxAbstractMain.class dot/junit/AssertionFailedException.class)
 	$(hide) mkdir -p $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).tmp
-	$(hide) $(call call-jack,$(PRIVATE_JACK_EXTRA_ARGS)) --output-dex $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).tmp \
-		$(if $(NO_OPTIMIZE_DX), -D jack.dex.optimize "false") --import $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jack && rm -f $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jack
+	$(hide) $(DX_COMMAND) --dex --output=$(PRIVATE_INTERMEDIATES_DEXCORE_JAR).tmp \
+		$(if $(NO_OPTIMIZE_DX), --no-optimize) $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar && rm -f $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar
 	$(hide) cd $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).tmp && zip -q -r $(abspath $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)) .
 	$(hide) cd $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/classes && zip -q -r ../../$(notdir $@) .
 	$(hide) cd $(dir $@) && zip -q -r $(notdir $@) tests
-oj_jack :=
-libart_jack :=
-endif # LOCAL_JACK_ENABLED
+oj_jar :=
+libart_jar :=
 
 # Clean up temp vars
 intermediates :=
diff --git a/tools/vm-tests-tf/etc/starthosttests b/tools/vm-tests-tf/etc/starthosttests
new file mode 100755
index 0000000..c1144f0
--- /dev/null
+++ b/tools/vm-tests-tf/etc/starthosttests
@@ -0,0 +1,249 @@
+#!/bin/bash
+#
+# Copyright (C) 2008 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.
+
+# Set up prog to be the path of this script, including following symlinks,
+# and set up progdir to be the fully-qualified pathname of its directory.
+
+prog="$0"
+while [ -h "${prog}" ]; do
+    newProg=`/bin/ls -ld "${prog}"`
+    newProg=`expr "${newProg}" : ".* -> \(.*\)$"`
+    if expr "x${newProg}" : 'x/' >/dev/null; then
+        prog="${newProg}"
+    else
+        progdir=`dirname "${prog}"`
+        prog="${progdir}/${newProg}"
+    fi
+done
+oldwd=`pwd`
+progdir=`dirname "${prog}"`
+cd "${progdir}"
+progdir=`pwd`
+prog="${progdir}"/`basename "${prog}"`
+cd "${oldwd}"
+
+javaOpts=""
+while expr "x$1" : 'x-J' >/dev/null; do
+    opt=`expr "$1" : '-J\(.*\)'`
+    javaOpts="${javaOpts} -${opt}"
+    shift
+done
+
+
+#######################################################################
+# Original content of invocation script follows. Uses values cleverly
+# deduced by the above code.
+#######################################################################
+
+selection=$1
+interpreter="fast"
+if [ "$selection" = "--portable" ]; then
+    selection=$2;
+    interpreter="portable"
+fi
+
+dalviktest=$ANDROID_BUILD_TOP/out/host/common/obj/JAVA_LIBRARIES/vm-tests-tf_intermediates
+dalviktestdir=$dalviktest/tests
+dexcore=$dalviktest/tests/dot/junit/dexcore.jar
+scriptdata=$dalviktestdir/data/scriptdata
+report=$dalviktest/report.html
+curdate=`date`
+datadir=/tmp/${USER}
+export ANDROID_PRINTF_LOG=tag
+export ANDROID_LOG_TAGS='*:s' # was: jdwp:i dalvikvm:i dalvikvmi:i'
+export ANDROID_DATA=$datadir
+export ANDROID_ROOT=$ANDROID_HOST_OUT
+# export LD_LIBRARY_PATH=$base/system/lib
+# export DYLD_LIBRARY_PATH=$base/system/lib
+debug_opts="-Xcheck:jni -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
+vmtpath=$ANDROID_HOST_OUT/../common/obj/JAVA_LIBRARIES/vm-tests-tf_intermediates/tests
+
+echo "--------------------------------------------------"
+echo "Dalvik VM Test Suite"
+echo "Version 1.0"
+echo "Copyright (c) 2008 The Android Open Source Project"
+echo ""
+
+if [ "$selection" = "--help" ]; then
+    echo "Usage: vm-tests [--help|--portable] [<mnemonic>]"
+    echo ""
+    echo "    --help      prints this help message"
+    echo ""
+    echo "    <mnemonic>  specifies the instruction to test;"
+    echo "                default is to run all tests"
+    echo ""
+    exit 1;
+fi
+
+rm -rf --preserve-root $datadir/dalvik-cache
+mkdir -p $datadir
+mkdir -p $datadir/dalvik-cache
+
+echo ""
+
+pre_report="<html><head><style>
+table tr.ok { background:#a0ffa0; }
+table tr.nok { background:#ffa0a0; }
+table tr.wok { background:#ffffa0; }
+table tr.lok { background:#aaaaff; }
+</style></head>
+<body>
+<h1>Dalvik VM test suite results</h1>
+Generated $curdate (using the emulator)
+<p>
+<table width='100%'>
+<tr><td>Status</td><td>Target</td><td>Category</td><td>Details</td></tr>"
+post_report="</body></html>"
+
+rm -f $report
+echo $pre_report > $report
+
+# ----------- running each opcode test ------------
+
+export jpassedcnt=0
+export jfailedcnt=0
+export jvfefailedcnt=0
+export jwarningcnt=0
+export jallcnt=0
+export jcolumns=0
+
+function classnameToJar()
+{
+    echo $1 | sed -e 's#\.#/#g;s#$#.jar#'
+}
+
+while read -u 3 myline;
+do
+    # dot.junit.opcodes.add_double.Main_testB1;dot.junit.opcodes.add_double.d.T_add_double_1 ;opcode add_double;test B #1 (border edge case)
+    # ->
+    # mainclass: dot.junit.opcodes.add_double.Main_testB1
+    # testcasedir: opcodes/add_double
+    # testname: testB1 ->
+    # dir dot/junit/opcodes/add_double/testB1
+
+    # e.g dot.junit.opcodes.add_double.Main_testB1
+    mainclass=`echo $myline | cut -d";" -f1`
+    # e.g dot.junit.opcodes.add_double.d.T_add_double_1, space sep. >=1 entries
+    deps=`echo $myline | cut -d";" -f2`
+
+    jtitle=`echo $myline | cut -d";" -f3`
+    jcomment=`echo $myline | cut -d";" -f4`
+    details=`echo $myline | cut -d";" -f5`
+
+    if [ "$selection" == "" ] || [ "$jtitle" == "$selection" ]; then
+
+        (( jallcnt += 1 ))
+
+        cd $dalviktestdir
+        rm -f $datadir/dalvikout
+        # write dalvik output to file
+        echo -n "mk_b:" > $datadir/dalvikout
+
+        classpath="${vmtpath}/dot/junit/dexcore.jar:${vmtpath}/mains.jar"
+        deps=${deps}" "${mainclass}
+        for dep in ${deps}; do
+            depJar=`classnameToJar ${dep}`
+            classpath=${classpath}:${vmtpath}/${depJar}
+        done
+
+        art -Djava.io.tmpdir=/tmp/${USER} \
+            -classpath $classpath $mainclass >> $datadir/dalvikout 2>&1 && \
+             echo -n dvmpassed: >> $datadir/dalvikout 2>&1
+
+        echo -n "mk_s:" >> $datadir/dalvikout
+        # Verify tmpout only contains mkdxc_start;mkdxc_stop -> no system.out/err
+        # because of exception. If ok -> green report line else red report with info
+        # between mkdxc_start and stop
+        vmresult=`cat $datadir/dalvikout`
+
+        if [[ ("$vmresult" == "mk_b:mk_s:") || ("$vmresult" == "mk_b:dvmpassed:mk_s:") ]]; then
+            (( jpassedcnt += 1 ))
+            echo -n "<tr class=\"ok\"><td>Success</td><td>$jtitle</td>" >> $report
+            echo "<td>$jcomment</td><td>$details</td></tr>" >> $report
+            echo -n "."
+        else
+            vmres=`cat $datadir/dalvikout | sed -e 's/mk_b://;s/mk_s://'`
+            vmres="$details<br><pre>$vmres</pre>"
+
+            stacktraces=`echo $vmresult | grep "java\.lang\." | grep -c "at dot\.junit\."`
+            if [[ $stacktraces > 0 ]]; then
+                jtype=`echo "$mainclass" | sed -e 's/.*_test\([^0-9]*\)[0-9].*/\1/' `
+                if [ "$jtype" == "VFE" ]; then
+                    (( jvfefailedcnt += 1 ))
+                    echo -n "V"
+                else
+                    (( jfailedcnt += 1 ))
+                    echo -n "F"
+                fi
+
+                echo "<tr class=\"nok\"><td>Failure</td><td>$jtitle</td><td>" >> $report
+                echo "$jcomment</td><td>$vmres</td></tr>" >> $report
+            else
+                (( jwarningcnt += 1 ))
+                echo "<tr class=\"wok\"><td>Failure</td><td>$jtitle</td><td>" >> $report
+                echo "$jcomment</td><td>(No stacktrace, but errors on console)" >> $report
+                echo "<br>$vmres</td></tr>" >> $report
+                echo -n "C"
+            fi
+        fi
+
+        (( jcolumns += 1 ))
+        if [ ${jcolumns} -eq 40 ]; then
+            echo ""
+            (( jcolumns = 0 ))
+        fi
+
+    fi
+# Use fd nr 3 to avoid subshelling via cat since this looses all
+# variables(and thus also the counters we are interested in).
+done 3<$scriptdata
+
+echo "</table>" >> $report
+let jallcalccnt=$jpassedcnt+$jfailedcnt+$jvfefailedcnt+$jwarningcnt
+if [ $jallcalccnt -ne $jallcnt ]; then
+    echo "<br>error: green & red != total , $jallcalccnt -ne $jallcnt" >> $report
+    exit 1;
+fi
+
+echo $post_report >> $report
+
+echo "<br>Tests run: ${jallcnt}" >> $report
+echo "<br>Functional failures: ${jfailedcnt}" >> $report
+echo "<br>Verifier failures: ${jvfefailedcnt}" >> $report
+echo "<br>Console errors: ${jwarningcnt}" >> $report
+
+echo $post_report >> $report
+
+if [[ jcolumns -ne 0 ]]; then
+    echo ""
+fi
+
+echo ""
+
+if [[ jallcnt -eq jpassedcnt ]]; then
+    echo "OK (${jpassedcnt} tests)"
+else
+    echo "FAILURES!!!"
+    echo ""
+    echo "Tests run          : ${jallcnt}"
+    echo "Functional failures: ${jfailedcnt}"
+    echo "Verifier failures  : ${jvfefailedcnt}"
+    echo "Console errors     : ${jwarningcnt}"
+fi
+
+echo ""
+echo "Please see complete report in ${report}"
+echo "--------------------------------------------------"
diff --git a/tools/vm-tests-tf/src/dot/junit/AssertionFailedException.java b/tools/vm-tests-tf/src/dot/junit/AssertionFailedException.java
new file mode 100644
index 0000000..44b686d
--- /dev/null
+++ b/tools/vm-tests-tf/src/dot/junit/AssertionFailedException.java
@@ -0,0 +1,28 @@
+/*
+ * 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 dot.junit;
+
+class AssertionFailedException extends RuntimeException {
+
+    public AssertionFailedException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public AssertionFailedException(String message) {
+        super(message);
+    }
+}
\ No newline at end of file
diff --git a/tools/vm-tests-tf/src/dot/junit/DxAbstractMain.java b/tools/vm-tests-tf/src/dot/junit/DxAbstractMain.java
index dac6dcf..6223507 100644
--- a/tools/vm-tests-tf/src/dot/junit/DxAbstractMain.java
+++ b/tools/vm-tests-tf/src/dot/junit/DxAbstractMain.java
@@ -25,20 +25,19 @@
     private static void checkError(Class<?> expectedErrorClass, Throwable thrown,
                                    boolean in_invocation_exc) {
         if (expectedErrorClass != null && thrown == null) {
-            fail("Expected error of type " + expectedErrorClass);
+            fail("Expected error of type " + expectedErrorClass, null);
         } else if (expectedErrorClass == null && thrown != null) {
-            fail("Unexpected error " + thrown);
+            fail("Unexpected error " + thrown, thrown);
         } else if (expectedErrorClass != null && thrown != null) {
             if (in_invocation_exc) {
                 if (!(thrown instanceof java.lang.reflect.InvocationTargetException)) {
-                    fail("Expected invocation target exception, but got " + thrown);
+                    fail("Expected invocation target exception, but got " + thrown, thrown);
                 }
                 thrown = thrown.getCause();
             }
             if (!expectedErrorClass.equals(thrown.getClass())) {
-                thrown.printStackTrace(System.err);
                 fail("Expected error of type " + expectedErrorClass + ", but got " +
-                     thrown.getClass());
+                         thrown.getClass(), thrown);
             }
         }
     }
@@ -47,19 +46,19 @@
      * Try to load the class with the given name, and check for the expected error.
      */
     public static Class<?> load(String className, Class<?> expectedErrorClass) {
+        Class<?> c;
         try {
-            Class<?> c = Class.forName(className);
-            checkError(expectedErrorClass, null, false);
-            return c;
+            c = Class.forName(className);
         } catch (Throwable t) {
             if (expectedErrorClass != null) {
                 checkError(expectedErrorClass, t, false);
             } else {
-                t.printStackTrace(System.err);
-                fail("Could not load class " + className + ": " + t);
+                fail("Could not load class " + className, t);
             }
             return null;
         }
+        checkError(expectedErrorClass, null, false);
+        return c;
     }
 
     /**
@@ -80,7 +79,7 @@
             }
         }
         if (method == null) {
-            fail("Could not find method 'run'");
+            fail("Could not find method 'run'", null);
         }
 
         Object receiver = null;
@@ -88,16 +87,17 @@
             try {
                 receiver = c.newInstance();
             } catch (Exception exc) {
-                fail("Could not instantiate " + className + ": " + exc.getMessage());
+                fail("Could not instantiate " + className, exc);
             }
         }
 
         try {
             method.invoke(receiver, args);
-            checkError(expectedErrorClass, null, false);
         } catch (Throwable t) {
             checkError(expectedErrorClass, t, wrapped);
+            return;
         }
+        checkError(expectedErrorClass, null, false);
     }
 
     public static void loadAndRun(String className, Class<?> expectedErrorClass) {
@@ -109,19 +109,26 @@
     }
 
     static public void assertEquals(int expected, int actual) {
-        if (expected != actual) throw new RuntimeException("AssertionFailedError: not equals. Expected " + expected + " actual " + actual);
+        if (expected != actual)
+            throw new AssertionFailedException(
+                    "not equals. Expected " + expected + " actual " + actual);
     }
 
     static public void assertEquals(String message, int expected, int actual) {
-        if (expected != actual) throw new RuntimeException("AssertionFailedError: not equals: " + message + " Expected " + expected + " actual " + actual);
+        if (expected != actual)
+            throw new AssertionFailedException(
+                    "not equals: " + message + " Expected " + expected + " actual " + actual);
     }
 
     static public void assertEquals(long expected, long actual) {
-        if (expected != actual) throw new RuntimeException("AssertionFailedError: not equals. Expected " + expected + " actual " + actual);
+        if (expected != actual)
+            throw new AssertionFailedException(
+                    "not equals. Expected " + expected + " actual " + actual);
     }
 
     static public void assertEquals(double expected, double actual, double delta) {
-        if(!(Math.abs(expected-actual) <= delta)) throw new RuntimeException("AssertionFailedError: not within delta");
+        if (!(Math.abs(expected - actual) <= delta))
+            throw new AssertionFailedException("not within delta");
     }
 
     static public void assertEquals(Object expected, Object actual) {
@@ -129,26 +136,34 @@
             return;
         if (expected != null && expected.equals(actual))
             return;
-        throw new RuntimeException("AssertionFailedError: not the same");
+        throw new AssertionFailedException("not the same: " + expected + " vs " + actual);
     }
 
     static public void assertTrue(boolean condition) {
-        if (!condition) throw new RuntimeException("AssertionFailedError: condition was false");
+        if (!condition)
+            throw new AssertionFailedException("condition was false");
     }
 
     static public void assertFalse(boolean condition) {
-        if (condition) throw new RuntimeException("AssertionFailedError: condition was true");
+        if (condition)
+            throw new AssertionFailedException("condition was true");
     }
 
     static public void assertNotNull(Object object) {
-        if (object == null) throw new RuntimeException("AssertionFailedError: object was null");
+        if (object == null)
+            throw new AssertionFailedException("object was null");
     }
 
     static public void assertNull(Object object) {
-        if (object != null) throw new RuntimeException("AssertionFailedError: object was not null");
+        if (object != null)
+            throw new AssertionFailedException("object was not null");
     }
 
     static public void fail(String message) {
-        throw new RuntimeException("AssertionFailedError msg:"+message);
+        fail(message, null);
+    }
+
+    static public void fail(String message, Throwable cause) {
+        throw new AssertionFailedException(message, cause);
     }
 }
diff --git a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java b/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
index 08b1e5f..dc927d9 100644
--- a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
+++ b/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
@@ -34,6 +34,7 @@
 import java.io.IOException;
 import java.io.OutputStreamWriter;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashSet;
@@ -261,7 +262,7 @@
     }
 
     private void addCTSHostMethod(String pName, String method, MethodData md,
-            Set<String> dependentTestClassNames) {
+            Collection<String> dependentTestClassNames) {
         curJunitFileData += "public void " + method + "() throws Exception {\n";
         final String targetCoreJarPath = String.format("%s/dot/junit/dexcore.jar",
                 TARGET_JAR_ROOT_PATH);
@@ -344,7 +345,7 @@
                 MethodData md = parseTestMethod(pName, classOnlyName, method);
                 String methodContent = md.methodBody;
 
-                Set<String> dependentTestClassNames = parseTestClassName(pName,
+                List<String> dependentTestClassNames = parseTestClassName(pName,
                         classOnlyName, methodContent);
 
                 addCTSHostMethod(pName, method, md, dependentTestClassNames);
@@ -490,7 +491,7 @@
     }
 
     private void generateBuildStepFor(String pName, String method,
-            Set<String> dependentTestClassNames, Set<BuildStep> targets) {
+            Collection<String> dependentTestClassNames, Set<BuildStep> targets) {
 
 
         for (String dependentTestClassName : dependentTestClassNames) {
@@ -640,9 +641,9 @@
      * @param methodSource
      * @return testclass names
      */
-    private Set<String> parseTestClassName(String pName, String classOnlyName,
+    private List<String> parseTestClassName(String pName, String classOnlyName,
             String methodSource) {
-        Set<String> entries = new HashSet<String>();
+        List<String> entries = new ArrayList<String>(2);
         String opcodeName = classOnlyName.substring(5);
 
         Scanner scanner = new Scanner(methodSource);
@@ -673,7 +674,7 @@
         Matcher m = p.matcher(methodSource);
         while (m.find()) {
             String res = m.group(1);
-            entries.add(res.trim());
+            entries.add(0, res.trim());
         }
 
         // search for " load(\"...\" " and add as dependency
diff --git a/tools/vm-tests-tf/src/util/build/JarBuildStep.java b/tools/vm-tests-tf/src/util/build/JarBuildStep.java
index 776e905..7fbe2d5 100644
--- a/tools/vm-tests-tf/src/util/build/JarBuildStep.java
+++ b/tools/vm-tests-tf/src/util/build/JarBuildStep.java
@@ -16,28 +16,36 @@
 
 package util.build;
 
-import sun.tools.jar.Main;
-
+import java.io.BufferedInputStream;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
 
-
+/**
+ * JarBuildStep takes a single input file and embeds it into a (new) jar file as a single entry.
+ */
 public class JarBuildStep extends BuildStep {
 
-    String destFileName;
+    String outputJarEntryName;
     private final boolean deleteInputFileAfterBuild;
 
-    public JarBuildStep(BuildFile inputFile, String destFileName,
-            BuildFile outputFile, boolean deleteInputFileAfterBuild) {
-        super(inputFile, outputFile);
-        this.destFileName = destFileName;
+    public JarBuildStep(BuildFile inputFile, String outputJarEntryName,
+            BuildFile outputJarFile, boolean deleteInputFileAfterBuild) {
+        super(inputFile, outputJarFile);
+        this.outputJarEntryName = outputJarEntryName;
         this.deleteInputFileAfterBuild = deleteInputFileAfterBuild;
     }
 
     @Override
     boolean build() {
         if (super.build()) {
-            File tempFile = new File(inputFile.folder, destFileName);
+            File tempFile = new File(inputFile.folder, outputJarEntryName);
             try {
                 if (!inputFile.fileName.equals(tempFile)) {
                     copyFile(inputFile.fileName, tempFile);
@@ -56,25 +64,53 @@
                         + outDir.getAbsolutePath());
                 return false;
             }
-            String[] arguments = new String[] {
-                    "-cMf", outputFile.fileName.getAbsolutePath(), "-C",
-                    inputFile.folder.getAbsolutePath(), destFileName};
-            Main main = new Main(System.out, System.err, "jar");
-            boolean success = main.run(arguments);
 
-            if (success) {
-                if (tempFile != null) {
-                    tempFile.delete();
-                }
-                if (deleteInputFileAfterBuild) {
-                    inputFile.fileName.delete();
-                }
-            } else {
-                System.err.println("exception in JarBuildStep while calling jar with args:" +
-                        " \"-cMf\", "+outputFile.fileName.getAbsolutePath()+", \"-C\"," + 
-                        inputFile.folder.getAbsolutePath()+", "+ destFileName);
+            // Find the input. We'll need to look into the input folder, but check with the
+            // (relative) destination filename (this is effectively removing the inputFile folder
+            // from the entry path in the jar file).
+            Path absoluteInputPath = Paths.get(inputFile.folder.getAbsolutePath())
+                    .resolve(outputJarEntryName);
+            File absoluteInputFile = absoluteInputPath.toFile();
+            if (!absoluteInputFile.exists()) {
+                // Something went wrong.
+                throw new IllegalArgumentException(absoluteInputFile.getAbsolutePath());
             }
-            return success;
+
+            // Use a JarOutputStream to create the output jar file.
+            File jarOutFile = outputFile.fileName;
+            try (JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(jarOutFile))) {
+                // Create the JAR entry for the file. Use destFileName, and copy the timestamp
+                // from the input.
+                JarEntry entry = new JarEntry(outputJarEntryName);
+                entry.setTime(absoluteInputFile.lastModified());
+
+                // Push the entry. The stream will then be ready to accept content.
+                jarOut.putNextEntry(entry);
+
+                // Copy absoluteInputFile into the jar file.
+                Files.copy(absoluteInputPath, jarOut);
+
+                // Finish the entry.
+                jarOut.closeEntry();
+
+                // (Implicitly close the stream, finishing the jar file.)
+            } catch (Exception e) {
+                System.err.println("exception in JarBuildStep for " +
+                        outputFile.fileName.getAbsolutePath() + ", " + outputJarEntryName);
+                e.printStackTrace(System.err);
+                jarOutFile.delete();
+                return false;
+            }
+
+            // Clean up.
+            if (tempFile != null) {
+                tempFile.delete();
+            }
+            if (deleteInputFileAfterBuild) {
+                inputFile.fileName.delete();
+            }
+
+            return true;
         }
         return false;
     }
@@ -82,7 +118,7 @@
     @Override
     public int hashCode() {
         return inputFile.hashCode() ^ outputFile.hashCode()
-                ^ destFileName.hashCode();
+                ^ outputJarEntryName.hashCode();
     }
 
     @Override
@@ -91,7 +127,7 @@
             JarBuildStep other = (JarBuildStep) obj;
             return inputFile.equals(other.inputFile)
                     && outputFile.equals(other.outputFile)
-                    && destFileName.equals(other.destFileName);
+                    && outputJarEntryName.equals(other.outputJarEntryName);
 
         }
         return false;
diff --git a/tools/vm-tests-tf/src/util/build/JavacBuildStep.java b/tools/vm-tests-tf/src/util/build/JavacBuildStep.java
index a1cde1f..e551989 100644
--- a/tools/vm-tests-tf/src/util/build/JavacBuildStep.java
+++ b/tools/vm-tests-tf/src/util/build/JavacBuildStep.java
@@ -16,12 +16,18 @@
 
 package util.build;
 
-import com.sun.tools.javac.Main;
-
 import java.io.File;
-import java.io.PrintWriter;
+import java.lang.Iterable;
+import java.util.stream.Collectors;
+import java.util.Arrays;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Set;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
 
 public class JavacBuildStep extends SourceBuildStep {
 
@@ -55,23 +61,37 @@
                 System.err.println("failed to create destination dir");
                 return false;
             }
-            int args = 8;
-            String[] commandLine = new String[sourceFiles.size()+args];
-            commandLine[0] = "-classpath";
-            commandLine[1] = classPath;
-            commandLine[2] = "-d";
-            commandLine[3] = destPath;
-            commandLine[4] = "-source";
-            commandLine[5] = "1.7";
-            commandLine[6] = "-target";
-            commandLine[7] = "1.7";
 
-            String[] files = new String[sourceFiles.size()];
-            sourceFiles.toArray(files);
+            Iterable<File> classPathFiles = Arrays.asList(classPath.split(":"))
+                    .stream()
+                    .map(File::new)
+                    .collect(Collectors.toList());
 
-            System.arraycopy(files, 0, commandLine, args, files.length);
+            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+            try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(
+                    null,     // diagnosticListener: we don't care about the details.
+                    null,     // locale: use default locale.
+                    null)) {  // charset: use platform default.
+                fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(
+                        new File(destPath)));
+                fileManager.setLocation(StandardLocation.CLASS_PATH, classPathFiles);
 
-            return Main.compile(commandLine, new PrintWriter(System.err)) == 0;
+                Iterable<? extends JavaFileObject> compilationUnits =
+                        fileManager.getJavaFileObjectsFromStrings(sourceFiles);
+
+                List<String> options = Arrays.asList("-source", "1.7", "-target", "1.7");
+
+                return compiler.getTask(
+                        null,  // out: write errors to System.err.
+                        fileManager,
+                        null,  // diagnosticListener: we don't care about the details.
+                        options,
+                        null,  // classes: classes for annotation processing = none.
+                        compilationUnits).call();
+            } catch (Exception e) {
+                e.printStackTrace();
+                return false;
+            }
         }
         return false;
     }