Merge "add MediaCodecTest with both video and audio encoding" into klp-dev
diff --git a/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java b/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java
index 8a44dfa..40d3cff 100644
--- a/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java
+++ b/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java
@@ -16,21 +16,24 @@
 
 package com.android.cts.appaccessdata;
 
+import java.io.BufferedReader;
+import java.io.DataInputStream;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
+import java.io.FileReader;
 import java.io.IOException;
 
 import android.test.AndroidTestCase;
 
 /**
- * Test that another app's private data cannot be accessed.
+ * Test that another app's private data cannot be accessed, while its public data can.
  *
- * Assumes that {@link APP_WITH_DATA_PKG} has already created the private data.
+ * Assumes that {@link APP_WITH_DATA_PKG} has already created the private and public data.
  */
 public class AccessPrivateDataTest extends AndroidTestCase {
 
     /**
-     * The Android package name of the application that owns the private data
+     * The Android package name of the application that owns the data
      */
     private static final String APP_WITH_DATA_PKG = "com.android.cts.appwithdata";
 
@@ -39,9 +42,15 @@
      * {@link APP_WITH_DATA_PKG}.
      */
     private static final String PRIVATE_FILE_NAME = "private_file.txt";
+    /**
+     * Name of public file to access. This must match the name of the file created by
+     * {@link APP_WITH_DATA_PKG}.
+     */
+    private static final String PUBLIC_FILE_NAME = "public_file.txt";
 
     /**
-     * Tests that another app's private file cannot be accessed
+     * Tests that another app's private data cannot be accessed. It includes file
+     * and detailed traffic stats.
      * @throws IOException
      */
     public void testAccessPrivateData() throws IOException {
@@ -58,5 +67,60 @@
         } catch (SecurityException e) {
             // also valid
         }
+        accessPrivateTrafficStats();
+    }
+
+    /**
+     * Tests that another app's public file can be accessed
+     * @throws IOException
+     */
+    public void testAccessPublicData() throws IOException {
+        try {
+            getOtherAppUid();
+        } catch (FileNotFoundException e) {
+            fail("Was not able to access another app's public file: " + e);
+        } catch (SecurityException e) {
+            fail("Was not able to access another app's public file: " + e);
+        }
+    }
+
+    private int getOtherAppUid() throws IOException, FileNotFoundException, SecurityException {
+        // construct the absolute file path to the other app's public file
+        String publicFilePath = String.format("/data/data/%s/files/%s", APP_WITH_DATA_PKG,
+                PUBLIC_FILE_NAME);
+        DataInputStream inputStream = new DataInputStream(new FileInputStream(publicFilePath));
+        int otherAppUid = (int)inputStream.readInt();
+        inputStream.close();
+        return otherAppUid;
+    }
+
+    private void accessPrivateTrafficStats() throws IOException {
+        int otherAppUid = -1;
+        try {
+            otherAppUid = getOtherAppUid();
+        } catch (FileNotFoundException e) {
+            fail("Was not able to access another app's public file: " + e);
+        } catch (SecurityException e) {
+            fail("Was not able to access another app's public file: " + e);
+        }
+
+        boolean foundOtherStats = false;
+        try {
+            BufferedReader qtaguidReader = new BufferedReader(new FileReader("/proc/net/xt_qtaguid/stats"));
+            String line;
+            while ((line = qtaguidReader.readLine()) != null) {
+                String tokens[] = line.split(" ");
+                if (tokens.length > 3 && tokens[3].equals(String.valueOf(otherAppUid))) {
+                    foundOtherStats = true;
+                    if (!tokens[2].equals("0x0")) {
+                        fail("Other apps detailed traffic stats leaked");
+                    }
+                }
+            }
+            qtaguidReader.close();
+        } catch (FileNotFoundException e) {
+            fail("Was not able to access qtaguid/stats: " + e);
+        }
+        assertTrue("Was expecting to find other apps' traffic stats", foundOtherStats);
     }
 }
diff --git a/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml
index 4b10030..9decbcd 100644
--- a/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml
@@ -22,6 +22,7 @@
     access.
     -->
 
+    <uses-permission android:name="android.permission.INTERNET" />
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
diff --git a/hostsidetests/appsecurity/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java b/hostsidetests/appsecurity/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java
index 1de6464..e11681a 100644
--- a/hostsidetests/appsecurity/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java
+++ b/hostsidetests/appsecurity/test-apps/AppWithData/src/com/android/cts/appwithdata/CreatePrivateDataTest.java
@@ -22,10 +22,23 @@
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
+import android.net.TrafficStats;
 import android.test.AndroidTestCase;
+import android.util.Log;
 
+import java.net.ServerSocket;
+import java.net.Socket;
+
+import java.io.BufferedReader;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
+import java.io.FileReader;
 import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
 
 /**
  * Test that will create private app data.
@@ -36,9 +49,15 @@
 public class CreatePrivateDataTest extends AndroidTestCase {
 
     /**
+     * The Android package name of the application that owns the private data
+     */
+    private static final String APP_WITH_DATA_PKG = "com.android.cts.appwithdata";
+
+    /**
      * Name of private file to create.
      */
     private static final String PRIVATE_FILE_NAME = "private_file.txt";
+    private static final String PUBLIC_FILE_NAME = "public_file.txt";
 
     private static final String PREFERENCES_FILE_NAME = "preferences";
     private static final String PREFERENCE_KEY = "preference_key";
@@ -49,7 +68,8 @@
     static final String DB_VALUE = "test_value";
 
     /**
-     * Creates a file private to this app
+     * Creates the private data for this app, which includes
+     * file, database entries, and traffic stats.
      * @throws IOException if any error occurred when creating the file
      */
     public void testCreatePrivateData() throws IOException {
@@ -59,8 +79,34 @@
         outputStream.close();
         assertTrue(getContext().getFileStreamPath(PRIVATE_FILE_NAME).exists());
 
+        outputStream = getContext().openFileOutput(PUBLIC_FILE_NAME,
+                Context.MODE_WORLD_READABLE);
+        DataOutputStream dataOut = new DataOutputStream(outputStream);
+        dataOut.writeInt(getContext().getApplicationInfo().uid);
+        dataOut.close();
+        outputStream.close();
+        // Ensure that some file will be accessible via the same path that will be used by other app.
+        accessPublicData();
+
         writeToPreferences();
         writeToDatabase();
+        createTrafficStatsWithTags();
+    }
+
+    private void accessPublicData() throws IOException {
+        try {
+            // construct the absolute file path to the app's public's file the same
+            // way as the appaccessdata package will.
+            String publicFilePath = String.format("/data/data/%s/files/%s", APP_WITH_DATA_PKG,
+                    PUBLIC_FILE_NAME);
+            DataInputStream inputStream = new DataInputStream(new FileInputStream(publicFilePath));
+            int otherAppUid = (int)inputStream.readInt();
+            inputStream.close();
+        } catch (FileNotFoundException e) {
+            fail("Was not able to access own public file: " + e);
+        } catch (SecurityException e) {
+            fail("Was not able to access own public file: " + e);
+        }
     }
 
     private void writeToPreferences() {
@@ -127,6 +173,76 @@
         }
     }
 
+    private void accessOwnTrafficStats() throws IOException {
+        final int ownAppUid = getContext().getApplicationInfo().uid;
+
+        boolean foundOwnDetailedStats = false;
+        try {
+            BufferedReader qtaguidReader = new BufferedReader(new FileReader("/proc/net/xt_qtaguid/stats"));
+            String line;
+            while ((line = qtaguidReader.readLine()) != null) {
+                String tokens[] = line.split(" ");
+                if (tokens.length > 3 && tokens[3].equals(String.valueOf(ownAppUid))) {
+                    if (!tokens[2].equals("0x0")) {
+                      foundOwnDetailedStats = true;
+                    }
+                }
+            }
+            qtaguidReader.close();
+        } catch (FileNotFoundException e) {
+            fail("Was not able to access qtaguid/stats: " + e);
+        }
+        assertTrue("Was expecting to find own traffic stats", foundOwnDetailedStats);
+    }
+
+    private void createTrafficStatsWithTags() throws IOException {
+
+        // Transfer 1MB of data across an explicitly localhost socket.
+        final int byteCount = 1024;
+        final int packetCount = 1024;
+
+        final ServerSocket server = new ServerSocket(0);
+        new Thread("CreatePrivateDataTest.createTrafficStatsWithTags") {
+            @Override
+            public void run() {
+                try {
+                    Socket socket = new Socket("localhost", server.getLocalPort());
+                    // Make sure that each write()+flush() turns into a packet:
+                    // disable Nagle.
+                    socket.setTcpNoDelay(true);
+                    OutputStream out = socket.getOutputStream();
+                    byte[] buf = new byte[byteCount];
+                    for (int i = 0; i < packetCount; i++) {
+                        TrafficStats.setThreadStatsTag(i % 10);
+                        TrafficStats.tagSocket(socket);
+                        out.write(buf);
+                        out.flush();
+                    }
+                    out.close();
+                    socket.close();
+                } catch (IOException e) {
+                  assertTrue("io exception" + e, false);
+                }
+            }
+        }.start();
+
+        try {
+            Socket socket = server.accept();
+            InputStream in = socket.getInputStream();
+            byte[] buf = new byte[byteCount];
+            int read = 0;
+            while (read < byteCount * packetCount) {
+                int n = in.read(buf);
+                assertTrue("Unexpected EOF", n > 0);
+                read += n;
+            }
+        } finally {
+            server.close();
+        }
+
+        accessOwnTrafficStats();
+    }
+
     static class TestDatabaseOpenHelper extends SQLiteOpenHelper {
 
         static final String _ID = "_id";
diff --git a/tests/AndroidManifest.xml b/tests/AndroidManifest.xml
index b992482..6851d94 100644
--- a/tests/AndroidManifest.xml
+++ b/tests/AndroidManifest.xml
@@ -98,6 +98,10 @@
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_LOGS" />
 
+    <!-- telephony provider tests -->
+    <uses-permission android:name="android.permission.READ_SMS"/>
+    <uses-permission android:name="android.permission.WRITE_SMS"/>
+
     <!-- content sync tests -->
     <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
     <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
diff --git a/tests/deviceadmin/Android.mk b/tests/deviceadmin/Android.mk
index c354599..bcc23fc 100644
--- a/tests/deviceadmin/Android.mk
+++ b/tests/deviceadmin/Android.mk
@@ -20,7 +20,7 @@
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner
+LOCAL_JAVA_LIBRARIES := android.test.runner guava
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/deviceadmin/src/android/deviceadmin/cts/CtsDeviceAdminActivationTestActivity.java b/tests/deviceadmin/src/android/deviceadmin/cts/CtsDeviceAdminActivationTestActivity.java
index a8c5051..1779ec8 100644
--- a/tests/deviceadmin/src/android/deviceadmin/cts/CtsDeviceAdminActivationTestActivity.java
+++ b/tests/deviceadmin/src/android/deviceadmin/cts/CtsDeviceAdminActivationTestActivity.java
@@ -21,6 +21,8 @@
 import android.os.Bundle;
 import android.view.WindowManager;
 
+import com.google.common.annotations.VisibleForTesting;
+
 /**
  * Helper {@link Activity} for CTS tests of Device Admin activation. The {@code Activity}
  * enables tests to capture the invocations of its {@link #onActivityResult(int, int, Intent)} by
@@ -45,6 +47,7 @@
                 | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
     }
 
+    @VisibleForTesting
     public void setOnActivityResultListener(OnActivityResultListener listener) {
         mOnActivityResultListener = listener;
     }
diff --git a/tests/src/android/renderscript/cts/group1.rs b/tests/src/android/renderscript/cts/group1.rs
new file mode 100644
index 0000000..f1172dc
--- /dev/null
+++ b/tests/src/android/renderscript/cts/group1.rs
@@ -0,0 +1,13 @@
+#pragma version(1)
+#pragma rs java_package_name(android.renderscript.cts)
+
+#include "shared.rsh"
+
+rs_allocation aSharedInt;
+
+uint32_t  __attribute__((kernel)) setSharedInt(uint32_t x) {
+    if (x == 1) {
+        rsSetElementAt_int(aSharedInt, -5, 0);
+    }
+    return x;
+}
diff --git a/tests/src/android/renderscript/cts/group2.rs b/tests/src/android/renderscript/cts/group2.rs
new file mode 100644
index 0000000..f7b62dd
--- /dev/null
+++ b/tests/src/android/renderscript/cts/group2.rs
@@ -0,0 +1,32 @@
+#pragma version(1)
+#pragma rs java_package_name(android.renderscript.cts)
+
+#include "shared.rsh"
+
+rs_allocation aSharedInt;
+rs_allocation aFailed;
+
+static bool failed[2] = { false, false };
+
+void __attribute__((kernel)) getSharedInt(uint32_t in, uint32_t x) {
+    int v = rsGetElementAt_int(aSharedInt, 0);
+    if (in != x) {
+        rsDebug("Failed to read in on iteration: ", x);
+        rsDebug("Read: ", in);
+        failed[x] = true;
+    }
+    if (v != -5) {
+        rsDebug("Failed to read -5 on iteration: ", x);
+        rsDebug("Read: ", v);
+        failed[x] = true;
+    }
+}
+
+// Write out aFailed if either of our kernel instances read old data.
+void verify() {
+    for (int i = 0; i < 2; i++) {
+        if (failed[i]) {
+            rsSetElementAt_int(aFailed, 1, 0);
+        }
+    }
+}
diff --git a/tests/src/android/renderscript/cts/verify.rs b/tests/src/android/renderscript/cts/verify.rs
index 85deb31..3563fee 100644
--- a/tests/src/android/renderscript/cts/verify.rs
+++ b/tests/src/android/renderscript/cts/verify.rs
@@ -16,11 +16,10 @@
 
 #include "shared.rsh"
 
-rs_allocation gIn1;
-rs_allocation gIn2;
-float gAllowedError;
-
+int gAllowedIntError = 0;
 static bool hadError = false;
+static int2 errorLoc = {0,0};
+
 
 static bool compare_float(float f1, float f2) {
     if (fabs(f1-f2) > 0.0001f) {
@@ -30,230 +29,271 @@
     return true;
 }
 
-static void verify_float4(rs_allocation in1, rs_allocation in2)
+static bool verify_float4(rs_allocation in1, rs_allocation in2)
 {
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            float4 p1 = rsGetElementAt_float4(in1, x, y);
-            float4 p2 = rsGetElementAt_float4(in2, x, y);
-            bool e = !compare_float(p1.x, p2.x);
-            e |= !compare_float(p1.y, p2.y);
-            e |= !compare_float(p1.z, p2.z);
-            e |= !compare_float(p1.w, p2.w);
+            float4 pref = rsGetElementAt_float4(in1, x, y);
+            float4 ptst = rsGetElementAt_float4(in2, x, y);
+            bool e = !compare_float(pref.x, ptst.x);
+            e |= !compare_float(pref.y, ptst.y);
+            e |= !compare_float(pref.z, ptst.z);
+            e |= !compare_float(pref.w, ptst.w);
             if (e) {
-                rsDebug("verify_float4 x", x);
-                rsDebug("verify_float4 y", y);
-                rsDebug("verify_float4 p1", p1);
-                rsDebug("verify_float4 p2", p2);
-                return;
+                errorLoc.x = x;
+                errorLoc.y = y;
+                return false;
             }
         }
     }
+    return true;
 }
 
-static void verify_float3(rs_allocation in1, rs_allocation in2)
+static bool verify_float3(rs_allocation in1, rs_allocation in2)
 {
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            float3 p1 = rsGetElementAt_float3(in1, x, y);
-            float3 p2 = rsGetElementAt_float3(in2, x, y);
-            bool e = !compare_float(p1.x, p2.x);
-            e |= !compare_float(p1.y, p2.y);
-            e |= !compare_float(p1.z, p2.z);
+            float3 pref = rsGetElementAt_float3(in1, x, y);
+            float3 ptst = rsGetElementAt_float3(in2, x, y);
+            bool e = !compare_float(pref.x, ptst.x);
+            e |= !compare_float(pref.y, ptst.y);
+            e |= !compare_float(pref.z, ptst.z);
             if (e) {
-                rsDebug("verify_float4 x", x);
-                rsDebug("verify_float4 y", y);
-                rsDebug("verify_float4 p1", p1);
-                rsDebug("verify_float4 p2", p2);
-                return;
+                errorLoc.x = x;
+                errorLoc.y = y;
+                return false;
             }
         }
     }
+    return true;
 }
 
-static void verify_float2(rs_allocation in1, rs_allocation in2)
+static bool verify_float2(rs_allocation in1, rs_allocation in2)
 {
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            float2 p1 = rsGetElementAt_float2(in1, x, y);
-            float2 p2 = rsGetElementAt_float2(in2, x, y);
-            bool e = !compare_float(p1.x, p2.x);
-            e |= !compare_float(p1.y, p2.y);
+            float2 pref = rsGetElementAt_float2(in1, x, y);
+            float2 ptst = rsGetElementAt_float2(in2, x, y);
+            bool e = !compare_float(pref.x, ptst.x);
+            e |= !compare_float(pref.y, ptst.y);
             if (e) {
-                rsDebug("verify_float4 x", x);
-                rsDebug("verify_float4 y", y);
-                rsDebug("verify_float4 p1", p1);
-                rsDebug("verify_float4 p2", p2);
-                return;
+                errorLoc.x = x;
+                errorLoc.y = y;
+                return false;
             }
         }
     }
+    return true;
 }
 
-static void verify_float(rs_allocation in1, rs_allocation in2)
+static bool verify_float(rs_allocation in1, rs_allocation in2)
 {
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            float p1 = rsGetElementAt_float(in1, x, y);
-            float p2 = rsGetElementAt_float(in2, x, y);
-            bool e = !compare_float(p1, p2);
+            float pref = rsGetElementAt_float(in1, x, y);
+            float ptst = rsGetElementAt_float(in2, x, y);
+            bool e = !compare_float(pref, ptst);
             if (e) {
-                rsDebug("verify_float4 x", x);
-                rsDebug("verify_float4 y", y);
-                rsDebug("verify_float4 p1", p1);
-                rsDebug("verify_float4 p2", p2);
-                return;
+                errorLoc.x = x;
+                errorLoc.y = y;
+                return false;
             }
         }
     }
+    return true;
 }
 
-static void verify_uchar4(rs_allocation in1, rs_allocation in2)
+static bool verify_uchar4(rs_allocation in1, rs_allocation in2)
 {
     int merr = 0;
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            int4 p1 = convert_int4(rsGetElementAt_uchar4(in1, x, y));
-            int4 p2 = convert_int4(rsGetElementAt_uchar4(in2, x, y));
-            int4 d = convert_int4(abs(p1 - p2));
+            int4 pref = convert_int4(rsGetElementAt_uchar4(in1, x, y));
+            int4 ptst = convert_int4(rsGetElementAt_uchar4(in2, x, y));
+            int4 d = convert_int4(abs(pref - ptst));
             int e = 0;
             e = max(e, d.x);
             e = max(e, d.y);
             e = max(e, d.z);
             e = max(e, d.w);
-            if (e != 0) {
-                rsDebug("verify_uchar4 x", x);
-                rsDebug("verify_uchar4 y", y);
-                rsDebug("verify_uchar4 p1", p1);
-                rsDebug("verify_uchar4 p2", p2);
-                return;
+            if (e > gAllowedIntError) {
+                errorLoc.x = x;
+                errorLoc.y = y;
+                hadError = true;
+                return false;
             }
             merr = max(e, merr);
         }
     }
+    return true;
 }
 
-static void verify_uchar3(rs_allocation in1, rs_allocation in2)
+static bool verify_uchar3(rs_allocation in1, rs_allocation in2)
 {
     int merr = 0;
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            int3 p1 = convert_int3(rsGetElementAt_uchar3(in1, x, y));
-            int3 p2 = convert_int3(rsGetElementAt_uchar3(in2, x, y));
-            int3 d = convert_int3(abs(p1 - p2));
+            int3 pref = convert_int3(rsGetElementAt_uchar3(in1, x, y));
+            int3 ptst = convert_int3(rsGetElementAt_uchar3(in2, x, y));
+            int3 d = convert_int3(abs(pref - ptst));
             int e = 0;
             e = max(e, d.x);
             e = max(e, d.y);
             e = max(e, d.z);
-            if (e != 0) {
-                rsDebug("verify_uchar3 x", x);
-                rsDebug("verify_uchar3 y", y);
-                rsDebug("verify_uchar3 p1", p1);
-                rsDebug("verify_uchar3 p2", p2);
-                return;
+            if (e > gAllowedIntError) {
+                errorLoc.x = x;
+                errorLoc.y = y;
+                hadError = true;
+                return false;
             }
             merr = max(e, merr);
         }
     }
+    return true;
 }
 
-static void verify_uchar2(rs_allocation in1, rs_allocation in2)
+static bool verify_uchar2(rs_allocation in1, rs_allocation in2)
 {
     int merr = 0;
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            int2 p1 = convert_int2(rsGetElementAt_uchar2(in1, x, y));
-            int2 p2 = convert_int2(rsGetElementAt_uchar2(in2, x, y));
-            int2 d = convert_int2(abs(p1 - p2));
+            int2 pref = convert_int2(rsGetElementAt_uchar2(in1, x, y));
+            int2 ptst = convert_int2(rsGetElementAt_uchar2(in2, x, y));
+            int2 d = convert_int2(abs(pref - ptst));
             int e = 0;
             e = max(e, d.x);
             e = max(e, d.y);
-            if (e != 0) {
-                rsDebug("verify_uchar2 x", x);
-                rsDebug("verify_uchar2 y", y);
-                rsDebug("verify_uchar2 p1", p1);
-                rsDebug("verify_uchar2 p2", p2);
-                return;
+            if (e > gAllowedIntError) {
+                errorLoc.x = x;
+                errorLoc.y = y;
+                hadError = true;
+                return false;
             }
             merr = max(e, merr);
         }
     }
+    return true;
 }
 
-static void verify_uchar(rs_allocation in1, rs_allocation in2)
+static bool verify_uchar(rs_allocation in1, rs_allocation in2)
 {
     int merr = 0;
     uint32_t w = rsAllocationGetDimX(in1);
     uint32_t h = rsAllocationGetDimY(in1);
     for (uint32_t y=0; y < h; y++) {
         for (uint32_t x=0; x < w; x++) {
-            int p1 = rsGetElementAt_uchar(in1, x, y);
-            int p2 = rsGetElementAt_uchar(in2, x, y);
-            int e = abs(p1 - p2);
-            if (e != 0) {
-                rsDebug("verify_uchar4 x", x);
-                rsDebug("verify_uchar4 y", y);
-                rsDebug("verify_uchar4 p1", p1);
-                rsDebug("verify_uchar4 p2", p2);
-                return;
+            int pref = rsGetElementAt_uchar(in1, x, y);
+            int ptst = rsGetElementAt_uchar(in2, x, y);
+            int e = abs(pref - ptst);
+            if (e > gAllowedIntError) {
+                errorLoc.x = x;
+                errorLoc.y = y;
+                hadError = true;
+                return false;
             }
             merr = max(e, merr);
         }
     }
+    return true;
 }
 
-void verify(rs_allocation in1, rs_allocation in2)
+#define printCell(txt, a, xy) \
+{                       \
+    rs_element e = rsAllocationGetElement(a); \
+    rs_data_type dt = rsElementGetDataType(e); \
+    uint32_t vs = rsElementGetVectorSize(e); \
+ \
+    if (dt == RS_TYPE_UNSIGNED_8) { \
+        switch(vs) { \
+        case 4: \
+            rsDebug(txt, rsGetElementAt_uchar4(a, xy.x, xy.y)); \
+            break; \
+        case 3: \
+            rsDebug(txt, rsGetElementAt_uchar3(a, xy.x, xy.y)); \
+            break; \
+        case 2: \
+            rsDebug(txt, rsGetElementAt_uchar2(a, xy.x, xy.y)); \
+            break; \
+        case 1: \
+            rsDebug(txt, rsGetElementAt_uchar(a, xy.x, xy.y)); \
+            break; \
+        } \
+    } else { \
+        switch(vs) { \
+        case 4: \
+            rsDebug(txt, rsGetElementAt_float4(a, xy.x, xy.y)); \
+            break; \
+        case 3: \
+            rsDebug(txt, rsGetElementAt_float3(a, xy.x, xy.y)); \
+            break; \
+        case 2: \
+            rsDebug(txt, rsGetElementAt_float2(a, xy.x, xy.y)); \
+            break; \
+        case 1: \
+            rsDebug(txt, rsGetElementAt_float(a, xy.x, xy.y)); \
+            break; \
+        } \
+    } \
+}
+
+void verify(rs_allocation ref_in, rs_allocation tst_in, rs_allocation src_in)
 {
-    rs_element e = rsAllocationGetElement(in1);
+    rs_element e = rsAllocationGetElement(ref_in);
     rs_data_type dt = rsElementGetDataType(e);
     uint32_t vs = rsElementGetVectorSize(e);
+    bool valid = false;
 
     if (dt == RS_TYPE_UNSIGNED_8) {
         switch(vs) {
         case 4:
-            verify_uchar4(in1, in2);
+            valid = verify_uchar4(ref_in, tst_in);
             break;
         case 3:
-            verify_uchar3(in1, in2);
+            valid = verify_uchar3(ref_in, tst_in);
             break;
         case 2:
-            verify_uchar2(in1, in2);
+            valid = verify_uchar2(ref_in, tst_in);
             break;
         case 1:
-            verify_uchar(in1, in2);
+            valid = verify_uchar(ref_in, tst_in);
             break;
         }
     } else {
         switch(vs) {
         case 4:
-            verify_float4(in1, in2);
+            valid = verify_float4(ref_in, tst_in);
             break;
         case 3:
-            verify_float3(in1, in2);
+            valid = verify_float3(ref_in, tst_in);
             break;
         case 2:
-            verify_float2(in1, in2);
+            valid = verify_float2(ref_in, tst_in);
             break;
         case 1:
-            verify_float(in1, in2);
+            valid = verify_float(ref_in, tst_in);
             break;
         }
     }
-
+    if (!valid) {
+        rsDebug("verify failure at xy", errorLoc);
+        printCell("start value     ", src_in, errorLoc);
+        printCell("reference value ", ref_in, errorLoc);
+        printCell("test value      ", tst_in, errorLoc);
+    }
 }
 
 void checkError()
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
index d51fc72..c981db3 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
@@ -186,6 +186,36 @@
         }
     }
 
+    public void testDecodeRegionInputStreamInBitmap() throws IOException {
+        Options opts = new BitmapFactory.Options();
+        for (int i = 0; i < NUM_TEST_IMAGES; ++i) {
+            for (int j = 0; j < SAMPLESIZES.length; ++j) {
+                for (int k = 0; k < COLOR_CONFIGS.length; ++k) {
+                    opts.inSampleSize = SAMPLESIZES[j];
+                    opts.inPreferredConfig = COLOR_CONFIGS[k];
+                    opts.inBitmap = null;
+
+                    InputStream is1 = obtainInputStream(RES_IDS[i]);
+                    BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is1, false);
+                    InputStream is2 = obtainInputStream(RES_IDS[i]);
+                    Bitmap wholeImage = BitmapFactory.decodeStream(is2, null, opts);
+
+                    // setting inBitmap enables several checks within compareRegionByRegion
+                    opts.inBitmap = Bitmap.createBitmap(
+                            wholeImage.getWidth(), wholeImage.getHeight(), opts.inPreferredConfig);
+
+                    if (RES_IDS[i] == R.drawable.webp_test && COLOR_CONFIGS[k] == Config.RGB_565) {
+                        compareRegionByRegion(decoder, opts, mMseMarginWebPConfigRgb565,
+                                              wholeImage);
+                    } else {
+                        compareRegionByRegion(decoder, opts, mMseMargin, wholeImage);
+                    }
+                    wholeImage.recycle();
+                }
+            }
+        }
+    }
+
     public void testDecodeRegionByteArray() throws IOException {
         Options opts = new BitmapFactory.Options();
         for (int i = 0; i < NUM_TEST_IMAGES; ++i) {
@@ -292,9 +322,18 @@
                 actual = decoder.decodeRegion(rect1, opts);
                 int left = rect1.left / opts.inSampleSize;
                 int top = rect1.top / opts.inSampleSize;
-                Rect rect2 = new Rect(left, top, left + actual.getWidth(),
+                if (opts.inBitmap != null) {
+                    // bitmap reuse path - ensure reuse worked
+                    assertSame(opts.inBitmap, actual);
+                    int currentWidth = rect1.width() / opts.inSampleSize;
+                    int currentHeight = rect1.height() / opts.inSampleSize;
+                    Rect actualRect = new Rect(0, 0, currentWidth, currentHeight);
+                    // crop 'actual' to the size to be tested (and avoid recycling inBitmap)
+                    actual = cropBitmap(actual, actualRect);
+                }
+                Rect expectedRect = new Rect(left, top, left + actual.getWidth(),
                         top + actual.getHeight());
-                expected = cropBitmap(wholeImage, rect2);
+                expected = cropBitmap(wholeImage, expectedRect);
                 compareBitmaps(expected, actual, mseMargin, true);
                 actual.recycle();
                 expected.recycle();
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
index 8509491..e04aea8 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -26,6 +26,7 @@
 import android.hardware.camera2.CaptureResult;
 import android.media.Image;
 import android.media.ImageReader;
+import android.os.Handler;
 import android.os.SystemClock;
 import android.test.AndroidTestCase;
 import android.util.Log;
@@ -45,7 +46,9 @@
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
 
     private CameraManager mCameraManager;
-    private CameraDevice.ErrorListener mMockErrorListener;
+    private CameraDevice.CameraDeviceListener mMockDeviceListener;
+    private CameraTestThread mLooperThread;
+    private Handler mCallbackHandler;
 
     /**
      * The error triggered flag starts out as false, and it will flip to true if any errors
@@ -67,7 +70,6 @@
     private static final int MAX_NUM_IMAGES = 5;
 
     private static int[] mTemplates = new int[] {
-            CameraDevice.TEMPLATE_MANUAL,
             CameraDevice.TEMPLATE_PREVIEW,
             CameraDevice.TEMPLATE_RECORD,
             CameraDevice.TEMPLATE_STILL_CAPTURE,
@@ -86,10 +88,10 @@
         System.setProperty("dexmaker.dexcache", mContext.getCacheDir().toString());
         /**
          * Create errorlistener in context scope, to catch asynchronous device error.
-         * Use spy object here since we want to use the SimpleErrorListener callback
+         * Use spy object here since we want to use the SimpleDeviceListener callback
          * implementation (spy doesn't stub the functions unless we ask it to do so).
          */
-        mMockErrorListener = spy(new SimpleErrorListener());
+        mMockDeviceListener = spy(new SimpleDeviceListener());
     }
 
     @Override
@@ -105,6 +107,8 @@
         mCameraManager = (CameraManager)mContext.getSystemService(Context.CAMERA_SERVICE);
         assertNotNull("Can't connect to camera manager", mCameraManager);
         createDefaultSurface();
+        mLooperThread = new CameraTestThread();
+        mCallbackHandler = mLooperThread.start();
     }
 
     @Override
@@ -117,15 +121,64 @@
     /**
      * This class need to be public because spy need access it.
      */
-    public class SimpleErrorListener implements CameraDevice.ErrorListener {
+    public class SimpleDeviceListener extends CameraDevice.CameraDeviceListener {
+        private final Object mIdleLock = new Object();
+        private boolean mIdle = false;
+
+        public SimpleDeviceListener() {
+
+        }
+
+        // Wait for idle to occur, with a timeout in milliseconds.
+        // A timeout of 0 means indefinite wait
+        public void waitForIdle(long timeout) {
+            synchronized(mIdleLock) {
+                if (!mIdle) {
+                    try {
+                        if (timeout > 0) {
+                            mIdleLock.wait(timeout);
+                        } else {
+                            mIdleLock.wait();
+                        }
+                    } catch (InterruptedException e) {
+                        // Probably fail the idle assert, but needs no other
+                        // action
+                    }
+                    assertTrue("Timeout waiting for camera device idle", mIdle);
+                }
+                mIdle = false;
+            }
+        }
+
+        // Clear idle flag
+        public void clearIdleFlag() {
+            synchronized(mIdleLock) {
+                mIdle = false;
+            }
+        }
+
         @Override
-        public void onCameraDeviceError(CameraDevice camera, int error) {
+        public void onCameraIdle(CameraDevice camera) {
+            synchronized(mIdleLock) {
+                mIdle = true;
+                mIdleLock.notifyAll();
+            }
+        }
+
+        @Override
+        public void onCameraDisconnected(CameraDevice camera) {
+            // Not expecting disconnections
+            mErrorTriggered = true;
+        }
+
+        @Override
+        public void onCameraError(CameraDevice camera, int error) {
             mErrorTriggered = true;
         }
     }
 
-    public void testCameraDeviceCreateCaptureRequest() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+    public void testCameraDeviceCreateCaptureBuilder() throws Exception {
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = null;
             try {
@@ -138,7 +191,7 @@
                  * present.
                  */
                 for (int j = 0; j < mTemplates.length; j++) {
-                    CaptureRequest capReq = camera.createCaptureRequest(mTemplates[j]);
+                    CaptureRequest.Builder capReq = camera.createCaptureRequest(mTemplates[j]);
                     assertNotNull("Failed to create capture request", capReq);
                     assertNotNull("Missing field: SENSOR_EXPOSURE_TIME",
                             capReq.get(CaptureRequest.SENSOR_EXPOSURE_TIME));
@@ -157,7 +210,7 @@
     }
 
     public void testCameraDeviceGetProperties() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = null;
             try {
@@ -182,7 +235,7 @@
     }
 
     public void testCameraDeviceSetErrorListener() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = null;
             try {
@@ -194,10 +247,10 @@
                  * Test: that the error listener can be set without problems.
                  * Also, wait some time to check if device doesn't run into error.
                  */
-                camera.setErrorListener(mMockErrorListener);
+                camera.setDeviceListener(mMockDeviceListener, mCallbackHandler);
                 SystemClock.sleep(ERROR_LISTENER_WAIT_TIMEOUT_MS);
-                verify(mMockErrorListener, never())
-                        .onCameraDeviceError(
+                verify(mMockDeviceListener, never())
+                        .onCameraError(
                                 any(CameraDevice.class),
                                 anyInt());
             }
@@ -227,6 +280,7 @@
 
     private class IsCameraMetadataNotEmpty<T extends CameraMetadata>
             extends ArgumentMatcher<T> {
+        @Override
         public boolean matches(Object obj) {
             /**
              * Do the simple verification here. Only verify the timestamp for now.
@@ -242,14 +296,14 @@
     }
 
     private void runCaptureTest(boolean burst, boolean repeating) throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = null;
             try {
                 camera = mCameraManager.openCamera(ids[i]);
                 assertNotNull(
                         String.format("Failed to open camera device %s", ids[i]), camera);
-                camera.setErrorListener(mMockErrorListener);
+                camera.setDeviceListener(mMockDeviceListener, mCallbackHandler);
 
                 prepareCapture(camera);
 
@@ -280,8 +334,8 @@
                     // Test: burst of 5 shots of different template types
                     captureBurstShot(camera, ids[i], mTemplates, mTemplates.length, repeating);
                 }
-                verify(mMockErrorListener, never())
-                        .onCameraDeviceError(
+                verify(mMockDeviceListener, never())
+                        .onCameraError(
                                 any(CameraDevice.class),
                                 anyInt());
             }
@@ -299,9 +353,9 @@
             int template,
             boolean repeating) throws Exception {
 
-        CaptureRequest request = camera.createCaptureRequest(template);
-        assertNotNull("Failed to create capture request", request);
-        request.addTarget(mSurface);
+        CaptureRequest.Builder requestBuilder = camera.createCaptureRequest(template);
+        assertNotNull("Failed to create capture request", requestBuilder);
+        requestBuilder.addTarget(mSurface);
         CameraDevice.CaptureListener mockCaptureListener =
                 mock(CameraDevice.CaptureListener.class);
 
@@ -310,10 +364,11 @@
                     id, template));
         }
         if (!repeating) {
-            camera.capture(request, mockCaptureListener);
+            camera.capture(requestBuilder.build(), mockCaptureListener, mCallbackHandler);
         }
         else {
-            camera.setRepeatingRequest(request, mockCaptureListener);
+            camera.setRepeatingRequest(requestBuilder.build(), mockCaptureListener,
+                    mCallbackHandler);
         }
 
         int expectedCaptureResultCount = repeating ? REPEATING_CAPTURE_EXPECTED_RESULT_COUNT : 1;
@@ -335,10 +390,10 @@
         assertTrue("Invalid args to capture function", len <= templates.length);
         List<CaptureRequest> requests = new ArrayList<CaptureRequest>();
         for (int i = 0; i < len; i++) {
-            CaptureRequest request = camera.createCaptureRequest(templates[i]);
-            assertNotNull("Failed to create capture request", request);
-            request.addTarget(mSurface);
-            requests.add(request);
+            CaptureRequest.Builder requestBuilder = camera.createCaptureRequest(templates[i]);
+            assertNotNull("Failed to create capture request", requestBuilder);
+            requestBuilder.addTarget(mSurface);
+            requests.add(requestBuilder.build());
         }
         CameraDevice.CaptureListener mockCaptureListener =
                 mock(CameraDevice.CaptureListener.class);
@@ -348,10 +403,10 @@
         }
 
         if (!repeating) {
-            camera.captureBurst(requests, mockCaptureListener);
+            camera.captureBurst(requests, mockCaptureListener, mCallbackHandler);
         }
         else {
-            camera.setRepeatingBurst(requests, mockCaptureListener);
+            camera.setRepeatingBurst(requests, mockCaptureListener, mCallbackHandler);
         }
         int expectedResultCount = len;
         if (repeating) {
@@ -386,7 +441,7 @@
     }
 
     private void createDefaultSurface() throws Exception {
-        ImageReader mReader =
+        mReader =
                 new ImageReader(DEFAULT_CAPTURE_WIDTH,
                         DEFAULT_CAPTURE_HEIGHT,
                         ImageFormat.YUV_420_888,
@@ -394,7 +449,7 @@
         mSurface = mReader.getSurface();
         // Create dummy image listener since we don't care the image data in this test.
         ImageReader.OnImageAvailableListener listener = new ImageDropperListener();
-        CameraTestThread mDummyThread = new CameraTestThread();
+        mDummyThread = new CameraTestThread();
         mReader.setImageAvailableListener(listener, mDummyThread.start());
     }
 
@@ -404,9 +459,9 @@
         // Should receive expected number of capture results.
         verify(mockListener,
                 timeout(CAPTURE_WAIT_TIMEOUT_MS).atLeast(expectResultCount))
-                        .onCaptureComplete(
+                        .onCaptureCompleted(
                                 any(CameraDevice.class),
-                                argThat(new IsCameraMetadataNotEmpty<CaptureRequest>()),
+                                any(CaptureRequest.class),
                                 argThat(new IsCameraMetadataNotEmpty<CaptureResult>()));
         // Should not receive any capture failed callbacks.
         verify(mockListener, never())
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraManagerTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraManagerTest.java
index 52f44f1..c2e0d0f 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraManagerTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraManagerTest.java
@@ -22,6 +22,7 @@
 import android.hardware.camera2.CameraDevice;
 import android.hardware.camera2.CameraManager;
 import android.hardware.camera2.CameraProperties;
+import android.os.Handler;
 import android.test.AndroidTestCase;
 import android.util.Log;
 
@@ -62,8 +63,8 @@
 
     public void testCameraManagerGetDeviceIdList() throws Exception {
 
-        // Test: that the getDeviceIdList method runs without exceptions.
-        String[] ids = mCameraManager.getDeviceIdList();
+        // Test: that the getCameraIdList method runs without exceptions.
+        String[] ids = mCameraManager.getCameraIdList();
         if (VERBOSE) Log.v(TAG, "CameraManager ids: " + Arrays.toString(ids));
 
         // Test: that if the device has a camera, there must be at least one reported id.
@@ -95,7 +96,7 @@
 
     // Test: that properties can be queried from each device, without exceptions.
     public void testCameraManagerGetCameraProperties() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull(
@@ -113,7 +114,7 @@
 
     // Test: that an exception is thrown if an invalid device id is passed down.
     public void testCameraManagerInvalidDevice() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         // Create an invalid id by concatenating all the valid ids together.
         StringBuilder invalidId = new StringBuilder();
         invalidId.append("INVALID");
@@ -132,7 +133,7 @@
 
     // Test: that each camera device can be opened one at a time, several times.
     public void testCameraManagerOpenCamerasSerially() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             for (int j = 0; j < NUM_CAMERA_REOPENS; j++) {
                 CameraDevice camera = mCameraManager.openCamera(ids[i]);
@@ -148,7 +149,7 @@
      * exception is thrown if this can't be done.
      */
     public void testCameraManagerOpenAllCameras() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         CameraDevice[] cameras = new CameraDevice[ids.length];
         try {
             for (int i = 0; i < ids.length; i++) {
@@ -185,7 +186,7 @@
 
     // Test: that opening the same device multiple times throws the right exception.
     public void testCameraManagerOpenCameraTwice() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         CameraDevice[] cameras = new CameraDevice[2];
         if (ids.length > 0) {
             try {
@@ -218,7 +219,7 @@
         }
     }
 
-    private class NoopCameraListener implements CameraManager.CameraListener {
+    private class NoopCameraListener extends CameraManager.AvailabilityListener {
         @Override
         public void onCameraAvailable(String cameraId) {
             // No-op
@@ -237,11 +238,13 @@
      * a listener that isn't registered should have no effect.
      */
     public void testCameraManagerListener() throws Exception {
-        mCameraManager.unregisterCameraListener(mListener);
-        mCameraManager.registerCameraListener(mListener);
-        mCameraManager.registerCameraListener(mListener);
-        mCameraManager.unregisterCameraListener(mListener);
-        mCameraManager.unregisterCameraListener(mListener);
+        CameraTestThread callbackThread = new CameraTestThread();
+        Handler callbackHandler = callbackThread.start();
+
+        mCameraManager.removeAvailabilityListener(mListener);
+        mCameraManager.addAvailabilityListener(mListener, callbackHandler);
+        mCameraManager.addAvailabilityListener(mListener, callbackHandler);
+        mCameraManager.removeAvailabilityListener(mListener);
+        mCameraManager.removeAvailabilityListener(mListener);
     }
 }
-
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraPropertiesTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraPropertiesTest.java
index 501d5aa..a5576d9 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraPropertiesTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraPropertiesTest.java
@@ -54,7 +54,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAeAvailableAntibandingModes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -73,7 +73,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAeAvailableTargetFpsRanges() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -92,7 +92,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAeCompensationRange() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -111,7 +111,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAeCompensationStep() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -130,7 +130,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAfAvailableModes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -149,7 +149,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAvailableEffects() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -168,7 +168,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAvailableSceneModes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -187,7 +187,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAvailableVideoStabilizationModes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -206,7 +206,7 @@
     }
 
     public void testCameraPropertiesAndroidControlAwbAvailableModes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -225,7 +225,7 @@
     }
 
     public void testCameraPropertiesAndroidControlMaxRegions() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -244,7 +244,7 @@
     }
 
     public void testCameraPropertiesAndroidFlashInfoAvailable() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -263,7 +263,7 @@
     }
 
     public void testCameraPropertiesAndroidJpegAvailableThumbnailSizes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -282,7 +282,7 @@
     }
 
     public void testCameraPropertiesAndroidLensFacing() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -301,7 +301,7 @@
     }
 
     public void testCameraPropertiesAndroidLensInfoAvailableApertures() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -320,7 +320,7 @@
     }
 
     public void testCameraPropertiesAndroidLensInfoAvailableFilterDensities() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -339,7 +339,7 @@
     }
 
     public void testCameraPropertiesAndroidLensInfoAvailableFocalLengths() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -358,7 +358,7 @@
     }
 
     public void testCameraPropertiesAndroidLensInfoAvailableOpticalStabilization() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -377,7 +377,7 @@
     }
 
     public void testCameraPropertiesAndroidLensInfoHyperfocalDistance() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -396,7 +396,7 @@
     }
 
     public void testCameraPropertiesAndroidLensInfoMinimumFocusDistance() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -415,7 +415,7 @@
     }
 
     public void testCameraPropertiesAndroidLensInfoShadingMapSize() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -434,7 +434,7 @@
     }
 
     public void testCameraPropertiesAndroidRequestMaxNumOutputStreams() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -453,7 +453,7 @@
     }
 
     public void testCameraPropertiesAndroidScalerAvailableFormats() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -472,7 +472,7 @@
     }
 
     public void testCameraPropertiesAndroidScalerAvailableJpegMinDurations() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -491,7 +491,7 @@
     }
 
     public void testCameraPropertiesAndroidScalerAvailableJpegSizes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -510,7 +510,7 @@
     }
 
     public void testCameraPropertiesAndroidScalerAvailableMaxDigitalZoom() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -529,7 +529,7 @@
     }
 
     public void testCameraPropertiesAndroidScalerAvailableProcessedMinDurations() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -548,7 +548,7 @@
     }
 
     public void testCameraPropertiesAndroidScalerAvailableProcessedSizes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -567,7 +567,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorBaseGainFactor() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -586,7 +586,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorMaxAnalogSensitivity() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -605,7 +605,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorOrientation() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -624,7 +624,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorInfoActiveArraySize() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -643,7 +643,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorInfoSensitivityRange() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -662,7 +662,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorInfoExposureTimeRange() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -681,7 +681,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorInfoMaxFrameDuration() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -700,7 +700,7 @@
     }
 
     public void testCameraPropertiesAndroidSensorInfoPhysicalSize() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -719,7 +719,7 @@
     }
 
     public void testCameraPropertiesAndroidStatisticsInfoAvailableFaceDetectModes() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -738,7 +738,7 @@
     }
 
     public void testCameraPropertiesAndroidStatisticsInfoMaxFaceCount() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -757,7 +757,7 @@
     }
 
     public void testCameraPropertiesAndroidTonemapMaxCurvePoints() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
@@ -776,7 +776,7 @@
     }
 
     public void testCameraPropertiesAndroidInfoSupportedHardwareLevel() throws Exception {
-        String[] ids = mCameraManager.getDeviceIdList();
+        String[] ids = mCameraManager.getCameraIdList();
         for (int i = 0; i < ids.length; i++) {
             CameraDevice camera = mCameraManager.openCamera(ids[i]);
             assertNotNull("Failed to open camera", camera);
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/ImageReaderTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/ImageReaderTest.java
index d5fad86..3ba9815 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/ImageReaderTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/ImageReaderTest.java
@@ -79,7 +79,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        mCameraIds = mCameraManager.getDeviceIdList();
+        mCameraIds = mCameraManager.getCameraIdList();
         mLooperThread = new CameraTestThread();
         mHandler = mLooperThread.start();
     }
@@ -220,11 +220,12 @@
         outputSurfaces.add(surface);
         mCamera.configureOutputs(outputSurfaces);
 
-        CaptureRequest captureRequest = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
-        assertNotNull("Fail to get captureRequest", captureRequest);
-        captureRequest.addTarget(mReader.getSurface());
+        CaptureRequest.Builder captureBuilder =
+                mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
+        assertNotNull("Fail to get captureRequest", captureBuilder);
+        captureBuilder.addTarget(mReader.getSurface());
 
-        return captureRequest;
+        return captureBuilder.build();
     }
 
     private void captureAndValidateImage(CaptureRequest request,
@@ -235,9 +236,9 @@
         // Only verify single image for still capture
         if (format == ImageFormat.JPEG) {
             captureCount = 1;
-            mCamera.capture(request, null);
+            mCamera.capture(request, null, null);
         } else {
-            mCamera.setRepeatingRequest(request, null);
+            mCamera.setRepeatingRequest(request, null, null);
         }
 
         for (int i = 0; i < captureCount; i++) {
diff --git a/tests/tests/keystore/Android.mk b/tests/tests/keystore/Android.mk
index 62c3301..f2dae38 100644
--- a/tests/tests/keystore/Android.mk
+++ b/tests/tests/keystore/Android.mk
@@ -20,7 +20,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner core-tests-support
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/keystore/AndroidManifest.xml b/tests/tests/keystore/AndroidManifest.xml
index a19c983..0ce9f09 100644
--- a/tests/tests/keystore/AndroidManifest.xml
+++ b/tests/tests/keystore/AndroidManifest.xml
@@ -19,6 +19,7 @@
     package="com.android.cts.keystore">
 
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+    <uses-permission android:name="android.permission.INTERNET" />
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
diff --git a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyPairGeneratorTest.java b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyPairGeneratorTest.java
index 2512aba..39373e3 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyPairGeneratorTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyPairGeneratorTest.java
@@ -20,9 +20,12 @@
 import android.test.AndroidTestCase;
 
 import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.Socket;
 import java.security.KeyPair;
 import java.security.KeyPairGenerator;
 import java.security.KeyStore;
+import java.security.Principal;
 import java.security.PrivateKey;
 import java.security.PublicKey;
 import java.security.SecureRandom;
@@ -37,9 +40,23 @@
 import java.security.spec.RSAKeyGenParameterSpec;
 import java.text.SimpleDateFormat;
 import java.util.Date;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
 
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509ExtendedKeyManager;
 import javax.security.auth.x500.X500Principal;
 
+import libcore.java.security.TestKeyStore;
+import libcore.javax.net.ssl.TestKeyManager;
+import libcore.javax.net.ssl.TestSSLContext;
+
 public class AndroidKeyPairGeneratorTest extends AndroidTestCase {
     private KeyPairGenerator mGenerator;
 
@@ -452,6 +469,92 @@
         Certificate[] chain = privEntry.getCertificateChain();
         assertEquals("A list of CA certificates should not exist for the generated entry", 1,
                 chain.length);
+
+        assertUsableInSSLConnection(privKey, x509userCert);
+    }
+
+    private static void assertUsableInSSLConnection(final PrivateKey privKey,
+            final X509Certificate x509userCert) throws Exception {
+        // TODO this should probably be in something like:
+        // TestKeyStore.createForClientSelfSigned(...)
+        String provider = SSLContext.getDefault().getProvider().getName();
+        TrustManager[] clientTrustManagers = TestKeyStore.createTrustManagers(
+                TestKeyStore.getIntermediateCa().keyStore);
+        SSLContext clientContext = TestSSLContext.createSSLContext("TLS", provider,
+                new KeyManager[] {
+                    TestKeyManager.wrap(new MyKeyManager(privKey, x509userCert))
+                }, clientTrustManagers);
+        TestKeyStore serverKeyStore = TestKeyStore.getServer();
+        serverKeyStore.keyStore.setCertificateEntry("client-selfSigned", x509userCert);
+        SSLContext serverContext = TestSSLContext.createSSLContext("TLS", provider,
+                serverKeyStore.keyManagers,
+                TestKeyStore.createTrustManagers(serverKeyStore.keyStore));
+        SSLServerSocket serverSocket = (SSLServerSocket) serverContext.getServerSocketFactory()
+                .createServerSocket(0);
+        InetAddress host = InetAddress.getLocalHost();
+        int port = serverSocket.getLocalPort();
+
+        SSLSocket client = (SSLSocket) clientContext.getSocketFactory().createSocket(host, port);
+        final SSLSocket server = (SSLSocket) serverSocket.accept();
+        ExecutorService executor = Executors.newSingleThreadExecutor();
+        Future<Void> future = executor.submit(new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                server.setNeedClientAuth(true);
+                server.setWantClientAuth(true);
+                server.startHandshake();
+                return null;
+            }
+        });
+        executor.shutdown();
+        client.startHandshake();
+        Certificate[] usedClientCerts = client.getSession().getLocalCertificates();
+        assertNotNull(usedClientCerts);
+        assertEquals(1, usedClientCerts.length);
+        assertEquals(x509userCert, usedClientCerts[0]);
+        future.get();
+        client.close();
+        server.close();
+    }
+
+    private static class MyKeyManager extends X509ExtendedKeyManager {
+        private final PrivateKey key;
+        private final X509Certificate[] chain;
+
+        public MyKeyManager(PrivateKey key, X509Certificate cert) {
+            this.key = key;
+            this.chain = new X509Certificate[] { cert };
+        }
+
+        @Override
+        public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
+            return "fake";
+        }
+
+        @Override
+        public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
+            throw new UnsupportedOperationException("Not implemented");
+        }
+
+        @Override
+        public X509Certificate[] getCertificateChain(String alias) {
+            return chain;
+        }
+
+        @Override
+        public String[] getClientAliases(String keyType, Principal[] issuers) {
+            return new String[] { "fake" };
+        }
+
+        @Override
+        public String[] getServerAliases(String keyType, Principal[] issuers) {
+            throw new UnsupportedOperationException("Not implemented");
+        }
+
+        @Override
+        public PrivateKey getPrivateKey(String alias) {
+            return key;
+        }
     }
 
     private static void assertDateEquals(String message, Date date1, Date date2) throws Exception {
diff --git a/tests/tests/location/src/android/location/cts/LocationManagerTest.java b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
index 5e823bc..2a2274c 100644
--- a/tests/tests/location/src/android/location/cts/LocationManagerTest.java
+++ b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
@@ -660,6 +660,13 @@
         // update location to outside proximity range
         updateLocationAndWait(FUSED_PROVIDER_NAME, 30, 30);
         registerProximityListener(0, 0, 1000, expiration);
+
+        // Adding geofences is asynchronous, the return of LocationManager.addProximityAlert
+        // doesn't mean that geofences are already being monitored. Wait for a few milliseconds
+        // so that GeofenceManager is actively monitoring locations before we send the mock
+        // location to avoid flaky tests.
+        Thread.sleep(500);
+
         updateLocationAndWait(FUSED_PROVIDER_NAME, 0, 0);
         waitForReceiveBroadcast();
         assertProximityType(true);
diff --git a/tests/tests/media/Android.mk b/tests/tests/media/Android.mk
index c116162..f7639a4 100644
--- a/tests/tests/media/Android.mk
+++ b/tests/tests/media/Android.mk
@@ -28,9 +28,6 @@
 
 LOCAL_PACKAGE_NAME := CtsMediaTestCases
 
-LOCAL_JNI_SHARED_LIBRARIES := libmockdrmcryptoplugin
-
-
 # uncomment when dalvik.annotation.Test* are removed or part of SDK
 #LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java b/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java
index c4a171e..0d83647 100644
--- a/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java
+++ b/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java
@@ -88,7 +88,7 @@
 
 
     public void testVideoEditQCIF() throws Throwable {
-        setParameters(176, 144, 1000000);
+        setParameters(176, 144, 1100000);
         VideoEditWrapper.runTest(this);
     }
     public void testVideoEditQVGA() throws Throwable {
diff --git a/tests/tests/media/src/android/media/cts/DecoderTest.java b/tests/tests/media/src/android/media/cts/DecoderTest.java
index ca5f31c..d251064 100644
--- a/tests/tests/media/src/android/media/cts/DecoderTest.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTest.java
@@ -21,6 +21,7 @@
 import android.content.res.AssetFileDescriptor;
 import android.content.res.Resources;
 import android.media.MediaCodec;
+import android.media.MediaCodecInfo;
 import android.media.MediaExtractor;
 import android.media.MediaFormat;
 import android.util.Log;
@@ -103,7 +104,6 @@
         short [] mono = decodeToMemory(res, false);
         if (mono.length == 44100) {
             // expected
-            return;
         } else if (mono.length == 88200) {
             // the decoder output 2 channels instead of 1, check that the left and right channel
             // are identical
@@ -116,7 +116,7 @@
 
         // we should get the same data when reconfiguring the codec
         short [] mono2 = decodeToMemory(res, true);
-        Arrays.equals(mono, mono2);
+        assertTrue(Arrays.equals(mono, mono2));
     }
 
     /**
@@ -705,6 +705,7 @@
         boolean sawOutputEOS = false;
         int deadDecoderCounter = 0;
         int samplenum = 0;
+        boolean dochecksum = false;
         while (!sawOutputEOS && deadDecoderCounter < 100) {
             if (!sawInputEOS) {
                 int inputBufIndex = codec.dequeueInputBuffer(kTimeOutUs);
@@ -758,7 +759,7 @@
                         numframes += info.size;
                     } else {
                         // for video, count the number of video frames
-                        long sum = checksum(codecOutputBuffers[res], info.size);
+                        long sum = dochecksum ? checksum(codecOutputBuffers[res], info.size) : 0;
                         if (numframes < checksums.length) {
                             checksums[numframes] = sum;
                         }
@@ -781,7 +782,8 @@
                 Log.d(TAG, "output buffers have changed.");
             } else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                 MediaFormat oformat = codec.getOutputFormat();
-
+                int colorFormat = oformat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
+                dochecksum = isRecognizedFormat(colorFormat);
                 Log.d(TAG, "output format has changed to " + oformat);
             } else {
                 Log.d(TAG, "no output");
@@ -816,6 +818,7 @@
         deadDecoderCounter = 0;
         samplenum = 0;
         numframes = 0;
+        dochecksum = false;
         while (!sawOutputEOS && deadDecoderCounter < 100) {
             if (!sawInputEOS) {
                 int inputBufIndex = codec.dequeueInputBuffer(kTimeOutUs);
@@ -869,7 +872,7 @@
                         numframes += info.size;
                     } else {
                         // for video, count the number of video frames
-                        long sum = checksum(codecOutputBuffers[res], info.size);
+                        long sum = dochecksum ? checksum(codecOutputBuffers[res], info.size) : 0;
                         if (numframes < checksums.length) {
                             assertEquals("frame data mismatch at frame " + numframes,
                                     checksums[numframes], sum);
@@ -893,7 +896,8 @@
                 Log.d(TAG, "output buffers have changed.");
             } else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                 MediaFormat oformat = codec.getOutputFormat();
-
+                int colorFormat = oformat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
+                dochecksum = isRecognizedFormat(colorFormat);
                 Log.d(TAG, "output format has changed to " + oformat);
             } else {
                 Log.d(TAG, "no output");
@@ -911,6 +915,21 @@
         testFd.close();
     }
 
+    /* from EncodeDecodeTest */
+    private static boolean isRecognizedFormat(int colorFormat) {
+        switch (colorFormat) {
+            // these are the formats we know how to handle for this test
+            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
+            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar:
+            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
+            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar:
+            case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar:
+                return true;
+            default:
+                return false;
+        }
+    }
+
     private long checksum(ByteBuffer buf, int size) {
         assertTrue(size != 0);
         assertTrue(size <= buf.capacity());
diff --git a/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java
new file mode 100644
index 0000000..197b437
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java
@@ -0,0 +1,952 @@
+/*
+ * Copyright (C) 2013 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.media.cts;
+
+
+import android.app.Presentation;
+import android.content.Context;
+import android.graphics.SurfaceTexture;
+import android.graphics.Typeface;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.VirtualDisplay;
+import android.media.MediaCodec;
+import android.media.MediaCodecInfo;
+import android.media.MediaCodecInfo.CodecCapabilities;
+import android.media.MediaCodecInfo.CodecProfileLevel;
+import android.media.MediaCodecList;
+import android.media.MediaFormat;
+import android.opengl.GLES11Ext;
+import android.opengl.GLES20;
+import android.opengl.Matrix;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.test.AndroidTestCase;
+import android.util.Log;
+import android.view.Display;
+import android.view.Surface;
+import android.view.WindowManager;
+import android.widget.TextView;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Tests to check if MediaCodec encoding works with composition of multiple virtual displays
+ * The test also tries to destroy and create virtual displays repeatedly to
+ * detect any issues. The test itself does not check the output as it is already done in other
+ * tests.
+ */
+public class EncodeVirtualDisplayWithCompositionTest extends AndroidTestCase {
+    private static final String TAG = "EncodeVirtualDisplayWithCompositionTest";
+    private static final boolean DBG = false;
+    private static final String MIME_TYPE = "video/avc";
+    private Handler mHandler;
+    private Surface mSurface;
+    private CodecInfo mCodecInfo;
+    private volatile boolean mCodecConfigReceived = false;
+    private volatile boolean mCodecBufferReceived = false;
+    private EncoderEventListener mEncoderEventListener = new EncoderEventListener() {
+        @Override
+        public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info) {
+            mCodecConfigReceived = true;
+        }
+        @Override
+        public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info) {
+            mCodecBufferReceived = true;
+        }
+        @Override
+        public void onError(String errorMessage) {
+            fail(errorMessage);
+        }
+    };
+
+    @Override
+    protected void setUp() {
+        mHandler = new Handler(Looper.getMainLooper());
+        mCodecInfo = getAvcSupportedFormatInfo();
+    }
+
+    public void testSingleVirtualDisplay() throws Exception {
+        doTestVirtualDisplays(1);
+    }
+
+    public void testMultipleVirtualDisplays() throws Exception {
+        doTestVirtualDisplays(3);
+    }
+
+    void doTestVirtualDisplays(int numDisplays) throws Exception {
+        final int NUM_CODEC_CREATION = 10;
+        final int NUM_DISPLAY_CREATION = 20;
+        final int NUM_RENDERING = 10;
+        VirtualDisplayPresentation[] virtualDisplays = new VirtualDisplayPresentation[numDisplays];
+        for (int i = 0; i < NUM_CODEC_CREATION; i++) {
+            mCodecConfigReceived = false;
+            mCodecBufferReceived = false;
+            if (DBG) {
+                Log.i(TAG, "start encoding");
+            }
+            EncodingHelper encodingHelper = new EncodingHelper();
+            mSurface = encodingHelper.startEncoding(mCodecInfo, mEncoderEventListener);
+            GlCompositor compositor = new GlCompositor();
+            if (DBG) {
+                Log.i(TAG, "start composition");
+            }
+            compositor.startComposition(mSurface, mCodecInfo.mMaxW, mCodecInfo.mMaxH,
+                    numDisplays);
+            for (int j = 0; j < NUM_DISPLAY_CREATION; j++) {
+                if (DBG) {
+                    Log.i(TAG, "create display");
+                }
+                for (int k = 0; k < numDisplays; k++) {
+                    virtualDisplays[k] =
+                        new VirtualDisplayPresentation(getContext(),
+                                compositor.getWindowSurface(k),
+                                mCodecInfo.mMaxW/numDisplays, mCodecInfo.mMaxH,
+                                VirtualDisplayPresentation.RENDERING_VIEW_HIERARCHY);
+                    virtualDisplays[k].createVirtualDisplay();
+                    virtualDisplays[k].createPresentation();
+                }
+                if (DBG) {
+                    Log.i(TAG, "start rendering");
+                }
+                for (int k = 0; k < NUM_RENDERING; k++) {
+                    for (int l = 0; l < numDisplays; l++) {
+                        virtualDisplays[l].doRendering();
+                    }
+                    // do not care how many frames are actually rendered.
+                    Thread.sleep(1);
+                }
+                for (int k = 0; k < numDisplays; k++) {
+                    virtualDisplays[k].dismissPresentation();
+                    virtualDisplays[k].destroyVirtualDisplay();
+                }
+                compositor.recreateWindows();
+            }
+            if (DBG) {
+                Log.i(TAG, "stop composition");
+            }
+            compositor.stopComposition();
+            if (DBG) {
+                Log.i(TAG, "stop encoding");
+            }
+            encodingHelper.stopEncoding();
+            assertTrue(mCodecConfigReceived);
+            assertTrue(mCodecBufferReceived);
+        }
+    }
+
+    interface EncoderEventListener {
+        public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info);
+        public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info);
+        public void onError(String errorMessage);
+    }
+
+    private class EncodingHelper {
+        private MediaCodec mEncoder;
+        private volatile boolean mStopEncoding = false;
+        private EncoderEventListener mEventListener;
+        private CodecInfo mCodecInfo;
+        private Thread mEncodingThread;
+        private Surface mSurface;
+        private static final int IFRAME_INTERVAL = 10;
+        private Semaphore mInitCompleted = new Semaphore(0);
+
+        Surface startEncoding(CodecInfo codecInfo, EncoderEventListener eventListener) {
+            mCodecInfo = codecInfo;
+            mEventListener = eventListener;
+            mEncodingThread = new Thread(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        doEncoding();
+                    } catch (Exception e) {
+                        mEventListener.onError(e.toString());
+                    }
+                }
+            });
+            mEncodingThread.start();
+            try {
+                if (DBG) {
+                    Log.i(TAG, "wait for encoder init");
+                }
+                mInitCompleted.acquire();
+                if (DBG) {
+                    Log.i(TAG, "wait for encoder done");
+                }
+            } catch (InterruptedException e) {
+                fail("should not happen");
+            }
+            return mSurface;
+        }
+
+        void stopEncoding() {
+            try {
+                mStopEncoding = true;
+                mEncodingThread.join();
+            } catch(InterruptedException e) {
+                // just ignore
+            } finally {
+                mEncodingThread = null;
+            }
+        }
+
+        private void doEncoding() throws Exception {
+            final int TIMEOUT_USEC_NORMAL = 1000000;
+            MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mCodecInfo.mMaxW,
+                    mCodecInfo.mMaxH);
+            format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+                    MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
+            format.setInteger(MediaFormat.KEY_BIT_RATE, mCodecInfo.mBitRate);
+            format.setInteger(MediaFormat.KEY_FRAME_RATE, mCodecInfo.mFps);
+            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
+            // Create a MediaCodec for the desired codec, then configure it as an encoder with
+            // our desired properties.  Request a Surface to use for input.
+            mEncoder = MediaCodec.createByCodecName(mCodecInfo.mCodecName);
+            mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
+            mSurface = mEncoder.createInputSurface();
+            mEncoder.start();
+            mInitCompleted.release();
+            try {
+                ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers();
+                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
+                boolean stopEncoding = false;
+                while (!stopEncoding) {
+                    if (mStopEncoding) {
+                        mEncoder.signalEndOfInputStream();
+                        mStopEncoding = false; // reset to prevent sending EOS again
+                    }
+                    int index = mEncoder.dequeueOutputBuffer(info, TIMEOUT_USEC_NORMAL);
+                    if (index >= 0) {
+                        if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
+                            Log.i(TAG, "codec config data");
+                            ByteBuffer encodedData = encoderOutputBuffers[index];
+                            encodedData.position(info.offset);
+                            encodedData.limit(info.offset + info.size);
+                            mEventListener.onCodecConfig(encodedData, info);
+                            mEncoder.releaseOutputBuffer(index, false);
+                        } else if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
+                            stopEncoding = true;
+                        } else {
+                            ByteBuffer encodedData = encoderOutputBuffers[index];
+                            encodedData.position(info.offset);
+                            encodedData.limit(info.offset + info.size);
+                            mEventListener.onBufferReady(encodedData, info);
+                            mEncoder.releaseOutputBuffer(index, false);
+                        }
+                    }
+                }
+            } finally {
+                mEncoder.stop();
+                mEncoder.release();
+                mEncoder = null;
+            }
+        }
+    }
+
+    /**
+     * Handles composition of multiple SurfaceTexture into a single Surface
+     */
+    private class GlCompositor implements SurfaceTexture.OnFrameAvailableListener {
+        private Surface mSurface;
+        private int mWidth;
+        private int mHeight;
+        private int mNumWindows;
+        private ArrayList<GlWindow> mWindows = new ArrayList<GlWindow>();
+        private HashMap<SurfaceTexture, GlWindow> mSurfaceTextureToWindowMap =
+                new HashMap<SurfaceTexture, GlWindow>();
+        private Thread mCompositionThread;
+        private Semaphore mStartCompletionSemaphore;
+        private Semaphore mRecreationCompletionSemaphore;
+        private Looper mLooper;
+        private Handler mHandler;
+        private InputSurface mEglHelper;
+        private int mGlProgramId = 0;
+        private int mGluMVPMatrixHandle;
+        private int mGluSTMatrixHandle;
+        private int mGlaPositionHandle;
+        private int mGlaTextureHandle;
+        private float[] mMVPMatrix = new float[16];
+
+        private static final String VERTEX_SHADER =
+                "uniform mat4 uMVPMatrix;\n" +
+                "uniform mat4 uSTMatrix;\n" +
+                "attribute vec4 aPosition;\n" +
+                "attribute vec4 aTextureCoord;\n" +
+                "varying vec2 vTextureCoord;\n" +
+                "void main() {\n" +
+                "  gl_Position = uMVPMatrix * aPosition;\n" +
+                "  vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
+                "}\n";
+
+        private static final String FRAGMENT_SHADER =
+                "#extension GL_OES_EGL_image_external : require\n" +
+                "precision mediump float;\n" +
+                "varying vec2 vTextureCoord;\n" +
+                "uniform samplerExternalOES sTexture;\n" +
+                "void main() {\n" +
+                "  gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
+                "}\n";
+
+        void startComposition(Surface surface, int w, int h, int numWindows) {
+            mSurface = surface;
+            mWidth = w;
+            mHeight = h;
+            mNumWindows = numWindows;
+            mCompositionThread = new Thread(new CompositionRunnable());
+            mStartCompletionSemaphore = new Semaphore(0);
+            mCompositionThread.start();
+            waitForStartCompletion();
+        }
+
+        void stopComposition() {
+            try {
+                if (mLooper != null) {
+                    mLooper.quit();
+                    mCompositionThread.join();
+                }
+            } catch (InterruptedException e) {
+                // don't care
+            }
+            mCompositionThread = null;
+            mSurface = null;
+            mStartCompletionSemaphore = null;
+        }
+
+        Surface getWindowSurface(int windowIndex) {
+            return mWindows.get(windowIndex).getSurface();
+        }
+
+        void recreateWindows() throws Exception {
+            mRecreationCompletionSemaphore = new Semaphore(0);
+            Message msg = mHandler.obtainMessage(CompositionHandler.DO_RECREATE_WINDOWS);
+            mHandler.sendMessage(msg);
+            mRecreationCompletionSemaphore.acquire();
+        }
+
+        @Override
+        public void onFrameAvailable(SurfaceTexture surface) {
+            if (DBG) {
+                Log.i(TAG, "onFrameAvailable " + surface);
+            }
+            GlWindow w = mSurfaceTextureToWindowMap.get(surface);
+            if (w != null) {
+                w.markTextureUpdated();
+                requestUpdate();
+            } else {
+                Log.w(TAG, "cannot map Surface " + surface + " to window");
+            }
+        }
+
+        private void requestUpdate() {
+            Message msg = mHandler.obtainMessage(CompositionHandler.DO_RENDERING);
+            mHandler.sendMessage(msg);
+        }
+
+        private int loadShader(int shaderType, String source) throws GlException {
+            int shader = GLES20.glCreateShader(shaderType);
+            checkGlError("glCreateShader type=" + shaderType);
+            GLES20.glShaderSource(shader, source);
+            GLES20.glCompileShader(shader);
+            int[] compiled = new int[1];
+            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
+            if (compiled[0] == 0) {
+                Log.e(TAG, "Could not compile shader " + shaderType + ":");
+                Log.e(TAG, " " + GLES20.glGetShaderInfoLog(shader));
+                GLES20.glDeleteShader(shader);
+                shader = 0;
+            }
+            return shader;
+        }
+
+        private int createProgram(String vertexSource, String fragmentSource) throws GlException {
+            int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
+            if (vertexShader == 0) {
+                return 0;
+            }
+            int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
+            if (pixelShader == 0) {
+                return 0;
+            }
+
+            int program = GLES20.glCreateProgram();
+            checkGlError("glCreateProgram");
+            if (program == 0) {
+                Log.e(TAG, "Could not create program");
+            }
+            GLES20.glAttachShader(program, vertexShader);
+            checkGlError("glAttachShader");
+            GLES20.glAttachShader(program, pixelShader);
+            checkGlError("glAttachShader");
+            GLES20.glLinkProgram(program);
+            int[] linkStatus = new int[1];
+            GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
+            if (linkStatus[0] != GLES20.GL_TRUE) {
+                Log.e(TAG, "Could not link program: ");
+                Log.e(TAG, GLES20.glGetProgramInfoLog(program));
+                GLES20.glDeleteProgram(program);
+                program = 0;
+            }
+            return program;
+        }
+
+        private void initGl() throws GlException {
+            mEglHelper = new InputSurface(mSurface);
+            mEglHelper.makeCurrent();
+            mGlProgramId = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
+            mGlaPositionHandle = GLES20.glGetAttribLocation(mGlProgramId, "aPosition");
+            checkGlError("glGetAttribLocation aPosition");
+            if (mGlaPositionHandle == -1) {
+                throw new RuntimeException("Could not get attrib location for aPosition");
+            }
+            mGlaTextureHandle = GLES20.glGetAttribLocation(mGlProgramId, "aTextureCoord");
+            checkGlError("glGetAttribLocation aTextureCoord");
+            if (mGlaTextureHandle == -1) {
+                throw new RuntimeException("Could not get attrib location for aTextureCoord");
+            }
+            mGluMVPMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uMVPMatrix");
+            checkGlError("glGetUniformLocation uMVPMatrix");
+            if (mGluMVPMatrixHandle == -1) {
+                throw new RuntimeException("Could not get attrib location for uMVPMatrix");
+            }
+            mGluSTMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uSTMatrix");
+            checkGlError("glGetUniformLocation uSTMatrix");
+            if (mGluSTMatrixHandle == -1) {
+                throw new RuntimeException("Could not get attrib location for uSTMatrix");
+            }
+            Matrix.setIdentityM(mMVPMatrix, 0);
+            Log.i(TAG, "initGl w:" + mWidth + " h:" + mHeight);
+            GLES20.glViewport(0, 0, mWidth, mHeight);
+            float[] vMatrix = new float[16];
+            float[] projMatrix = new float[16];
+            // max window is from (0,0) to (mWidth - 1, mHeight - 1)
+            float wMid = mWidth / 2f;
+            float hMid = mHeight / 2f;
+            // look from positive z to hide windows in lower z
+            Matrix.setLookAtM(vMatrix, 0, wMid, hMid, 5f, wMid, hMid, 0f, 0f, 1.0f, 0.0f);
+            Matrix.orthoM(projMatrix, 0, -wMid, wMid, -hMid, hMid, 1, 10);
+            Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, vMatrix, 0);
+            createWindows();
+        }
+
+        private void createWindows() throws GlException {
+            // windows placed horizontally
+            int windowWidth = mWidth / mNumWindows;
+            for (int i = 0; i < mNumWindows; i++) {
+                GlWindow window = new GlWindow(this, i * windowWidth, 0, windowWidth, mHeight);
+                window.init();
+                mSurfaceTextureToWindowMap.put(window.getSurfaceTexture(), window);
+                mWindows.add(window);
+            }
+        }
+
+        private void cleanupGl() {
+            for (GlWindow w: mWindows) {
+                w.cleanup();
+            }
+            mWindows.clear();
+            mSurfaceTextureToWindowMap.clear();
+            if (mEglHelper != null) {
+                mEglHelper.release();
+            }
+        }
+
+        private void doGlRendering() throws GlException {
+            if (DBG) {
+                Log.i(TAG, "doGlRendering");
+            }
+            for (GlWindow w: mWindows) {
+                w.updateTexImageIfNecessary();
+            }
+            GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
+            GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
+
+            GLES20.glUseProgram(mGlProgramId);
+            for (GlWindow w: mWindows) {
+                GLES20.glUniformMatrix4fv(mGluMVPMatrixHandle, 1, false, mMVPMatrix, 0);
+                w.onDraw(mGluSTMatrixHandle, mGlaPositionHandle, mGlaTextureHandle);
+                checkGlError("window draw");
+            }
+            mEglHelper.swapBuffers();
+        }
+        private void doRecreateWindows() throws GlException {
+            for (GlWindow w: mWindows) {
+                w.cleanup();
+            }
+            mWindows.clear();
+            mSurfaceTextureToWindowMap.clear();
+            createWindows();
+            mRecreationCompletionSemaphore.release();
+        }
+
+        private void waitForStartCompletion() {
+            try {
+                mStartCompletionSemaphore.acquire();
+            } catch (InterruptedException e) {
+                //ignore
+            }
+            mStartCompletionSemaphore = null;
+        }
+
+        private class CompositionRunnable implements Runnable {
+            @Override
+            public void run() {
+                try {
+                    initGl();
+                    Looper.prepare();
+                    mLooper = Looper.myLooper();
+                    mHandler = new CompositionHandler();
+                    // init done
+                    mStartCompletionSemaphore.release();
+                    Looper.loop();
+                } catch (GlException e) {
+                    // ignore and clean-up
+                } finally {
+                    cleanupGl();
+                    mHandler = null;
+                    mLooper = null;
+                }
+            }
+        }
+
+        private class CompositionHandler extends Handler {
+            private static final int DO_RENDERING = 1;
+            private static final int DO_RECREATE_WINDOWS = 2;
+
+            @Override
+            public void handleMessage(Message msg) {
+                try {
+                    switch(msg.what) {
+                        case DO_RENDERING: {
+                            doGlRendering();
+                        } break;
+                        case DO_RECREATE_WINDOWS: {
+                            doRecreateWindows();
+                        } break;
+                    }
+                } catch (GlException e) {
+                    // should stop rendering
+                    mLooper.quit();
+                }
+            }
+        }
+
+        private class GlWindow {
+            private static final int FLOAT_SIZE_BYTES = 4;
+            private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
+            private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
+            private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
+            private int mBlX;
+            private int mBlY;
+            private int mWidth;
+            private int mHeight;
+            private int mTextureId = 0; // 0 is invalid
+            private volatile SurfaceTexture mSurfaceTexture;
+            private volatile Surface mSurface;
+            private FloatBuffer mVerticesData;
+            private float[] mSTMatrix = new float[16];
+            private AtomicBoolean mTextureUpdated = new AtomicBoolean(false);
+            private GlCompositor mCompositor;
+
+            /**
+             * @param blX X coordinate of bottom-left point of window
+             * @param blY Y coordinate of bottom-left point of window
+             * @param w window width
+             * @param h window height
+             */
+            public GlWindow(GlCompositor compositor, int blX, int blY, int w, int h) {
+                mCompositor = compositor;
+                mBlX = blX;
+                mBlY = blY;
+                mWidth = w;
+                mHeight = h;
+                int trX = blX + w;
+                int trY = blY + h;
+                float[] vertices = new float[] {
+                        // x, y, z, u, v
+                        mBlX, mBlY, 0, 0, 0,
+                        trX, mBlY, 0, 1, 0,
+                        mBlX, trY, 0, 0, 1,
+                        trX, trY, 0, 1, 1
+                };
+                Log.i(TAG, "create window " + this + " blX:" + mBlX + " blY:" + mBlY + " trX:" +
+                        trX + " trY:" + trY);
+                mVerticesData = ByteBuffer.allocateDirect(
+                        vertices.length * FLOAT_SIZE_BYTES)
+                                .order(ByteOrder.nativeOrder()).asFloatBuffer();
+                mVerticesData.put(vertices).position(0);
+            }
+
+            /**
+             * initialize the window for composition. counter-part is cleanup()
+             * @throws GlException
+             */
+            public void init() throws GlException {
+                int[] textures = new int[1];
+                GLES20.glGenTextures(1, textures, 0);
+
+                mTextureId = textures[0];
+                GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
+                checkGlError("glBindTexture mTextureID");
+
+                GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
+                        GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
+                GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
+                        GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
+                GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
+                        GLES20.GL_CLAMP_TO_EDGE);
+                GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
+                        GLES20.GL_CLAMP_TO_EDGE);
+                checkGlError("glTexParameter");
+                mSurfaceTexture = new SurfaceTexture(mTextureId);
+                mSurfaceTexture.setDefaultBufferSize(mWidth, mHeight);
+                mSurface = new Surface(mSurfaceTexture);
+                mSurfaceTexture.setOnFrameAvailableListener(mCompositor);
+            }
+
+            public void cleanup() {
+                mTextureUpdated.set(false);
+                if (mTextureId != 0) {
+                    int[] textures = new int[] {
+                            mTextureId
+                    };
+                    GLES20.glDeleteTextures(1, textures, 0);
+                }
+                GLES20.glFinish();
+                mSurface.release();
+                mSurface = null;
+                mSurfaceTexture.release();
+                mSurfaceTexture = null;
+            }
+
+            /**
+             * make texture as updated so that it can be updated in the next rendering.
+             */
+            public void markTextureUpdated() {
+                mTextureUpdated.set(true);
+            }
+
+            /**
+             * update texture for rendering if it is updated.
+             */
+            public void updateTexImageIfNecessary() {
+                if (mTextureUpdated.getAndSet(false)) {
+                    if (DBG) {
+                        Log.i(TAG, "updateTexImageIfNecessary " + this);
+                    }
+                    mSurfaceTexture.updateTexImage();
+                    mSurfaceTexture.getTransformMatrix(mSTMatrix);
+                }
+            }
+
+            /**
+             * draw the window. It will not be drawn at all if the window is not visible.
+             * @param uSTMatrixHandle shader handler for the STMatrix for texture coordinates
+             * mapping
+             * @param aPositionHandle shader handle for vertex position.
+             * @param aTextureHandle shader handle for texture
+             */
+            public void onDraw(int uSTMatrixHandle, int aPositionHandle, int aTextureHandle) {
+                GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
+                GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
+                mVerticesData.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
+                GLES20.glVertexAttribPointer(aPositionHandle, 3, GLES20.GL_FLOAT, false,
+                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData);
+                GLES20.glEnableVertexAttribArray(aPositionHandle);
+
+                mVerticesData.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
+                GLES20.glVertexAttribPointer(aTextureHandle, 2, GLES20.GL_FLOAT, false,
+                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData);
+                GLES20.glEnableVertexAttribArray(aTextureHandle);
+                GLES20.glUniformMatrix4fv(uSTMatrixHandle, 1, false, mSTMatrix, 0);
+                GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
+            }
+
+            public SurfaceTexture getSurfaceTexture() {
+                return mSurfaceTexture;
+            }
+
+            public Surface getSurface() {
+                return mSurface;
+            }
+        }
+    }
+
+    static void checkGlError(String op) throws GlException {
+        int error;
+        while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
+            Log.e(TAG, op + ": glError " + error);
+            throw new GlException(op + ": glError " + error);
+        }
+    }
+
+    public static class GlException extends Exception {
+        public GlException(String msg) {
+            super(msg);
+        }
+    }
+
+    private class VirtualDisplayPresentation {
+        public static final int RENDERING_OPENGL = 0;
+        public static final int RENDERING_VIEW_HIERARCHY = 1;
+
+        private Context mContext;
+        private Surface mSurface;
+        private int mWidth;
+        private int mHeight;
+        private int mRenderingType;
+        private final DisplayManager mDisplayManager;
+        private VirtualDisplay mVirtualDisplay;
+        private TestPresentation mPresentation;
+
+        VirtualDisplayPresentation(Context context, Surface surface, int w, int h,
+                int renderingType) {
+            mContext = context;
+            mSurface = surface;
+            mWidth = w;
+            mHeight = h;
+            mRenderingType = renderingType;
+            mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
+        }
+
+        void createVirtualDisplay() {
+            runOnMainSync(new Runnable() {
+                @Override
+                public void run() {
+                    mVirtualDisplay = mDisplayManager.createVirtualDisplay(
+                            TAG, mWidth, mHeight, 200, mSurface, 0);
+                }
+            });
+        }
+
+        void destroyVirtualDisplay() {
+            runOnMainSync(new Runnable() {
+                @Override
+                public void run() {
+                    mVirtualDisplay.release();
+                }
+            });
+        }
+
+        void createPresentation() {
+            runOnMainSync(new Runnable() {
+                @Override
+                public void run() {
+                    mPresentation = new TestPresentation(getContext(),
+                            mVirtualDisplay.getDisplay());
+                    mPresentation.show();
+                }
+            });
+        }
+
+        void dismissPresentation() {
+            runOnMainSync(new Runnable() {
+                @Override
+                public void run() {
+                    mPresentation.dismiss();
+                }
+            });
+        }
+
+        void doRendering() {
+            runOnMainSync(new Runnable() {
+                @Override
+                public void run() {
+                    mPresentation.doRendering();
+                }
+            });
+        }
+
+        private class TestPresentation extends Presentation {
+            private TextView mTextView;
+            private int mRenderingCount = 0;
+
+            public TestPresentation(Context outerContext, Display display) {
+                super(outerContext, display);
+                getWindow().setType(WindowManager.LayoutParams.TYPE_PRIVATE_PRESENTATION);
+            }
+
+            @Override
+            protected void onCreate(Bundle savedInstanceState) {
+                super.onCreate(savedInstanceState);
+                if (VirtualDisplayPresentation.this.mRenderingType == RENDERING_OPENGL) {
+                    //TODO add init for opengl renderer
+                } else {
+                    mTextView = new TextView(getContext());
+                    mTextView.setTextSize(14);
+                    mTextView.setTypeface(Typeface.DEFAULT_BOLD);
+                    mTextView.setText(Integer.toString(mRenderingCount));
+                    setContentView(mTextView);
+                }
+            }
+
+            public void doRendering() {
+                if (VirtualDisplayPresentation.this.mRenderingType == RENDERING_OPENGL) {
+                    //TODO add opengl rendering
+                } else {
+                    mRenderingCount++;
+                    mTextView.setText(Integer.toString(mRenderingCount));
+                }
+            }
+        }
+    }
+
+    private static class CodecInfo {
+        public int mMaxW;
+        public int mMaxH;
+        public int mFps;
+        public int mBitRate;
+        public String mCodecName;
+    };
+    /**
+     * Returns the first codec capable of encoding the specified MIME type, or null if no
+     * match was found.
+     */
+    private static MediaCodecInfo selectCodec(String mimeType) {
+        int numCodecs = MediaCodecList.getCodecCount();
+        for (int i = 0; i < numCodecs; i++) {
+            MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
+
+            if (!codecInfo.isEncoder()) {
+                continue;
+            }
+
+            String[] types = codecInfo.getSupportedTypes();
+            for (int j = 0; j < types.length; j++) {
+                if (types[j].equalsIgnoreCase(mimeType)) {
+                    return codecInfo;
+                }
+            }
+        }
+        return null;
+    }
+
+    private static CodecInfo getAvcSupportedFormatInfo() {
+        MediaCodecInfo mediaCodecInfo = selectCodec(MIME_TYPE);
+        CodecCapabilities cap = mediaCodecInfo.getCapabilitiesForType(MIME_TYPE);
+        if (cap == null) { // not supported
+            return null;
+        }
+        CodecInfo info = new CodecInfo();
+        int highestLevel = 0;
+        for (CodecProfileLevel lvl : cap.profileLevels) {
+            if (lvl.level > highestLevel) {
+                highestLevel = lvl.level;
+            }
+        }
+        int maxW = 0;
+        int maxH = 0;
+        int bitRate = 0;
+        int fps = 0; // frame rate for the max resolution
+        switch(highestLevel) {
+            // Do not support Level 1 to 2.
+            case CodecProfileLevel.AVCLevel1:
+            case CodecProfileLevel.AVCLevel11:
+            case CodecProfileLevel.AVCLevel12:
+            case CodecProfileLevel.AVCLevel13:
+            case CodecProfileLevel.AVCLevel1b:
+            case CodecProfileLevel.AVCLevel2:
+                return null;
+            case CodecProfileLevel.AVCLevel21:
+                maxW = 352;
+                maxH = 576;
+                bitRate = 4000000;
+                fps = 25;
+                break;
+            case CodecProfileLevel.AVCLevel22:
+                maxW = 720;
+                maxH = 480;
+                bitRate = 4000000;
+                fps = 15;
+                break;
+            case CodecProfileLevel.AVCLevel3:
+                maxW = 720;
+                maxH = 480;
+                bitRate = 10000000;
+                fps = 30;
+                break;
+            case CodecProfileLevel.AVCLevel31:
+                maxW = 1280;
+                maxH = 720;
+                bitRate = 14000000;
+                fps = 30;
+                break;
+            case CodecProfileLevel.AVCLevel32:
+                maxW = 1280;
+                maxH = 720;
+                bitRate = 20000000;
+                fps = 60;
+                break;
+            case CodecProfileLevel.AVCLevel4: // only try up to 1080p
+            default:
+                maxW = 1920;
+                maxH = 1080;
+                bitRate = 20000000;
+                fps = 30;
+                break;
+        }
+        info.mMaxW = maxW;
+        info.mMaxH = maxH;
+        info.mFps = fps;
+        info.mBitRate = bitRate;
+        info.mCodecName = mediaCodecInfo.getName();
+        Log.i(TAG, "AVC Level 0x" + Integer.toHexString(highestLevel) + " bit rate " + bitRate +
+                " fps " + info.mFps + " w " + maxW + " h " + maxH);
+
+        return info;
+    }
+
+    public void runOnMainSync(Runnable runner) {
+        SyncRunnable sr = new SyncRunnable(runner);
+        mHandler.post(sr);
+        sr.waitForComplete();
+    }
+
+    private static final class SyncRunnable implements Runnable {
+        private final Runnable mTarget;
+        private boolean mComplete;
+
+        public SyncRunnable(Runnable target) {
+            mTarget = target;
+        }
+
+        public void run() {
+            mTarget.run();
+            synchronized (this) {
+                mComplete = true;
+                notifyAll();
+            }
+        }
+
+        public void waitForComplete() {
+            synchronized (this) {
+                while (!mComplete) {
+                    try {
+                        wait();
+                    } catch (InterruptedException e) {
+                    }
+                }
+            }
+        }
+    }
+}
diff --git a/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java b/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java
index c0350d7..a09d368 100644
--- a/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaDrmMockTest.java
@@ -41,7 +41,7 @@
     static final UUID mockScheme = new UUID(0x0102030405060708L, 0x090a0b0c0d0e0f10L);
     static final UUID badScheme = new UUID(0xffffffffffffffffL, 0xffffffffffffffffL);
 
-    private boolean testIsCryptoSchemeSupported() {
+    private boolean isMockPluginInstalled() {
         return MediaDrm.isCryptoSchemeSupported(mockScheme);
     }
 
@@ -49,27 +49,36 @@
         assertFalse(MediaDrm.isCryptoSchemeSupported(badScheme));
     }
 
+    public void testMediaDrmConstructor() throws Exception {
+        if (isMockPluginInstalled()) {
+            MediaDrm md = new MediaDrm(mockScheme);
+        } else {
+            Log.w(TAG, "optional plugin libmockdrmcryptoplugin.so is not installed");
+            Log.w(TAG, "To verify the MediaDrm APIs, you should install this plugin");
+        }
+    }
+
     public void testIsMimeTypeSupported() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
         String mimeType = "video/mp4";
         assertTrue(MediaDrm.isCryptoSchemeSupported(mockScheme, mimeType));
     }
 
     public void testIsMimeTypeNotSupported() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
         String mimeType = "video/foo";
         assertFalse(MediaDrm.isCryptoSchemeSupported(mockScheme, mimeType));
     }
 
-    public void testMediaDrmConstructor() throws Exception {
-        boolean gotException = false;
-        try {
-            MediaDrm md = new MediaDrm(mockScheme);
-        } catch (MediaDrmException e) {
-            gotException = true;
-        }
-        assertFalse(gotException);
-    }
-
     public void testMediaDrmConstructorFails() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         boolean gotException = false;
         try {
             MediaDrm md = new MediaDrm(badScheme);
@@ -80,6 +89,10 @@
     }
 
     public void testStringProperties() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         md.setPropertyString("test-string", "test-value");
@@ -87,6 +100,10 @@
     }
 
     public void testByteArrayProperties() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         byte testArray[] = {0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x10, 0x11, 0x12};
@@ -95,6 +112,10 @@
     }
 
     public void testMissingPropertyString() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         boolean gotException = false;
@@ -107,6 +128,10 @@
     }
 
     public void testNullPropertyString() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         boolean gotException = false;
@@ -119,6 +144,10 @@
     }
 
     public void testMissingPropertyByteArray() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         boolean gotException = false;
@@ -131,6 +160,10 @@
     }
 
     public void testNullPropertyByteArray() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         boolean gotException = false;
@@ -143,12 +176,20 @@
     }
 
     public void testOpenCloseSession() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
         md.closeSession(sessionId);
     }
 
     public void testBadSession() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = {0x05, 0x6, 0x7, 0x8};
         boolean gotException = false;
@@ -161,6 +202,10 @@
     }
 
     public void testNullSession() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = null;
         boolean gotException = false;
@@ -173,6 +218,10 @@
     }
 
     public void testGetKeyRequest() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
 
@@ -203,6 +252,10 @@
     }
 
     public void testGetKeyRequestNoOptionalParameters() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
 
@@ -229,6 +282,10 @@
     }
 
     public void testGetKeyRequestOffline() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
 
@@ -255,6 +312,10 @@
     }
 
     public void testGetKeyRequestRelease() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
 
@@ -278,6 +339,10 @@
     }
 
     public void testProvideKeyResponse() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
 
@@ -291,6 +356,10 @@
     }
 
     public void testRemoveKeys() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
 
@@ -302,6 +371,10 @@
     }
 
     public void testRestoreKeys() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
 
@@ -315,6 +388,10 @@
     }
 
     public void testQueryKeyStatus() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
         byte[] sessionId = openSession(md);
         HashMap<String, String> infoMap = md.queryKeyStatus(sessionId);
@@ -329,6 +406,10 @@
     }
 
     public void testGetProvisionRequest() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         // Set up mock expected responses using properties
@@ -343,6 +424,10 @@
     }
 
     public void testProvideProvisionResponse() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         // Set up mock expected responses using properties
@@ -353,6 +438,10 @@
     }
 
     public void testGetSecureStops() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         // Set up mock expected responses using properties
@@ -374,6 +463,10 @@
     }
 
     public void testReleaseSecureStops() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         // Set up mock expected responses using properties
@@ -384,6 +477,10 @@
     }
 
     public void testMultipleSessions() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         byte[] session1 = openSession(md);
@@ -399,6 +496,10 @@
     }
 
     public void testCryptoSession() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         byte[] sessionId = openSession(md);
@@ -407,6 +508,10 @@
     }
 
     public void testBadCryptoSession() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         boolean gotException = false;
@@ -420,6 +525,10 @@
     }
 
     public void testCryptoSessionEncrypt() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         byte[] sessionId = openSession(md);
@@ -442,6 +551,10 @@
     }
 
     public void testCryptoSessionDecrypt() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         byte[] sessionId = openSession(md);
@@ -464,6 +577,10 @@
     }
 
     public void testCryptoSessionSign() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         byte[] sessionId = openSession(md);
@@ -484,6 +601,10 @@
     }
 
     public void testCryptoSessionVerify() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
         MediaDrm md = new MediaDrm(mockScheme);
 
         byte[] sessionId = openSession(md);
@@ -511,6 +632,10 @@
     private boolean mGotEvent = false;
 
     public void testEventNoSessionNoData() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
 
         new Thread() {
             @Override
@@ -577,6 +702,10 @@
     }
 
     public void testEventWithSessionAndData() throws Exception {
+        if (!isMockPluginInstalled()) {
+            return;
+        }
+
 
         new Thread() {
             @Override
diff --git a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
index 42ae7a7..9cad011 100644
--- a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
@@ -38,6 +38,11 @@
     private static final String TAG = "MediaMuxerTest";
     private static final boolean VERBOSE = false;
     private static final int MAX_SAMPLE_SIZE = 256 * 1024;
+    private static final float LATITUDE = 0.0000f;
+    private static final float LONGITUDE  = -180.0f;
+    private static final float BAD_LATITUDE = 91.0f;
+    private static final float BAD_LONGITUDE = -181.0f;
+    private static final float TOLERANCE = 0.0002f;
     private Resources mResources;
 
     @Override
@@ -189,6 +194,25 @@
         if (degrees >= 0) {
             muxer.setOrientationHint(degrees);
         }
+
+        // Test setLocation out of bound cases
+        try {
+            muxer.setLocation(BAD_LATITUDE, LONGITUDE);
+            fail("setLocation succeeded with bad argument: [" + BAD_LATITUDE + "," + LONGITUDE
+                    + "]");
+        } catch (IllegalArgumentException e) {
+            // Expected
+        }
+        try {
+            muxer.setLocation(LATITUDE, BAD_LONGITUDE);
+            fail("setLocation succeeded with bad argument: [" + LATITUDE + "," + BAD_LONGITUDE
+                    + "]");
+        } catch (IllegalArgumentException e) {
+            // Expected
+        }
+
+        muxer.setLocation(LATITUDE, LONGITUDE);
+
         muxer.start();
         while (!sawEOS) {
             bufferInfo.offset = offset;
@@ -235,6 +259,7 @@
         try {
             cloneMediaUsingMuxer(srcMedia, outputMediaFile, expectedTrackCount, degrees);
             verifyAttributesMatch(srcMedia, outputMediaFile, degrees);
+            verifyLocationInFile(outputMediaFile);
             // Check the sample on 1s and 0.5s.
             verifySamplesMatch(srcMedia, outputMediaFile, 1000000);
             verifySamplesMatch(srcMedia, outputMediaFile, 500000);
@@ -337,5 +362,32 @@
             fail("byteBuffer didn't match");
         }
     }
+
+    private void verifyLocationInFile(String fileName) {
+        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+        retriever.setDataSource(fileName);
+        String location = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION);
+        assertNotNull("No location information found in file " + fileName, location);
+
+        // parsing String location and recover the location inforamtion in floats
+        // Make sure the tolerance is very small - due to rounding errors.
+
+        // Get the position of the -/+ sign in location String, which indicates
+        // the beginning of the longtitude.
+        int index = location.lastIndexOf('-');
+        if (index == -1) {
+            index = location.lastIndexOf('+');
+        }
+        assertTrue("+ or - is not found", index != -1);
+        assertTrue("+ or - is only found at the beginning", index != 0);
+        float latitude = Float.parseFloat(location.substring(0, index - 1));
+        float longitude = Float.parseFloat(location.substring(index));
+        assertTrue("Incorrect latitude: " + latitude,
+                Math.abs(latitude - LATITUDE) <= TOLERANCE);
+        assertTrue("Incorrect longitude: " + longitude,
+                Math.abs(longitude - LONGITUDE) <= TOLERANCE);
+        retriever.release();
+    }
+
 }
 
diff --git a/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java b/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java
index ce3a9c4..dfaabb8 100644
--- a/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java
@@ -83,11 +83,6 @@
         Cursor c = mRingtoneManager.getCursor();
         assertTrue("Must have at least one ring tone available", c.getCount() > 0);
 
-        mRingtoneManager.setIncludeDrm(true);
-        assertTrue(mRingtoneManager.getIncludeDrm());
-        mRingtoneManager.setIncludeDrm(false);
-        assertFalse(mRingtoneManager.getIncludeDrm());
-
         assertNotNull(mRingtoneManager.getRingtone(0));
         assertNotNull(RingtoneManager.getRingtone(mContext, Settings.System.DEFAULT_RINGTONE_URI));
         int expectedPosition = 0;
diff --git a/tests/tests/mediadrm/Android.mk b/tests/tests/mediadrm/Android.mk
deleted file mode 100644
index ef8c633..0000000
--- a/tests/tests/mediadrm/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright (C) 2013 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/mediadrm/lib/Android.mk b/tests/tests/mediadrm/lib/Android.mk
deleted file mode 100644
index 42a5e1b..0000000
--- a/tests/tests/mediadrm/lib/Android.mk
+++ /dev/null
@@ -1,35 +0,0 @@
-#
-# Copyright (C) 2013 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_SRC_FILES:= \
-    MockDrmCryptoPlugin.cpp
-
-LOCAL_MODULE := libmockdrmcryptoplugin
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR_SHARED_LIBRARIES)/mediadrm
-
-LOCAL_SHARED_LIBRARIES := \
-    libutils liblog
-
-LOCAL_C_INCLUDES += \
-    $(TOP)/frameworks/av/include \
-    $(TOP)/frameworks/native/include/media
-
-LOCAL_MODULE_TAGS := optional
-
-include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/mediadrm/lib/MockDrmCryptoPlugin.cpp b/tests/tests/mediadrm/lib/MockDrmCryptoPlugin.cpp
deleted file mode 100644
index f2cadf7..0000000
--- a/tests/tests/mediadrm/lib/MockDrmCryptoPlugin.cpp
+++ /dev/null
@@ -1,705 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "MockDrmCryptoPlugin"
-#include <utils/Log.h>
-
-
-#include "drm/DrmAPI.h"
-#include "MockDrmCryptoPlugin.h"
-#include "media/stagefright/MediaErrors.h"
-
-using namespace android;
-
-// Shared library entry point
-DrmFactory *createDrmFactory()
-{
-    return new MockDrmFactory();
-}
-
-// Shared library entry point
-CryptoFactory *createCryptoFactory()
-{
-    return new MockCryptoFactory();
-}
-
-const uint8_t mock_uuid[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
-                               0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
-
-namespace android {
-
-    // MockDrmFactory
-    bool MockDrmFactory::isCryptoSchemeSupported(const uint8_t uuid[16])
-    {
-        return (!memcmp(uuid, mock_uuid, sizeof(uuid)));
-    }
-
-    bool MockDrmFactory::isContentTypeSupported(const String8 &mimeType)
-    {
-        if (mimeType != "video/mp4") {
-            return false;
-        }
-        return true;
-    }
-
-    status_t MockDrmFactory::createDrmPlugin(const uint8_t uuid[16], DrmPlugin **plugin)
-    {
-        *plugin = new MockDrmPlugin();
-        return OK;
-    }
-
-    // MockCryptoFactory
-    bool MockCryptoFactory::isCryptoSchemeSupported(const uint8_t uuid[16]) const
-    {
-        return (!memcmp(uuid, mock_uuid, sizeof(uuid)));
-    }
-
-    status_t MockCryptoFactory::createPlugin(const uint8_t uuid[16], const void *data,
-                                             size_t size, CryptoPlugin **plugin)
-    {
-        *plugin = new MockCryptoPlugin();
-        return OK;
-    }
-
-
-    // MockDrmPlugin methods
-
-    status_t MockDrmPlugin::openSession(Vector<uint8_t> &sessionId)
-    {
-        const size_t kSessionIdSize = 8;
-
-        Mutex::Autolock lock(mLock);
-        for (size_t i = 0; i < kSessionIdSize / sizeof(long); i++) {
-            long r = random();
-            sessionId.appendArray((uint8_t *)&r, sizeof(long));
-        }
-        mSessions.add(sessionId);
-
-        ALOGD("MockDrmPlugin::openSession() -> %s", vectorToString(sessionId).string());
-        return OK;
-    }
-
-    status_t MockDrmPlugin::closeSession(Vector<uint8_t> const &sessionId)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::closeSession(%s)", vectorToString(sessionId).string());
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-        mSessions.removeAt(index);
-        return OK;
-    }
-
-
-    status_t MockDrmPlugin::getKeyRequest(Vector<uint8_t> const &sessionId,
-                                          Vector<uint8_t> const &initData,
-                                          String8 const &mimeType, KeyType keyType,
-                                          KeyedVector<String8, String8> const &optionalParameters,
-                                          Vector<uint8_t> &request, String8 &defaultUrl)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::getKeyRequest(sessionId=%s, initData=%s, mimeType=%s"
-              ", keyType=%d, optionalParameters=%s))",
-              vectorToString(sessionId).string(), vectorToString(initData).string(), mimeType.string(),
-              keyType, stringMapToString(optionalParameters).string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] initData           -> mock-initdata
-        //   string mimeType           -> mock-mimetype
-        //   string keyType            -> mock-keytype
-        //   string optionalParameters -> mock-optparams formatted as {key1,value1},{key2,value2}
-
-        mByteArrayProperties.add(String8("mock-initdata"), initData);
-        mStringProperties.add(String8("mock-mimetype"), mimeType);
-
-        String8 keyTypeStr;
-        keyTypeStr.appendFormat("%d", (int)keyType);
-        mStringProperties.add(String8("mock-keytype"), keyTypeStr);
-
-        String8 params;
-        for (size_t i = 0; i < optionalParameters.size(); i++) {
-            params.appendFormat("%s{%s,%s}", i ? "," : "",
-                                optionalParameters.keyAt(i).string(),
-                                optionalParameters.valueAt(i).string());
-        }
-        mStringProperties.add(String8("mock-optparams"), params);
-
-        // Properties used in mock test, set by cts test app returned from mock plugin
-        //   byte[] mock-request       -> request
-        //   string mock-default-url   -> defaultUrl
-
-        index = mByteArrayProperties.indexOfKey(String8("mock-request"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-request' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            request = mByteArrayProperties.valueAt(index);
-        }
-
-        index = mStringProperties.indexOfKey(String8("mock-defaultUrl"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-defaultUrl' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            defaultUrl = mStringProperties.valueAt(index);
-        }
-        return OK;
-    }
-
-    status_t MockDrmPlugin::provideKeyResponse(Vector<uint8_t> const &sessionId,
-                                               Vector<uint8_t> const &response,
-                                               Vector<uint8_t> &keySetId)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::provideKeyResponse(sessionId=%s, response=%s)",
-              vectorToString(sessionId).string(), vectorToString(response).string());
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-        if (response.size() == 0) {
-            return BAD_VALUE;
-        }
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] response            -> mock-response
-        mByteArrayProperties.add(String8("mock-response"), response);
-
-        const size_t kKeySetIdSize = 8;
-
-        for (size_t i = 0; i < kKeySetIdSize / sizeof(long); i++) {
-            long r = random();
-            keySetId.appendArray((uint8_t *)&r, sizeof(long));
-        }
-        mKeySets.add(keySetId);
-
-        return OK;
-    }
-
-    status_t MockDrmPlugin::removeKeys(Vector<uint8_t> const &keySetId)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::removeKeys(keySetId=%s)",
-              vectorToString(keySetId).string());
-
-        ssize_t index = findKeySet(keySetId);
-        if (index == kNotFound) {
-            ALOGD("Invalid keySetId");
-            return BAD_VALUE;
-        }
-        mKeySets.removeAt(index);
-
-        return OK;
-    }
-
-    status_t MockDrmPlugin::restoreKeys(Vector<uint8_t> const &sessionId,
-                                        Vector<uint8_t> const &keySetId)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::restoreKeys(sessionId=%s, keySetId=%s)",
-              vectorToString(sessionId).string(),
-              vectorToString(keySetId).string());
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        index = findKeySet(keySetId);
-        if (index == kNotFound) {
-            ALOGD("Invalid keySetId");
-            return BAD_VALUE;
-        }
-
-        return OK;
-    }
-
-    status_t MockDrmPlugin::queryKeyStatus(Vector<uint8_t> const &sessionId,
-                                               KeyedVector<String8, String8> &infoMap) const
-    {
-        ALOGD("MockDrmPlugin::queryKeyStatus(sessionId=%s)",
-              vectorToString(sessionId).string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        infoMap.add(String8("purchaseDuration"), String8("1000"));
-        infoMap.add(String8("licenseDuration"), String8("100"));
-        return OK;
-    }
-
-    status_t MockDrmPlugin::getProvisionRequest(Vector<uint8_t> &request,
-                                                String8 &defaultUrl)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::getProvisionRequest()");
-
-        // Properties used in mock test, set by cts test app returned from mock plugin
-        //   byte[] mock-request       -> request
-        //   string mock-default-url   -> defaultUrl
-
-        ssize_t index = mByteArrayProperties.indexOfKey(String8("mock-request"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-request' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            request = mByteArrayProperties.valueAt(index);
-        }
-
-        index = mStringProperties.indexOfKey(String8("mock-defaultUrl"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-defaultUrl' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            defaultUrl = mStringProperties.valueAt(index);
-        }
-        return OK;
-    }
-
-    status_t MockDrmPlugin::provideProvisionResponse(Vector<uint8_t> const &response)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::provideProvisionResponse(%s)",
-              vectorToString(response).string());
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] response            -> mock-response
-
-        mByteArrayProperties.add(String8("mock-response"), response);
-        return OK;
-    }
-
-    status_t MockDrmPlugin::getSecureStops(List<Vector<uint8_t> > &secureStops)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::getSecureStops()");
-
-        // Properties used in mock test, set by cts test app returned from mock plugin
-        //   byte[] mock-secure-stop1  -> first secure stop in list
-        //   byte[] mock-secure-stop2  -> second secure stop in list
-
-        Vector<uint8_t> ss1, ss2;
-        ssize_t index = mByteArrayProperties.indexOfKey(String8("mock-secure-stop1"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-secure-stop1' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            ss1 = mByteArrayProperties.valueAt(index);
-        }
-
-        index = mByteArrayProperties.indexOfKey(String8("mock-secure-stop2"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-secure-stop2' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            ss2 = mByteArrayProperties.valueAt(index);
-        }
-
-        secureStops.push_back(ss1);
-        secureStops.push_back(ss2);
-        return OK;
-    }
-
-    status_t MockDrmPlugin::releaseSecureStops(Vector<uint8_t> const &ssRelease)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::releaseSecureStops(%s)",
-              vectorToString(ssRelease).string());
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] secure-stop-release  -> mock-ssrelease
-        mByteArrayProperties.add(String8("mock-ssrelease"), ssRelease);
-
-        return OK;
-    }
-
-    status_t MockDrmPlugin::getPropertyString(String8 const &name, String8 &value) const
-    {
-        ALOGD("MockDrmPlugin::getPropertyString(name=%s)", name.string());
-        ssize_t index = mStringProperties.indexOfKey(name);
-        if (index < 0) {
-            ALOGD("no property for '%s'", name.string());
-            return BAD_VALUE;
-        }
-        value = mStringProperties.valueAt(index);
-        return OK;
-    }
-
-    status_t MockDrmPlugin::getPropertyByteArray(String8 const &name,
-                                                 Vector<uint8_t> &value) const
-    {
-        ALOGD("MockDrmPlugin::getPropertyByteArray(name=%s)", name.string());
-        ssize_t index = mByteArrayProperties.indexOfKey(name);
-        if (index < 0) {
-            ALOGD("no property for '%s'", name.string());
-            return BAD_VALUE;
-        }
-        value = mByteArrayProperties.valueAt(index);
-        return OK;
-    }
-
-    status_t MockDrmPlugin::setPropertyString(String8 const &name,
-                                              String8 const &value)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::setPropertyString(name=%s, value=%s)",
-              name.string(), value.string());
-
-        if (name == "mock-send-event") {
-            unsigned code, extra;
-            sscanf(value.string(), "%d %d", &code, &extra);
-            DrmPlugin::EventType eventType = (DrmPlugin::EventType)code;
-
-            Vector<uint8_t> const *pSessionId = NULL;
-            ssize_t index = mByteArrayProperties.indexOfKey(String8("mock-event-session-id"));
-            if (index >= 0) {
-                pSessionId = &mByteArrayProperties[index];
-            }
-
-            Vector<uint8_t> const *pData = NULL;
-            index = mByteArrayProperties.indexOfKey(String8("mock-event-data"));
-            if (index >= 0) {
-                pData = &mByteArrayProperties[index];
-            }
-            ALOGD("sending event from mock drm plugin: %d %d %s %s",
-                  (int)code, extra, pSessionId ? vectorToString(*pSessionId) : "{}",
-                  pData ? vectorToString(*pData) : "{}");
-
-            sendEvent(eventType, extra, pSessionId, pData);
-        } else {
-            mStringProperties.add(name, value);
-        }
-        return OK;
-    }
-
-    status_t MockDrmPlugin::setPropertyByteArray(String8 const &name,
-                                                 Vector<uint8_t> const &value)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::setPropertyByteArray(name=%s, value=%s)",
-              name.string(), vectorToString(value).string());
-        mByteArrayProperties.add(name, value);
-        return OK;
-    }
-
-    status_t MockDrmPlugin::setCipherAlgorithm(Vector<uint8_t> const &sessionId,
-                                               String8 const &algorithm)
-    {
-        Mutex::Autolock lock(mLock);
-
-        ALOGD("MockDrmPlugin::setCipherAlgorithm(sessionId=%s, algorithm=%s)",
-              vectorToString(sessionId).string(), algorithm.string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        if (algorithm == "AES/CBC/NoPadding") {
-            return OK;
-        }
-        return BAD_VALUE;
-    }
-
-    status_t MockDrmPlugin::setMacAlgorithm(Vector<uint8_t> const &sessionId,
-                                            String8 const &algorithm)
-    {
-        Mutex::Autolock lock(mLock);
-
-        ALOGD("MockDrmPlugin::setMacAlgorithm(sessionId=%s, algorithm=%s)",
-              vectorToString(sessionId).string(), algorithm.string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        if (algorithm == "HmacSHA256") {
-            return OK;
-        }
-        return BAD_VALUE;
-    }
-
-    status_t MockDrmPlugin::encrypt(Vector<uint8_t> const &sessionId,
-                                    Vector<uint8_t> const &keyId,
-                                    Vector<uint8_t> const &input,
-                                    Vector<uint8_t> const &iv,
-                                    Vector<uint8_t> &output)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::encrypt(sessionId=%s, keyId=%s, input=%s, iv=%s)",
-              vectorToString(sessionId).string(),
-              vectorToString(keyId).string(),
-              vectorToString(input).string(),
-              vectorToString(iv).string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] keyId              -> mock-keyid
-        //   byte[] input              -> mock-input
-        //   byte[] iv                 -> mock-iv
-        mByteArrayProperties.add(String8("mock-keyid"), keyId);
-        mByteArrayProperties.add(String8("mock-input"), input);
-        mByteArrayProperties.add(String8("mock-iv"), iv);
-
-        // Properties used in mock test, set by cts test app returned from mock plugin
-        //   byte[] mock-output        -> output
-        index = mByteArrayProperties.indexOfKey(String8("mock-output"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-request' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            output = mByteArrayProperties.valueAt(index);
-        }
-        return OK;
-    }
-
-    status_t MockDrmPlugin::decrypt(Vector<uint8_t> const &sessionId,
-                                    Vector<uint8_t> const &keyId,
-                                    Vector<uint8_t> const &input,
-                                    Vector<uint8_t> const &iv,
-                                    Vector<uint8_t> &output)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::decrypt(sessionId=%s, keyId=%s, input=%s, iv=%s)",
-              vectorToString(sessionId).string(),
-              vectorToString(keyId).string(),
-              vectorToString(input).string(),
-              vectorToString(iv).string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] keyId              -> mock-keyid
-        //   byte[] input              -> mock-input
-        //   byte[] iv                 -> mock-iv
-        mByteArrayProperties.add(String8("mock-keyid"), keyId);
-        mByteArrayProperties.add(String8("mock-input"), input);
-        mByteArrayProperties.add(String8("mock-iv"), iv);
-
-        // Properties used in mock test, set by cts test app returned from mock plugin
-        //   byte[] mock-output        -> output
-        index = mByteArrayProperties.indexOfKey(String8("mock-output"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-request' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            output = mByteArrayProperties.valueAt(index);
-        }
-        return OK;
-    }
-
-    status_t MockDrmPlugin::sign(Vector<uint8_t> const &sessionId,
-                                 Vector<uint8_t> const &keyId,
-                                 Vector<uint8_t> const &message,
-                                 Vector<uint8_t> &signature)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::sign(sessionId=%s, keyId=%s, message=%s)",
-              vectorToString(sessionId).string(),
-              vectorToString(keyId).string(),
-              vectorToString(message).string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] keyId              -> mock-keyid
-        //   byte[] message            -> mock-message
-        mByteArrayProperties.add(String8("mock-keyid"), keyId);
-        mByteArrayProperties.add(String8("mock-message"), message);
-
-        // Properties used in mock test, set by cts test app returned from mock plugin
-        //   byte[] mock-signature        -> signature
-        index = mByteArrayProperties.indexOfKey(String8("mock-signature"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-request' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            signature = mByteArrayProperties.valueAt(index);
-        }
-        return OK;
-    }
-
-    status_t MockDrmPlugin::verify(Vector<uint8_t> const &sessionId,
-                                   Vector<uint8_t> const &keyId,
-                                   Vector<uint8_t> const &message,
-                                   Vector<uint8_t> const &signature,
-                                   bool &match)
-    {
-        Mutex::Autolock lock(mLock);
-        ALOGD("MockDrmPlugin::verify(sessionId=%s, keyId=%s, message=%s, signature=%s)",
-              vectorToString(sessionId).string(),
-              vectorToString(keyId).string(),
-              vectorToString(message).string(),
-              vectorToString(signature).string());
-
-        ssize_t index = findSession(sessionId);
-        if (index == kNotFound) {
-            ALOGD("Invalid sessionId");
-            return BAD_VALUE;
-        }
-
-        // Properties used in mock test, set by mock plugin and verifed cts test app
-        //   byte[] keyId              -> mock-keyid
-        //   byte[] message            -> mock-message
-        //   byte[] signature          -> mock-signature
-        mByteArrayProperties.add(String8("mock-keyid"), keyId);
-        mByteArrayProperties.add(String8("mock-message"), message);
-        mByteArrayProperties.add(String8("mock-signature"), signature);
-
-        // Properties used in mock test, set by cts test app returned from mock plugin
-        //   String mock-match "1" or "0"         -> match
-        index = mStringProperties.indexOfKey(String8("mock-match"));
-        if (index < 0) {
-            ALOGD("Missing 'mock-request' parameter for mock");
-            return BAD_VALUE;
-        } else {
-            match = atol(mStringProperties.valueAt(index).string());
-        }
-        return OK;
-    }
-
-    ssize_t MockDrmPlugin::findSession(Vector<uint8_t> const &sessionId) const
-    {
-        ALOGD("findSession: nsessions=%d, size=%d", mSessions.size(), sessionId.size());
-        for (size_t i = 0; i < mSessions.size(); ++i) {
-            if (memcmp(mSessions[i].array(), sessionId.array(), sessionId.size()) == 0) {
-                return i;
-            }
-        }
-        return kNotFound;
-    }
-
-    ssize_t MockDrmPlugin::findKeySet(Vector<uint8_t> const &keySetId) const
-    {
-        ALOGD("findKeySet: nkeySets=%d, size=%d", mKeySets.size(), keySetId.size());
-        for (size_t i = 0; i < mKeySets.size(); ++i) {
-            if (memcmp(mKeySets[i].array(), keySetId.array(), keySetId.size()) == 0) {
-                return i;
-            }
-        }
-        return kNotFound;
-    }
-
-
-    // Conversion utilities
-    String8 MockDrmPlugin::vectorToString(Vector<uint8_t> const &vector) const
-    {
-        return arrayToString(vector.array(), vector.size());
-    }
-
-    String8 MockDrmPlugin::arrayToString(uint8_t const *array, size_t len) const
-    {
-        String8 result("{ ");
-        for (size_t i = 0; i < len; i++) {
-            result.appendFormat("0x%02x ", array[i]);
-        }
-        result += "}";
-        return result;
-    }
-
-    String8 MockDrmPlugin::stringMapToString(KeyedVector<String8, String8> map) const
-    {
-        String8 result("{ ");
-        for (size_t i = 0; i < map.size(); i++) {
-            result.appendFormat("%s{name=%s, value=%s}", i > 0 ? ", " : "",
-                                map.keyAt(i).string(), map.valueAt(i).string());
-        }
-        return result + " }";
-    }
-
-    bool operator<(Vector<uint8_t> const &lhs, Vector<uint8_t> const &rhs) {
-        return lhs.size() < rhs.size() || (memcmp(lhs.array(), rhs.array(), lhs.size()) < 0);
-    }
-
-    //
-    // Crypto Plugin
-    //
-
-    bool MockCryptoPlugin::requiresSecureDecoderComponent(const char *mime) const
-    {
-        ALOGD("MockCryptoPlugin::requiresSecureDecoderComponent(mime=%s)", mime);
-        return false;
-    }
-
-    ssize_t
-    MockCryptoPlugin::decrypt(bool secure, const uint8_t key[16], const uint8_t iv[16],
-                              Mode mode, const void *srcPtr, const SubSample *subSamples,
-                              size_t numSubSamples, void *dstPtr, AString *errorDetailMsg)
-    {
-        ALOGD("MockCryptoPlugin::decrypt(secure=%d, key=%s, iv=%s, mode=%d, src=%p, "
-              "subSamples=%s, dst=%p)",
-              (int)secure,
-              arrayToString(key, sizeof(key)).string(),
-              arrayToString(iv, sizeof(iv)).string(),
-              (int)mode, srcPtr,
-              subSamplesToString(subSamples, numSubSamples).string(),
-              dstPtr);
-        return OK;
-    }
-
-    // Conversion utilities
-    String8 MockCryptoPlugin::arrayToString(uint8_t const *array, size_t len) const
-    {
-        String8 result("{ ");
-        for (size_t i = 0; i < len; i++) {
-            result.appendFormat("0x%02x ", array[i]);
-        }
-        result += "}";
-        return result;
-    }
-
-    String8 MockCryptoPlugin::subSamplesToString(SubSample const *subSamples,
-                                                 size_t numSubSamples) const
-    {
-        String8 result;
-        for (size_t i = 0; i < numSubSamples; i++) {
-            result.appendFormat("[%d] {clear:%d, encrypted:%d} ", i,
-                                subSamples[i].mNumBytesOfClearData,
-                                subSamples[i].mNumBytesOfEncryptedData);
-        }
-        return result;
-    }
-
-};
diff --git a/tests/tests/mediadrm/lib/MockDrmCryptoPlugin.h b/tests/tests/mediadrm/lib/MockDrmCryptoPlugin.h
deleted file mode 100644
index 2297f9b..0000000
--- a/tests/tests/mediadrm/lib/MockDrmCryptoPlugin.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2013 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 <utils/Mutex.h>
-
-#include "drm/DrmAPI.h"
-#include "hardware/CryptoAPI.h"
-
-extern "C" {
-      android::DrmFactory *createDrmFactory();
-      android::CryptoFactory *createCryptoFactory();
-}
-
-namespace android {
-
-    class MockDrmFactory : public DrmFactory {
-    public:
-        MockDrmFactory() {}
-        virtual ~MockDrmFactory() {}
-
-        bool isCryptoSchemeSupported(const uint8_t uuid[16]);
-        bool isContentTypeSupported(const String8 &mimeType);
-        status_t createDrmPlugin(const uint8_t uuid[16], DrmPlugin **plugin);
-    };
-
-    class MockCryptoFactory : public CryptoFactory {
-    public:
-        MockCryptoFactory() {}
-        virtual ~MockCryptoFactory() {}
-
-        bool isCryptoSchemeSupported(const uint8_t uuid[16]) const;
-        status_t createPlugin(
-            const uint8_t uuid[16], const void *data, size_t size,
-            CryptoPlugin **plugin);
-    };
-
-
-
-    class MockDrmPlugin : public DrmPlugin {
-    public:
-        MockDrmPlugin() {}
-        virtual ~MockDrmPlugin() {}
-
-        // from DrmPlugin
-        status_t openSession(Vector<uint8_t> &sessionId);
-        status_t closeSession(Vector<uint8_t> const &sessionId);
-
-        status_t getKeyRequest(Vector<uint8_t> const &sessionId,
-                               Vector<uint8_t> const &initData,
-                               String8 const &mimeType, KeyType keyType,
-                               KeyedVector<String8, String8> const &optionalParameters,
-                               Vector<uint8_t> &request, String8 &defaultUrl);
-
-        status_t provideKeyResponse(Vector<uint8_t> const &sessionId,
-                                    Vector<uint8_t> const &response,
-                                    Vector<uint8_t> &keySetId);
-
-        status_t removeKeys(Vector<uint8_t> const &keySetId);
-
-        status_t restoreKeys(Vector<uint8_t> const &sessionId,
-                             Vector<uint8_t> const &keySetId);
-
-        status_t queryKeyStatus(Vector<uint8_t> const &sessionId,
-                                KeyedVector<String8, String8> &infoMap) const;
-
-        status_t getProvisionRequest(Vector<uint8_t> &request,
-                                             String8 &defaultUrl);
-
-        status_t provideProvisionResponse(Vector<uint8_t> const &response);
-
-        status_t getSecureStops(List<Vector<uint8_t> > &secureStops);
-        status_t releaseSecureStops(Vector<uint8_t> const &ssRelease);
-
-        status_t getPropertyString(String8 const &name, String8 &value ) const;
-        status_t getPropertyByteArray(String8 const &name,
-                                              Vector<uint8_t> &value ) const;
-
-        status_t setPropertyString(String8 const &name,
-                                   String8 const &value );
-        status_t setPropertyByteArray(String8 const &name,
-                                      Vector<uint8_t> const &value );
-
-        status_t setCipherAlgorithm(Vector<uint8_t> const &sessionId,
-                                    String8 const &algorithm);
-
-        status_t setMacAlgorithm(Vector<uint8_t> const &sessionId,
-                                 String8 const &algorithm);
-
-        status_t encrypt(Vector<uint8_t> const &sessionId,
-                         Vector<uint8_t> const &keyId,
-                         Vector<uint8_t> const &input,
-                         Vector<uint8_t> const &iv,
-                         Vector<uint8_t> &output);
-
-        status_t decrypt(Vector<uint8_t> const &sessionId,
-                         Vector<uint8_t> const &keyId,
-                         Vector<uint8_t> const &input,
-                         Vector<uint8_t> const &iv,
-                         Vector<uint8_t> &output);
-
-        status_t sign(Vector<uint8_t> const &sessionId,
-                      Vector<uint8_t> const &keyId,
-                      Vector<uint8_t> const &message,
-                      Vector<uint8_t> &signature);
-
-        status_t verify(Vector<uint8_t> const &sessionId,
-                        Vector<uint8_t> const &keyId,
-                        Vector<uint8_t> const &message,
-                        Vector<uint8_t> const &signature,
-                        bool &match);
-
-    private:
-        String8 vectorToString(Vector<uint8_t> const &vector) const;
-        String8 arrayToString(uint8_t const *array, size_t len) const;
-        String8 stringMapToString(KeyedVector<String8, String8> map) const;
-
-        SortedVector<Vector<uint8_t> > mSessions;
-        SortedVector<Vector<uint8_t> > mKeySets;
-
-        static const ssize_t kNotFound = -1;
-        ssize_t findSession(Vector<uint8_t> const &sessionId) const;
-        ssize_t findKeySet(Vector<uint8_t> const &keySetId) const;
-
-        Mutex mLock;
-        KeyedVector<String8, String8> mStringProperties;
-        KeyedVector<String8, Vector<uint8_t> > mByteArrayProperties;
-    };
-
-
-    class MockCryptoPlugin : public CryptoPlugin {
-
-        bool requiresSecureDecoderComponent(const char *mime) const;
-
-        ssize_t decrypt(bool secure,
-            const uint8_t key[16], const uint8_t iv[16],
-            Mode mode, const void *srcPtr,
-            const SubSample *subSamples, size_t numSubSamples,
-            void *dstPtr, AString *errorDetailMsg);
-    private:
-        String8 subSamplesToString(CryptoPlugin::SubSample const *subSamples, size_t numSubSamples) const;
-        String8 arrayToString(uint8_t const *array, size_t len) const;
-    };
-};
diff --git a/tests/tests/net/src/android/net/cts/TrafficStatsTest.java b/tests/tests/net/src/android/net/cts/TrafficStatsTest.java
index 180d259..9483bdc 100644
--- a/tests/tests/net/src/android/net/cts/TrafficStatsTest.java
+++ b/tests/tests/net/src/android/net/cts/TrafficStatsTest.java
@@ -19,7 +19,11 @@
 import android.net.TrafficStats;
 import android.os.Process;
 import android.test.AndroidTestCase;
+import android.util.Log;
 
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -29,6 +33,8 @@
 import java.util.concurrent.TimeUnit;
 
 public class TrafficStatsTest extends AndroidTestCase {
+    private static final String LOG_TAG = "TrafficStatsTest";
+
     public void testValidMobileStats() {
         // We can't assume a mobile network is even present in this test, so
         // we simply assert that a valid value is returned.
@@ -75,19 +81,39 @@
         return packetCount * (20 + 32 + bytes);
     }
 
+    private void accessOwnTrafficStats() throws IOException {
+        final int ownAppUid = getContext().getApplicationInfo().uid;
+        Log.d(LOG_TAG, "accesOwnTrafficStatsWithTags(): about to read qtaguid stats for own uid " + ownAppUid);
+
+        boolean foundOwnDetailedStats = false;
+        try {
+            BufferedReader qtaguidReader = new BufferedReader(new FileReader("/proc/net/xt_qtaguid/stats"));
+            String line;
+            while ((line = qtaguidReader.readLine()) != null) {
+                String tokens[] = line.split(" ");
+                if (tokens.length > 3 && tokens[3].equals(String.valueOf(ownAppUid))) {
+                    Log.d(LOG_TAG, "accessOwnTrafficStatsWithTags(): got own stats: " + line);
+                }
+            }
+            qtaguidReader.close();
+        } catch (FileNotFoundException e) {
+            fail("Was not able to access qtaguid/stats: " + e);
+        }
+    }
+
     public void testTrafficStatsForLocalhost() throws IOException {
-        long mobileTxPacketsBefore = TrafficStats.getMobileTxPackets();
-        long mobileRxPacketsBefore = TrafficStats.getMobileRxPackets();
-        long mobileTxBytesBefore = TrafficStats.getMobileTxBytes();
-        long mobileRxBytesBefore = TrafficStats.getMobileRxBytes();
-        long totalTxPacketsBefore = TrafficStats.getTotalTxPackets();
-        long totalRxPacketsBefore = TrafficStats.getTotalRxPackets();
-        long totalTxBytesBefore = TrafficStats.getTotalTxBytes();
-        long totalRxBytesBefore = TrafficStats.getTotalRxBytes();
-        long uidTxBytesBefore = TrafficStats.getUidTxBytes(Process.myUid());
-        long uidRxBytesBefore = TrafficStats.getUidRxBytes(Process.myUid());
-        long uidTxPacketsBefore = TrafficStats.getUidTxPackets(Process.myUid());
-        long uidRxPacketsBefore = TrafficStats.getUidRxPackets(Process.myUid());
+        final long mobileTxPacketsBefore = TrafficStats.getMobileTxPackets();
+        final long mobileRxPacketsBefore = TrafficStats.getMobileRxPackets();
+        final long mobileTxBytesBefore = TrafficStats.getMobileTxBytes();
+        final long mobileRxBytesBefore = TrafficStats.getMobileRxBytes();
+        final long totalTxPacketsBefore = TrafficStats.getTotalTxPackets();
+        final long totalRxPacketsBefore = TrafficStats.getTotalRxPackets();
+        final long totalTxBytesBefore = TrafficStats.getTotalTxBytes();
+        final long totalRxBytesBefore = TrafficStats.getTotalRxBytes();
+        final long uidTxBytesBefore = TrafficStats.getUidTxBytes(Process.myUid());
+        final long uidRxBytesBefore = TrafficStats.getUidRxBytes(Process.myUid());
+        final long uidTxPacketsBefore = TrafficStats.getUidTxPackets(Process.myUid());
+        final long uidRxPacketsBefore = TrafficStats.getUidRxPackets(Process.myUid());
 
         // Transfer 1MB of data across an explicitly localhost socket.
         final int byteCount = 1024;
@@ -104,22 +130,36 @@
                     socket.setTcpNoDelay(true);
                     OutputStream out = socket.getOutputStream();
                     byte[] buf = new byte[byteCount];
+                    TrafficStats.setThreadStatsTag(0x42);
+                    TrafficStats.tagSocket(socket);
+                    accessOwnTrafficStats();
                     for (int i = 0; i < packetCount; i++) {
                         out.write(buf);
                         out.flush();
+                        try {
+                            // Bug: 10668088, Even with Nagle disabled, and flushing the 1024 bytes
+                            // the kernel still regroups data into a larger packet.
+                            Thread.sleep(5);
+                        } catch (InterruptedException e) {
+                        }
                     }
                     out.close();
                     socket.close();
+                    accessOwnTrafficStats();
                 } catch (IOException e) {
+                    Log.i(LOG_TAG, "Badness during writes to socket: " + e);
                 }
             }
         }.start();
 
+        int read = 0;
         try {
             Socket socket = server.accept();
+            socket.setTcpNoDelay(true);
+            TrafficStats.setThreadStatsTag(0x43);
+            TrafficStats.tagSocket(socket);
             InputStream in = socket.getInputStream();
             byte[] buf = new byte[byteCount];
-            int read = 0;
             while (read < byteCount * packetCount) {
                 int n = in.read(buf);
                 assertTrue("Unexpected EOF", n > 0);
@@ -128,6 +168,7 @@
         } finally {
             server.close();
         }
+        assertTrue("Not all data read back", read >= byteCount * packetCount);
 
         // It's too fast to call getUidTxBytes function.
         try {
@@ -163,18 +204,30 @@
          *   + 7 approx.: syn, syn-ack, ack, fin-ack, ack, fin-ack, ack;
          *   but sometimes the last find-acks just vanish, so we set a lower limit of +5.
          */
-        assertTrue("uidtxp: " + uidTxPacketsBefore + " -> " + uidTxPacketsAfter + " delta=" + uidTxDeltaPackets,
-            uidTxDeltaPackets >= packetCount + 5 &&
-            uidTxDeltaPackets <= packetCount + packetCount + 7);
-        assertTrue("uidrxp: " + uidRxPacketsBefore + " -> " + uidRxPacketsAfter + " delta=" + uidRxDeltaPackets,
-            uidRxDeltaPackets >= packetCount + 5 &&
-            uidRxDeltaPackets <= packetCount + packetCount + 7);
-        assertTrue("uidtxb: " + uidTxBytesBefore + " -> " + uidTxBytesAfter + " delta=" + uidTxDeltaBytes,
-            uidTxDeltaBytes >= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(5, 0) &&
-            uidTxDeltaBytes <= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(packetCount + 7, 0));
-        assertTrue("uidrxb: " + uidRxBytesBefore + " -> " + uidRxBytesAfter + " delta=" + uidRxDeltaBytes,
-            uidRxDeltaBytes >= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(5, 0) &&
-            uidRxDeltaBytes <= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(packetCount + 7, 0));
+        final int maxExpectedExtraPackets = 7;
+        final int minExpectedExtraPackets = 5;
+
+
+        assertTrue("uidtxp: " + uidTxPacketsBefore + " -> " + uidTxPacketsAfter + " delta=" + uidTxDeltaPackets +
+            " Wanted: " + uidTxDeltaPackets + ">=" + packetCount + "+" + minExpectedExtraPackets + " && " +
+            uidTxDeltaPackets + "<=" + packetCount + "+" + packetCount + "+" + maxExpectedExtraPackets,
+            uidTxDeltaPackets >= packetCount + minExpectedExtraPackets &&
+            uidTxDeltaPackets <= packetCount + packetCount + maxExpectedExtraPackets);
+        assertTrue("uidrxp: " + uidRxPacketsBefore + " -> " + uidRxPacketsAfter + " delta=" + uidRxDeltaPackets +
+            " Wanted: " + uidRxDeltaPackets + ">=" + packetCount + "+" + minExpectedExtraPackets + " && " +
+            uidRxDeltaPackets + "<=" + packetCount + "+" + packetCount + "+" + maxExpectedExtraPackets,
+            uidRxDeltaPackets >= packetCount + minExpectedExtraPackets &&
+            uidRxDeltaPackets <= packetCount + packetCount + maxExpectedExtraPackets);
+        assertTrue("uidtxb: " + uidTxBytesBefore + " -> " + uidTxBytesAfter + " delta=" + uidTxDeltaBytes +
+            " Wanted: " + uidTxDeltaBytes + ">=" + tcpPacketToIpBytes(packetCount, byteCount) + "+" + tcpPacketToIpBytes(minExpectedExtraPackets, 0) + " && " +
+            uidTxDeltaBytes + "<=" + tcpPacketToIpBytes(packetCount, byteCount) + "+" + tcpPacketToIpBytes(packetCount + maxExpectedExtraPackets, 0),
+            uidTxDeltaBytes >= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(minExpectedExtraPackets, 0) &&
+            uidTxDeltaBytes <= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(packetCount + maxExpectedExtraPackets, 0));
+        assertTrue("uidrxb: " + uidRxBytesBefore + " -> " + uidRxBytesAfter + " delta=" + uidRxDeltaBytes +
+            " Wanted: " + uidRxDeltaBytes + ">=" + tcpPacketToIpBytes(packetCount, byteCount) + "+" + tcpPacketToIpBytes(minExpectedExtraPackets, 0) + " && " +
+            uidRxDeltaBytes + "<=" + tcpPacketToIpBytes(packetCount, byteCount) + "+" + tcpPacketToIpBytes(packetCount + maxExpectedExtraPackets, 0),
+            uidRxDeltaBytes >= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(minExpectedExtraPackets, 0) &&
+            uidRxDeltaBytes <= tcpPacketToIpBytes(packetCount, byteCount) + tcpPacketToIpBytes(packetCount + maxExpectedExtraPackets, 0));
 
         // Localhost traffic *does* count against total stats.
         // Fudge by 132 packets of 1500 bytes not related to the test.
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index db88cea..08f08d7 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -397,6 +397,7 @@
                     "/data/data/recovery/HTCFOTA",
                     "/data/data/recovery/OMADM",
                     "/data/data/shared",
+                    "/data/diag_logs",
                     "/data/dontpanic",
                     "/data/drm",
                     "/data/drm/fwdlock",
@@ -464,6 +465,7 @@
                     "/data/property",
                     "/data/radio",
                     "/data/secure",
+                    "/data/security",
                     "/data/sensors",
                     "/data/shared",
                     "/data/simcom",
@@ -472,6 +474,7 @@
                     "/data/system",
                     "/data/tmp",
                     "/data/tombstones",
+                    "/data/tombstones/ramdump",
                     "/data/tpapi",
                     "/data/tpapi/etc",
                     "/data/tpapi/etc/tpa",
diff --git a/tests/tests/provider/src/android/provider/cts/TelephonyProviderTest.java b/tests/tests/provider/src/android/provider/cts/TelephonyProviderTest.java
new file mode 100644
index 0000000..e352252
--- /dev/null
+++ b/tests/tests/provider/src/android/provider/cts/TelephonyProviderTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 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.provider.cts;
+
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.net.Uri;
+import android.os.ParcelFileDescriptor;
+import android.test.InstrumentationTestCase;
+
+import java.lang.reflect.Field;
+
+import java.io.FileDescriptor;
+
+// To run the tests in this file w/o running all the cts tests:
+// build cts
+// cts-tradefed
+// run cts -c android.provider.cts.TelephonyProviderTest
+
+public class TelephonyProviderTest extends InstrumentationTestCase {
+    private ContentResolver mContentResolver;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mContentResolver = getInstrumentation().getTargetContext().getContentResolver();
+    }
+
+    // Test that the TelephonyProvider doesn't allow clients to update _data column data and
+    // if they can, that they can't abuse the provider to open an arbitrary file.
+    public void testOpeningAnyFile() {
+        Uri uri = Uri.parse("content://mms/100/part");
+        try {
+            ContentValues values2 = new ContentValues();
+            values2.put("_data", "/dev/urandom");
+            Uri uri2 = mContentResolver.insert(uri, values2);
+            assertEquals("The code was able to insert the _data column", null, uri2);
+            if (uri2 == null) {
+                return;
+            }
+            ContentValues values = new ContentValues();
+            values.put("_data", "/dev/urandom");
+            int rowCnt = mContentResolver.update(uri2, values, null, null);
+            assertEquals("Was able to update the _data column", 0, rowCnt);
+
+            ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(uri2, "rw");
+            pfd.getFileDescriptor();
+            FileDescriptor fd = pfd.getFileDescriptor();
+            Field fld = fd.getClass().getDeclaredField("descriptor");
+            fld.setAccessible(true);
+            int fint  = fld.getInt(fd);
+            fail("The code was able to abuse the MmsProvider to open any file");
+        } catch(Exception e){
+            e.printStackTrace();
+        }
+    }
+}
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AcosPiTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AcosPiTest.java
index cc82f0c..9d0bc7d 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/AcosPiTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AcosPiTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testAcosPiF32_relaxed() {
-        doF32_relaxed(0xe1, 5);
+        doF32_relaxed(0xe1, 128);
     }
 
     public void testAcosPiF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testAcosPiF32_2_relaxed() {
-        doF32_2_relaxed(0xa123, 5);
+        doF32_2_relaxed(0xa123, 128);
     }
 
     public void testAcosPiF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testAcosPiF32_3_relaxed() {
-        doF32_3_relaxed(0x123, 5);
+        doF32_3_relaxed(0x123, 128);
     }
 
     public void testAcosPiF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testAcosPiF32_4_relaxed() {
-        doF32_4_relaxed(0x123ef, 5);
+        doF32_4_relaxed(0x123ef, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AcosTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AcosTest.java
index 57490b2..d540c60 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/AcosTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AcosTest.java
@@ -92,19 +92,19 @@
     }
 
     public void testAcosF32_relaxed() {
-        doF32_relaxed(0x123e, 4);
+        doF32_relaxed(0x123e, 128);
     }
 
     public void testAcosF32_2_relaxed() {
-        doF32_2_relaxed(0x1e, 4);
+        doF32_2_relaxed(0x1e, 128);
     }
 
     public void testAcosF32_3_relaxed() {
-        doF32_3_relaxed(0xeaf, 4);
+        doF32_3_relaxed(0xeaf, 128);
     }
 
     public void testAcosF32_4_relaxed() {
-        doF32_4_relaxed(0x123, 4);
+        doF32_4_relaxed(0x123, 128);
     }
 
 
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AsinTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AsinTest.java
index d7a1575..7f3c367 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/AsinTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AsinTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testAsinF32_relaxed() {
-        doF32_relaxed(0x12efa, 4);
+        doF32_relaxed(0x12efa, 128);
     }
 
     public void testAsinF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testAsinF32_2_relaxed() {
-        doF32_2_relaxed(0x34ef, 4);
+        doF32_2_relaxed(0x34ef, 128);
     }
 
     public void testAsinF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testAsinF32_3_relaxed() {
-        doF32_3_relaxed(0xae31, 4);
+        doF32_3_relaxed(0xae31, 128);
     }
 
     public void testAsinF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testAsinF32_4_relaxed() {
-        doF32_4_relaxed(0x341, 4);
+        doF32_4_relaxed(0x341, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AsinhTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AsinhTest.java
index f5b8a9b..e0204d2 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/AsinhTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AsinhTest.java
@@ -81,7 +81,7 @@
     }
 
     public void testAsinhF32_relaxed() {
-        doF32_relaxed(0x12, 4);
+        doF32_relaxed(0x12, 128);
     }
 
     public void testAsinhF32_2() {
@@ -89,7 +89,7 @@
     }
 
     public void testAsinhF32_2_relaxed() {
-        doF32_2_relaxed(0xead, 4);
+        doF32_2_relaxed(0xead, 128);
     }
 
     public void testAsinhF32_3() {
@@ -97,7 +97,7 @@
     }
 
     public void testAsinhF32_3_relaxed() {
-        doF32_3_relaxed(0xabc, 4);
+        doF32_3_relaxed(0xabc, 128);
     }
 
     public void testAsinhF32_4() {
@@ -105,7 +105,7 @@
 
     }
     public void testAsinhF32_4_relaxed() {
-        doF32_4_relaxed(0xfea, 4);
+        doF32_4_relaxed(0xfea, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Atan2PiTest.java b/tests/tests/renderscript/src/android/renderscript/cts/Atan2PiTest.java
index 5cbd868..f96e7d6 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Atan2PiTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Atan2PiTest.java
@@ -95,7 +95,7 @@
     public void testAtan2PiF32_relaxed() {
         ScriptField_atan2pi_float_input in = new ScriptField_atan2pi_float_input(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_relaxed(0x12678, 6);
+        doF32_relaxed(0x12678, 128);
     }
 
     public void testAtan2PiF32_2() {
@@ -107,7 +107,7 @@
     public void testAtan2PiF32_2_relaxed() {
         ScriptField_atan2pi_float2_input in = new ScriptField_atan2pi_float2_input(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_2_relaxed(0x1af45, 6);
+        doF32_2_relaxed(0x1af45, 128);
     }
 
     public void testAtan2PiF32_3() {
@@ -119,7 +119,7 @@
     public void testAtan2PiF32_3_relaxed() {
         ScriptField_atan2pi_float3_input in = new ScriptField_atan2pi_float3_input(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_3_relaxed(0x1cd345, 6);
+        doF32_3_relaxed(0x1cd345, 128);
     }
 
     public void testAtan2PiF32_4() {
@@ -131,6 +131,6 @@
     public void testAtan2PiF32_4_relaxed() {
         ScriptField_atan2pi_float4_input in = new ScriptField_atan2pi_float4_input(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_4_relaxed(0x1ca45, 6);
+        doF32_4_relaxed(0x1ca45, 128);
     }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Atan2Test.java b/tests/tests/renderscript/src/android/renderscript/cts/Atan2Test.java
index 9eead6d..c3eabb7 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Atan2Test.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Atan2Test.java
@@ -95,7 +95,7 @@
     public void testAtan2F32_relaxed() {
         ScriptField_atan2_f32_in in = new ScriptField_atan2_f32_in(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_relaxed(0x12678, 6);
+        doF32_relaxed(0x12678, 128);
     }
 
     public void testAtan2F32_2() {
@@ -107,7 +107,7 @@
     public void testAtan2F32_2_relaxed() {
         ScriptField_atan2_f32_2_in in = new ScriptField_atan2_f32_2_in(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_2_relaxed(0x1af45, 6);
+        doF32_2_relaxed(0x1af45, 128);
     }
 
     public void testAtan2F32_3() {
@@ -119,7 +119,7 @@
     public void testAtan2F32_3_relaxed() {
         ScriptField_atan2_f32_3_in in = new ScriptField_atan2_f32_3_in(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_3_relaxed(0x1cd345, 6);
+        doF32_3_relaxed(0x1cd345, 128);
     }
 
     public void testAtan2F32_4() {
@@ -131,6 +131,6 @@
     public void testAtan2F32_4_relaxed() {
         ScriptField_atan2_f32_4_in in = new ScriptField_atan2_f32_4_in(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_4_relaxed(0x1ca45, 6);
+        doF32_4_relaxed(0x1ca45, 128);
     }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AtanPiTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AtanPiTest.java
index 1fbd6dd..17fe5ad 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/AtanPiTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AtanPiTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testAtanPiF32_relaxed() {
-        doF32_relaxed(0x123, 5);
+        doF32_relaxed(0x123, 128);
     }
 
     public void testAtanPiF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testAtanPiF32_2_relaxed() {
-        doF32_2_relaxed(0x12, 5);
+        doF32_2_relaxed(0x12, 128);
     }
 
     public void testAtanPiF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testAtanPiF32_3_relaxed() {
-        doF32_3_relaxed(0x847, 5);
+        doF32_3_relaxed(0x847, 128);
     }
 
     public void testAtanPiF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testAtanPiF32_4_relaxed() {
-        doF32_4_relaxed(0xfa2, 5);
+        doF32_4_relaxed(0xfa2, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AtanTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AtanTest.java
index a02cd23..c41be40 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/AtanTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AtanTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testAtanF32_relaxed() {
-        doF32_relaxed(0x12a, 5);
+        doF32_relaxed(0x12a, 128);
     }
 
     public void testAtanF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testAtanF32_2_relaxed() {
-        doF32_2_relaxed(0xad, 5);
+        doF32_2_relaxed(0xad, 128);
     }
 
     public void testAtanF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testAtanF32_3_relaxed() {
-        doF32_3_relaxed(0xafe, 5);
+        doF32_3_relaxed(0xafe, 128);
     }
 
     public void testAtanF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testAtanF32_4_relaxed() {
-        doF32_4_relaxed(0x1238, 5);
+        doF32_4_relaxed(0x1238, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/AtanhTest.java b/tests/tests/renderscript/src/android/renderscript/cts/AtanhTest.java
index d9753b3..7182251 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/AtanhTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/AtanhTest.java
@@ -81,7 +81,7 @@
     }
 
     public void testAtanhF32_relaxed() {
-        doF32_relaxed(0xace, 5);
+        doF32_relaxed(0xace, 128);
     }
 
     public void testAtanhF32_2() {
@@ -89,7 +89,7 @@
     }
 
     public void testAtanhF32_2_relaxed() {
-        doF32_2_relaxed(0xdae, 5);
+        doF32_2_relaxed(0xdae, 128);
     }
 
     public void testAtanhF32_3() {
@@ -97,7 +97,7 @@
     }
 
     public void testAtanhF32_3_relaxed() {
-        doF32_3_relaxed(0x123, 5);
+        doF32_3_relaxed(0x123, 128);
     }
 
     public void testAtanhF32_4() {
@@ -105,7 +105,7 @@
 
     }
     public void testAtanhF32_4_relaxed() {
-        doF32_4_relaxed(0x6480, 5);
+        doF32_4_relaxed(0x6480, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/CbrtTest.java b/tests/tests/renderscript/src/android/renderscript/cts/CbrtTest.java
index 374daba..603794a 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/CbrtTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/CbrtTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testCbrtF32_relaxed() {
-        doF32_relaxed(0xabe, 2);
+        doF32_relaxed(0xabe, 128);
     }
 
     public void testCbrtF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testCbrtF32_2_relaxed() {
-        doF32_2_relaxed(0x78, 2);
+        doF32_2_relaxed(0x78, 128);
     }
 
     public void testCbrtF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testCbrtF32_3_relaxed() {
-        doF32_3_relaxed(0x1e, 2);
+        doF32_3_relaxed(0x1e, 128);
     }
 
     public void testCbrtF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testCbrtF32_4_relaxed() {
-        doF32_4_relaxed(0xfe2, 2);
+        doF32_4_relaxed(0xfe2, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/CeilTest.java b/tests/tests/renderscript/src/android/renderscript/cts/CeilTest.java
index 4f2750f..5d64b95 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/CeilTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/CeilTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testCeilF32_relaxed() {
-        doF32_relaxed(0x12345ace, 0);
+        doF32_relaxed(0x12345ace, 1);
     }
 
     public void testCeilF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testCeilF32_2_relaxed() {
-        doF32_2_relaxed(0x1ac478, 0);
+        doF32_2_relaxed(0x1ac478, 1);
     }
 
     public void testCeilF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testCeilF32_3_relaxed() {
-        doF32_3_relaxed(0xacef, 0);
+        doF32_3_relaxed(0xacef, 1);
     }
 
     public void testCeilF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testCeilF32_4_relaxed() {
-        doF32_4_relaxed(0xef12, 0);
+        doF32_4_relaxed(0xef12, 1);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/CoshTest.java b/tests/tests/renderscript/src/android/renderscript/cts/CoshTest.java
index 6762921..9fa3603 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/CoshTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/CoshTest.java
@@ -81,7 +81,7 @@
     }
 
     public void testCoshF32_relaxed() {
-        doF32_relaxed(0xfe, 4);
+        doF32_relaxed(0xfe, 128);
     }
 
     public void testCoshF32_2() {
@@ -89,7 +89,7 @@
     }
 
     public void testCoshF32_2_relaxed() {
-        doF32_2_relaxed(0x71, 4);
+        doF32_2_relaxed(0x71, 128);
     }
 
     public void testCoshF32_3() {
@@ -97,7 +97,7 @@
     }
 
     public void testCoshF32_3_relaxed() {
-        doF32_3_relaxed(0xa, 4);
+        doF32_3_relaxed(0xa, 128);
     }
 
     public void testCoshF32_4() {
@@ -105,7 +105,7 @@
 
     }
     public void testCoshF32_4_relaxed() {
-        doF32_4_relaxed(0xabe, 4);
+        doF32_4_relaxed(0xabe, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/CrossTest.java b/tests/tests/renderscript/src/android/renderscript/cts/CrossTest.java
index a5bc267..43a036b 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/CrossTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/CrossTest.java
@@ -89,7 +89,7 @@
     public void testCrossF32_3_relaxed() {
         ScriptField__cross_f32_3_struct in = new ScriptField__cross_f32_3_struct(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_3_relaxed(0x12345678, 0);
+        doF32_3_relaxed(0x12345678, 2);
     }
 
 
@@ -105,7 +105,7 @@
     public void testCrossF32_4_relaxed() {
         ScriptField__cross_f32_4_struct in = new ScriptField__cross_f32_4_struct(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_4_relaxed(0x12ac5678, 0);
+        doF32_4_relaxed(0x12ac5678, 2);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Exp10Test.java b/tests/tests/renderscript/src/android/renderscript/cts/Exp10Test.java
index d8ab93a..875af18 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Exp10Test.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Exp10Test.java
@@ -80,7 +80,7 @@
     }
 
     public void testExp10F32_relaxed() {
-        doF32_relaxed(0x81, 3);
+        doF32_relaxed(0x81, 16);
     }
 
     public void testExp10F32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testExp10F32_2_relaxed() {
-        doF32_2_relaxed(0xa42, 3);
+        doF32_2_relaxed(0xa42, 16);
     }
 
     public void testExp10F32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testExp10F32_3_relaxed() {
-        doF32_3_relaxed(0xace2, 3);
+        doF32_3_relaxed(0xace2, 16);
     }
 
     public void testExp10F32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testExp10F32_4_relaxed() {
-        doF32_4_relaxed(0x918, 3);
+        doF32_4_relaxed(0x918, 16);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Exp2Test.java b/tests/tests/renderscript/src/android/renderscript/cts/Exp2Test.java
index 108c273..ac99b92 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Exp2Test.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Exp2Test.java
@@ -80,7 +80,7 @@
     }
 
     public void testExp2F32_relaxed() {
-        doF32_relaxed(0xa6, 3);
+        doF32_relaxed(0xa6, 16);
     }
 
     public void testExp2F32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testExp2F32_2_relaxed() {
-        doF32_2_relaxed(0xab2, 3);
+        doF32_2_relaxed(0xab2, 16);
     }
 
     public void testExp2F32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testExp2F32_3_relaxed() {
-        doF32_3_relaxed(0x617a, 3);
+        doF32_3_relaxed(0x617a, 16);
     }
 
     public void testExp2F32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testExp2F32_4_relaxed() {
-        doF32_4_relaxed(0xabc3, 3);
+        doF32_4_relaxed(0xabc3, 16);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ExpTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ExpTest.java
index 6f85873..e2f86ca 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/ExpTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/ExpTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testExpF32_relaxed() {
-        doF32_relaxed(0xa28, 3);
+        doF32_relaxed(0xa28, 16);
     }
 
     public void testExpF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testExpF32_2_relaxed() {
-        doF32_2_relaxed(0xfeb4, 3);
+        doF32_2_relaxed(0xfeb4, 16);
     }
 
     public void testExpF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testExpF32_3_relaxed() {
-        doF32_3_relaxed(0xab2, 3);
+        doF32_3_relaxed(0xab2, 16);
     }
 
     public void testExpF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testExpF32_4_relaxed() {
-        doF32_4_relaxed(0x7a6, 3);
+        doF32_4_relaxed(0x7a6, 16);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Expm1Test.java b/tests/tests/renderscript/src/android/renderscript/cts/Expm1Test.java
index 1160b54..36b65ff 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Expm1Test.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Expm1Test.java
@@ -80,7 +80,7 @@
     }
 
     public void testExpm1F32_relaxed() {
-        doF32_relaxed(0xa29, 3);
+        doF32_relaxed(0xa29, 16);
     }
 
     public void testExpm1F32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testExpm1F32_2_relaxed() {
-        doF32_2_relaxed(0x8a2, 3);
+        doF32_2_relaxed(0x8a2, 16);
     }
 
     public void testExpm1F32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testExpm1F32_3_relaxed() {
-        doF32_3_relaxed(0xa7c, 3);
+        doF32_3_relaxed(0xa7c, 16);
     }
 
     public void testExpm1F32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testExpm1F32_4_relaxed() {
-        doF32_4_relaxed(0x81a, 3);
+        doF32_4_relaxed(0x81a, 16);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/FloorTest.java b/tests/tests/renderscript/src/android/renderscript/cts/FloorTest.java
index 60251ad..e7494e6 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/FloorTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/FloorTest.java
@@ -79,7 +79,7 @@
     }
 
     public void testfloorF32_relaxed() {
-        doF32_relaxed(0xa, 0);
+        doF32_relaxed(0xa, 1);
     }
 
     public void testfloorF32_2() {
@@ -87,7 +87,7 @@
     }
 
     public void testfloorF32_2_relaxed() {
-        doF32_2_relaxed(0xb, 0);
+        doF32_2_relaxed(0xb, 1);
     }
 
     public void testfloorF32_3() {
@@ -95,7 +95,7 @@
     }
 
     public void testfloorF32_3_relaxed() {
-        doF32_3_relaxed(0xef1, 0);
+        doF32_3_relaxed(0xef1, 1);
     }
 
     public void testfloorF32_4() {
@@ -103,7 +103,7 @@
 
     }
     public void testfloorF32_4_relaxed() {
-        doF32_4_relaxed(0xefa12, 0);
+        doF32_4_relaxed(0xefa12, 1);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java
index 8e43aeb..7d952f6 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicBase.java
@@ -59,26 +59,19 @@
         return e;
     }
 
-    protected void makeSource(int w, int h, Element e) {
-        System.gc();
-
-        if (mAllocSrc != null) {
-            mAllocSrc.destroy();
-        }
-        if (mAllocRef != null) {
-            mAllocRef.destroy();
-        }
-        if (mAllocDst != null) {
-            mAllocDst.destroy();
-        }
-
+    protected Allocation makeAllocation(int w, int h, Element e) {
         Type.Builder tb = new Type.Builder(mRS, e);
         tb.setX(w);
         tb.setY(h);
         Type t = tb.create();
-        mAllocSrc = Allocation.createTyped(mRS, t);
-        mAllocRef = Allocation.createTyped(mRS, t);
-        mAllocDst = Allocation.createTyped(mRS, t);
+        return Allocation.createTyped(mRS, t);
+    }
+
+    protected void makeSource(int w, int h, Element e) {
+        if (mAllocSrc != null) {
+            mAllocSrc.destroy();
+        }
+        mAllocSrc = makeAllocation(w, h, e);
 
         java.util.Random r = new java.util.Random(100);
 
@@ -111,6 +104,13 @@
 
     protected void makeBuffers(int w, int h, Element e) {
         makeSource(w, h, e);
+
+        if (mAllocRef != null) {
+            mAllocRef.destroy();
+        }
+        if (mAllocDst != null) {
+            mAllocDst.destroy();
+        }
         mAllocRef = Allocation.createTyped(mRS, mAllocSrc.getType());
         mAllocDst = Allocation.createTyped(mRS, mAllocSrc.getType());
     }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java
index 371eefb..2ac7d6f 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicColorMatrix.java
@@ -41,76 +41,110 @@
         Element eout = makeElement(dtOut, vsOut);
 
 
-        System.gc();
         makeSource(w, h, ein);
-        mAllocRef = Allocation.createTyped(mRS, mAllocSrc.getType());
-        mAllocDst = Allocation.createTyped(mRS, mAllocSrc.getType());
+        mAllocRef = makeAllocation(w, h, eout);
+        mAllocDst = makeAllocation(w, h, eout);
 
         mSi.setColorMatrix(mat);
+        mSi.setAdd(add);
         mSi.forEach(mAllocSrc, mAllocDst);
         mSr.invoke_reference(mat, add, mAllocSrc, mAllocRef);
 
-        android.util.Log.e("RSI test", "test ColorMatrix " + vsIn + " 1 " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst);
+        android.util.Log.e("RSI test", "test ColorMatrix  vsin=" + vsIn + ", vsout=" + vsOut + ",  dim " + w + ", " + h);
+        mVerify.invoke_verify(mAllocRef, mAllocDst, mAllocSrc);
         mRS.finish();
     }
 
 
-    private void test(Element.DataType dtin, Element.DataType dtout) {
+    private void test(Element.DataType dtin, Element.DataType dtout, int subtest) {
         Float4 add = new Float4();
         Matrix4f mat = new Matrix4f();
         java.util.Random r = new java.util.Random(100);
 
-        for (int t=0; t < 1; t++) {
-            float f[] = mat.getArray();
+        float f[] = mat.getArray();
+        for (int i=0; i < f.length; i++) {
+            f[i] = 0.f;
+        }
+
+
+        switch (subtest) {
+        case 0:
+            mVerify.set_gAllowedIntError(0);
+            mat.loadIdentity();
+            break;
+        case 1:
+            mVerify.set_gAllowedIntError(1);
+            mat.set(0, 0, 1.f);
+            mat.set(0, 1, 1.f);
+            mat.set(0, 2, 1.f);
+            break;
+        default:
+            mVerify.set_gAllowedIntError(2);
             for (int i=0; i < f.length; i++) {
-                f[i] = 0.f;
-            }
-
-
-            switch (t) {
-            case 0:
-                mat.loadIdentity();
-                break;
-            case 1:
-                mat.set(0, 0, 1.f);
-                mat.set(0, 1, 1.f);
-                mat.set(0, 2, 1.f);
-                break;
-            case 2:
-                for (int i=0; i < f.length; i++) {
-                    if (r.nextFloat() > 0.2f) {
-                        f[i] = 10.f * r.nextFloat();
-                    }
+                if (r.nextFloat() > 0.5f) {
+                    f[i] = r.nextFloat() * (subtest - 1);
                 }
-
             }
-
-            for (int i=1; i <= 4; i++) {
-                for (int j=1; j <=4; j++) {
-                    subtest(101, 101, mat, add,
-                            dtin, i,
-                            dtout, j);
-                    checkError();
+            for (int i=0; i < f.length; i++) {
+                if (r.nextFloat() > 0.5f) {
+                    add.x = r.nextFloat() * (subtest - 1);
                 }
+                if (r.nextFloat() > 0.5f) {
+                    add.y = r.nextFloat() * (subtest - 1);
+                }
+                if (r.nextFloat() > 0.5f) {
+                    add.z = r.nextFloat() * (subtest - 1);
+                }
+                if (r.nextFloat() > 0.5f) {
+                    add.w = r.nextFloat() * (subtest - 1);
+                }
+            }
+            android.util.Log.v("rs", "Mat [" + f[0] + ", " + f[4] + ", " + f[8] + ", " + f[12] + "]");
+            android.util.Log.v("rs", "    [" + f[1] + ", " + f[5] + ", " + f[9] + ", " + f[13] + "]");
+            android.util.Log.v("rs", "    [" + f[2] + ", " + f[6] + ", " + f[10] + ", " + f[14] + "]");
+            android.util.Log.v("rs", "    [" + f[3] + ", " + f[7] + ", " + f[11] + ", " + f[15] + "]");
+        }
+
+        for (int i=1; i <= 4; i++) {
+            for (int j=1; j <=4; j++) {
+                subtest(101, 101, mat, add,
+                        dtin, i,
+                        dtout, j);
             }
         }
+        checkError();
     }
 
-    public void test_U8_U8() {
-        test(Element.DataType.UNSIGNED_8, Element.DataType.UNSIGNED_8);
+    public void test_U8_U8_Ident() {
+        test(Element.DataType.UNSIGNED_8, Element.DataType.UNSIGNED_8, 0);
     }
 
-    public void test_F32_F32() {
-        test(Element.DataType.FLOAT_32, Element.DataType.FLOAT_32);
+    public void test_F32_F32_Ident() {
+        test(Element.DataType.FLOAT_32, Element.DataType.FLOAT_32, 0);
     }
 
-    public void test_U8_F32() {
-        test(Element.DataType.UNSIGNED_8, Element.DataType.FLOAT_32);
+    public void test_U8_F32_Ident() {
+        test(Element.DataType.UNSIGNED_8, Element.DataType.FLOAT_32, 0);
     }
 
-    public void test_F32_U8() {
-        test(Element.DataType.FLOAT_32, Element.DataType.UNSIGNED_8);
+    public void test_F32_U8_Ident() {
+        test(Element.DataType.FLOAT_32, Element.DataType.UNSIGNED_8, 0);
+    }
+
+    public void test_U8_U8_Rand() {
+        test(Element.DataType.UNSIGNED_8, Element.DataType.UNSIGNED_8, 2);
+    }
+
+    public void test_F32_F32_Rand() {
+        test(Element.DataType.FLOAT_32, Element.DataType.FLOAT_32, 10);
+    }
+
+    public void test_U8_F32_Rand() {
+        test(Element.DataType.UNSIGNED_8, Element.DataType.FLOAT_32, 10);
+    }
+
+    public void test_F32_U8_Rand() {
+        test(Element.DataType.FLOAT_32, Element.DataType.UNSIGNED_8, 10);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java
index 7354db5..12eae9a 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve3x3.java
@@ -74,7 +74,7 @@
         }
 
         android.util.Log.e("RSI test", "test convolve U8_" + vecSize + " 1 " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst);
+        mVerify.invoke_verify(mAllocRef, mAllocDst, mAllocSrc);
 
         si.setCoefficients(cf2);
         sr.set_gCoeffs(cf2);
@@ -111,7 +111,7 @@
             }
         }
         android.util.Log.e("RSI test", "test convolve U8_" + vecSize + " 2 " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst);
+        mVerify.invoke_verify(mAllocRef, mAllocDst, mAllocSrc);
         mRS.finish();
     }
 
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java
index ebdf501..482db59 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/IntrinsicConvolve5x5.java
@@ -63,7 +63,7 @@
         }
 
         android.util.Log.e("RSI test", name + "  " + e.getVectorSize() + " " + num + " " + w + ", " + h);
-        mVerify.invoke_verify(mAllocRef, mAllocDst);
+        mVerify.invoke_verify(mAllocRef, mAllocDst, mAllocSrc);
         mRS.finish();
     }
 
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Log10Test.java b/tests/tests/renderscript/src/android/renderscript/cts/Log10Test.java
index 664de50..bc571a3 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Log10Test.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Log10Test.java
@@ -80,7 +80,7 @@
     }
 
     public void testLog10F32_relaxed() {
-        doF32_relaxed(0x13, 3);
+        doF32_relaxed(0x13, 16);
     }
 
     public void testLog10F32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testLog10F32_2_relaxed() {
-        doF32_2_relaxed(0xf, 3);
+        doF32_2_relaxed(0xf, 16);
     }
 
     public void testLog10F32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testLog10F32_3_relaxed() {
-        doF32_3_relaxed(0xa, 3);
+        doF32_3_relaxed(0xa, 16);
     }
 
     public void testLog10F32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testLog10F32_4_relaxed() {
-        doF32_4_relaxed(0xf3, 3);
+        doF32_4_relaxed(0xf3, 16);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Log1PTest.java b/tests/tests/renderscript/src/android/renderscript/cts/Log1PTest.java
index dd30b29..a4daf61 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Log1PTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Log1PTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testLog1PF32_relaxed() {
-        doF32_relaxed(0xab, 2);
+        doF32_relaxed(0xab, 16);
     }
 
     public void testLog1PF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testLog1PF32_2_relaxed() {
-        doF32_2_relaxed(0x12, 2);
+        doF32_2_relaxed(0x12, 16);
     }
 
     public void testLog1PF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testLog1PF32_3_relaxed() {
-        doF32_3_relaxed(0xa1, 2);
+        doF32_3_relaxed(0xa1, 16);
     }
 
     public void testLog1PF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testLog1PF32_4_relaxed() {
-        doF32_4_relaxed(0xbae, 2);
+        doF32_4_relaxed(0xbae, 16);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/Log2Test.java b/tests/tests/renderscript/src/android/renderscript/cts/Log2Test.java
index f41e515..dd13d8d 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/Log2Test.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/Log2Test.java
@@ -80,7 +80,7 @@
     }
 
     public void testLog2F32_relaxed() {
-        doF32_relaxed(0x18a, 3);
+        doF32_relaxed(0x18a, 128);
     }
 
     public void testLog2F32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testLog2F32_2_relaxed() {
-        doF32_2_relaxed(0xfa, 3);
+        doF32_2_relaxed(0xfa, 128);
     }
 
     public void testLog2F32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testLog2F32_3_relaxed() {
-        doF32_3_relaxed(0xaef, 3);
+        doF32_3_relaxed(0xaef, 128);
     }
 
     public void testLog2F32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testLog2F32_4_relaxed() {
-        doF32_4_relaxed(0xae62, 3);
+        doF32_4_relaxed(0xae62, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/LogTest.java b/tests/tests/renderscript/src/android/renderscript/cts/LogTest.java
index 202d44a..ee03b4e 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/LogTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/LogTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testLogF32_relaxed() {
-        doF32_relaxed(0xfae, 3);
+        doF32_relaxed(0xfae, 16);
     }
 
     public void testLogF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testLogF32_2_relaxed() {
-        doF32_2_relaxed(0x123, 3);
+        doF32_2_relaxed(0x123, 16);
     }
 
     public void testLogF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testLogF32_3_relaxed() {
-        doF32_3_relaxed(0xab4, 3);
+        doF32_3_relaxed(0xab4, 16);
     }
 
     public void testLogF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testLogF32_4_relaxed() {
-        doF32_4_relaxed(0xfa3, 3);
+        doF32_4_relaxed(0xfa3, 16);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/PowTest.java b/tests/tests/renderscript/src/android/renderscript/cts/PowTest.java
index 4f5eefd..09a2e94 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/PowTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/PowTest.java
@@ -101,7 +101,7 @@
     public void testPowF32_relaxed() {
         ScriptField_PowInputData in = new ScriptField_PowInputData(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_relaxed(0x12345678, 16);
+        doF32_relaxed(0x12345678, 128);
     }
 
     public void testPowF32_2() {
@@ -113,7 +113,7 @@
     public void testPowF32_2_relaxed() {
         ScriptField_PowInputData_2 in = new ScriptField_PowInputData_2(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_2_relaxed(0x12ab78, 16);
+        doF32_2_relaxed(0x12ab78, 128);
     }
 
     public void testPowF32_3() {
@@ -125,7 +125,7 @@
     public void testPowF32_3_relaxed() {
         ScriptField_PowInputData_3 in = new ScriptField_PowInputData_3(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_3_relaxed(0x1f5678, 16);
+        doF32_3_relaxed(0x1f5678, 128);
     }
 
     public void testPowF32_4() {
@@ -137,6 +137,6 @@
     public void testPowF32_4_relaxed() {
         ScriptField_PowInputData_4 in = new ScriptField_PowInputData_4(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_4_relaxed(0xc678, 16);
+        doF32_4_relaxed(0xc678, 128);
     }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/PownTest.java b/tests/tests/renderscript/src/android/renderscript/cts/PownTest.java
index 510175d..c95a294 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/PownTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/PownTest.java
@@ -97,7 +97,7 @@
         nAlloc.copyFrom(n);
         script_f32_relaxed.set_n1(nAlloc);
 
-        doF32_relaxed(0x716acd, 16);
+        doF32_relaxed(0x716acd, 128);
     }
 
     public void testPownF32_2() {
@@ -119,7 +119,7 @@
         nAlloc.copyFrom(n);
         script_f32_relaxed.set_n2(nAlloc);
 
-        doF32_2_relaxed(0xacdef1, 16);
+        doF32_2_relaxed(0xacdef1, 128);
     }
 
     public void testPownF32_3() {
@@ -141,7 +141,7 @@
         nAlloc.copyFrom(n);
         script_f32_relaxed.set_n3(nAlloc);
 
-        doF32_3_relaxed(0xaac3f1, 16);
+        doF32_3_relaxed(0xaac3f1, 128);
     }
 
     public void testPownF32_4() {
@@ -163,6 +163,6 @@
         nAlloc.copyFrom(n);
         script_f32_relaxed.set_n4(nAlloc);
 
-        doF32_4_relaxed(0xaa12f1, 16);
+        doF32_4_relaxed(0xaa12f1, 128);
     }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/PowrTest.java b/tests/tests/renderscript/src/android/renderscript/cts/PowrTest.java
index 8432973..f10995b 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/PowrTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/PowrTest.java
@@ -101,7 +101,7 @@
     public void testPowrF32_relaxed() {
         ScriptField_PowInputData in = new ScriptField_PowInputData(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_relaxed(0x12345678, 16);
+        doF32_relaxed(0x12345678, 128);
     }
 
     public void testPowrF32_2() {
@@ -113,7 +113,7 @@
     public void testPowrF32_2_relaxed() {
         ScriptField_PowInputData_2 in = new ScriptField_PowInputData_2(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_2(0x12ab78, 16);
+        doF32_2(0x12ab78, 128);
     }
 
     public void testPowrF32_3() {
@@ -125,7 +125,7 @@
     public void testPowrF32_3_relaxed() {
         ScriptField_PowInputData_3 in = new ScriptField_PowInputData_3(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_3_relaxed(0x1f5678, 16);
+        doF32_3_relaxed(0x1f5678, 128);
     }
 
     public void testPowrF32_4() {
@@ -137,6 +137,6 @@
     public void testPowrF32_4_relaxed() {
         ScriptField_PowInputData_4 in = new ScriptField_PowInputData_4(mRS, INPUTSIZE);
         mIn = in.getAllocation();
-        doF32_4_relaxed(0xc678, 16);
+        doF32_4_relaxed(0xc678, 128);
     }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/RsFracTest.java b/tests/tests/renderscript/src/android/renderscript/cts/RsFracTest.java
index ab59e08..2185ae2 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/RsFracTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/RsFracTest.java
@@ -52,7 +52,7 @@
     }
     public void testRsFrac_relaxed() {
         mScript_relaxed = new ScriptC_rs_frac_f32_relaxed(mRS, mRes, R.raw.rs_frac_f32);
-        doF32_relaxed(0x12, 0);
+        doF32_relaxed(0x12, 1);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/ScriptGroupTest.java b/tests/tests/renderscript/src/android/renderscript/cts/ScriptGroupTest.java
index 64496ef..c9a79c8 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/ScriptGroupTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/ScriptGroupTest.java
@@ -202,13 +202,13 @@
         Type compareType = new Type.Builder(mRS, Element.I32(mRS)).create();
 
         ScriptC_scriptgroup node1, node2, node3, node4, node5, compare;
-        node1 = new ScriptC_scriptgroup(mRS, mRes, R.raw.scriptgroup);
-        node2 = new ScriptC_scriptgroup(mRS, mRes, R.raw.scriptgroup);
-        node3 = new ScriptC_scriptgroup(mRS, mRes, R.raw.scriptgroup);
-        node4 = new ScriptC_scriptgroup(mRS, mRes, R.raw.scriptgroup);
-        node5 = new ScriptC_scriptgroup(mRS, mRes, R.raw.scriptgroup);
+        node1 = new ScriptC_scriptgroup(mRS);
+        node2 = new ScriptC_scriptgroup(mRS);
+        node3 = new ScriptC_scriptgroup(mRS);
+        node4 = new ScriptC_scriptgroup(mRS);
+        node5 = new ScriptC_scriptgroup(mRS);
 
-        compare = new ScriptC_scriptgroup(mRS, mRes, R.raw.scriptgroup);
+        compare = new ScriptC_scriptgroup(mRS);
 
         Allocation in1, in2, out, resultAlloc;
         in1 = Allocation.createTyped(mRS, connect);
@@ -265,4 +265,50 @@
         assertTrue(result[0] == 2);
     }
 
+    /**
+     * Tests a case where a shared global variable is updated by the first kernel in a group,
+     * but then read by a subsequent kernel.
+     *
+     * The test ensures that we don't accidentally apply any fusion optimizations to the kernel
+     * pair, since there is a potential dependency that crosses the kernel cell boundary.
+     */
+    public void testScriptGroupSharedGlobal() {
+        Type i32 = new Type.Builder(mRS, Element.I32(mRS)).setX(1).create();
+        Type u32 = new Type.Builder(mRS, Element.U32(mRS)).setX(2).create();
+
+        Allocation aFailed = Allocation.createTyped(mRS, i32);
+        Allocation aSharedInt = Allocation.createTyped(mRS, i32);
+
+        ScriptC_group1 mG1 = new ScriptC_group1(mRS);
+        ScriptC_group2 mG2 = new ScriptC_group2(mRS);
+
+        mG1.set_aSharedInt(aSharedInt);
+        mG2.set_aSharedInt(aSharedInt);
+        mG2.set_aFailed(aFailed);
+
+        int [] Failed = new int [1];
+        Failed[0] = 0;
+        aFailed.copyFrom(Failed);
+
+        ScriptGroup.Builder b = new ScriptGroup.Builder(mRS);
+
+        // Writes to aSharedInt[x] in the kernel.
+        b.addKernel(mG1.getKernelID_setSharedInt());
+        // Reads aSharedInt[1] to verify it is -5.
+        b.addKernel(mG2.getKernelID_getSharedInt());
+        // If we fuse mG1/mG2, we won't see the update to the aSharedInt[1] during mG2 for x == 0.
+        // The update is only visible if we correctly identify the dependency and execute all of
+        // mG1 before starting on mG2.
+        b.addConnection(u32, mG1.getKernelID_setSharedInt(), mG2.getKernelID_getSharedInt());
+        ScriptGroup group = b.create();
+        group.execute();
+
+        mG2.invoke_verify();
+        aFailed.copyTo(Failed);
+        if (Failed[0] != 0) {
+            FoundError = true;
+        }
+
+        checkForErrors();
+    }
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/SinTest.java b/tests/tests/renderscript/src/android/renderscript/cts/SinTest.java
index cb43ca9..5911632 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/SinTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/SinTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testSinF32_relaxed() {
-        doF32_relaxed(0xba, 4);
+        doF32_relaxed(0xba, 128);
     }
 
     public void testSinF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testSinF32_2_relaxed() {
-        doF32_2_relaxed(0xbaa, 4);
+        doF32_2_relaxed(0xbaa, 128);
     }
 
     public void testSinF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testSinF32_3_relaxed() {
-        doF32_3_relaxed(0xca, 4);
+        doF32_3_relaxed(0xca, 128);
     }
 
     public void testSinF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testSinF32_4_relaxed() {
-        doF32_4_relaxed(0xda, 4);
+        doF32_4_relaxed(0xda, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/SinhTest.java b/tests/tests/renderscript/src/android/renderscript/cts/SinhTest.java
index 11c3b53..a95c574 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/SinhTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/SinhTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testSinhF32_relaxed() {
-        doF32_relaxed(0x32a, 4);
+        doF32_relaxed(0x32a, 128);
     }
 
     public void testSinhF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testSinhF32_2_relaxed() {
-        doF32_2_relaxed(0xba35, 4);
+        doF32_2_relaxed(0xba35, 128);
     }
 
     public void testSinhF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testSinhF32_3_relaxed() {
-        doF32_3_relaxed(0xacc3, 4);
+        doF32_3_relaxed(0xacc3, 128);
     }
 
     public void testSinhF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testSinhF32_4_relaxed() {
-        doF32_4_relaxed(0xaa, 4);
+        doF32_4_relaxed(0xaa, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/TanTest.java b/tests/tests/renderscript/src/android/renderscript/cts/TanTest.java
index 5122cd0..a4e62e9 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/TanTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/TanTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testTanF32_relaxed() {
-        doF32_relaxed(0xabe, 5);
+        doF32_relaxed(0xabe, 128);
     }
 
     public void testTanF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testTanF32_2_relaxed() {
-        doF32_2_relaxed(0x29, 5);
+        doF32_2_relaxed(0x29, 128);
     }
 
     public void testTanF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testTanF32_3_relaxed() {
-        doF32_3_relaxed(0x9a, 5);
+        doF32_3_relaxed(0x9a, 128);
     }
 
     public void testTanF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testTanF32_4_relaxed() {
-        doF32_4_relaxed(0xac3, 5);
+        doF32_4_relaxed(0xac3, 128);
     }
 
 }
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/TanhTest.java b/tests/tests/renderscript/src/android/renderscript/cts/TanhTest.java
index 84a01dd..4dc7d15 100644
--- a/tests/tests/renderscript/src/android/renderscript/cts/TanhTest.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/TanhTest.java
@@ -80,7 +80,7 @@
     }
 
     public void testTanhF32_relaxed() {
-        doF32_relaxed(0xab61, 5);
+        doF32_relaxed(0xab61, 128);
     }
 
     public void testTanhF32_2() {
@@ -88,7 +88,7 @@
     }
 
     public void testTanhF32_2_relaxed() {
-        doF32_2_relaxed(0xa301, 5);
+        doF32_2_relaxed(0xa301, 128);
     }
 
     public void testTanhF32_3() {
@@ -96,7 +96,7 @@
     }
 
     public void testTanhF32_3_relaxed() {
-        doF32_3_relaxed(0x918, 5);
+        doF32_3_relaxed(0x918, 128);
     }
 
     public void testTanhF32_4() {
@@ -104,7 +104,7 @@
 
     }
     public void testTanhF32_4_relaxed() {
-        doF32_4_relaxed(0x81, 5);
+        doF32_4_relaxed(0x81, 128);
     }
 
 }
diff --git a/tests/tests/security/src/android/security/cts/KeystoreExploitTest.java b/tests/tests/security/src/android/security/cts/KeystoreExploitTest.java
new file mode 100644
index 0000000..23266c2
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/KeystoreExploitTest.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import android.test.AndroidTestCase;
+
+import java.io.File;
+import java.lang.reflect.Method;
+
+public class KeystoreExploitTest extends AndroidTestCase {
+    public void testKeystoreCrash() throws Exception {
+        int pid = Proc.findPidFor("/system/bin/keystore");
+
+        Class<?> keystoreClass = Class.forName("android.security.KeyStore");
+        Method getInstance = keystoreClass.getMethod("getInstance");
+        Method get = keystoreClass.getMethod("get", String.class);
+
+        Object keystore = getInstance.invoke(null);
+        String keyName = "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA "
+                + "AAAA AAAA AAAA AAAA";
+        get.invoke(keystore, keyName);
+
+        Thread.sleep(2000); // give keystore some time to crash
+
+        assertTrue("PID=" + pid + " crashed due to a malformed key name.",
+                new File("/proc/" + pid + "/cmdline").exists());
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/Proc.java b/tests/tests/security/src/android/security/cts/Proc.java
new file mode 100644
index 0000000..6fe0706
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/Proc.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+
+/**
+ * Utilities for accessing /proc filesystem information.
+ */
+public class Proc {
+    public static int findPidFor(String executable) throws IOException {
+        File f = new File("/proc");
+        for (File d : f.listFiles()) {
+            String cmdLineString = d.getAbsolutePath() + "/cmdline";
+            File cmdLine = new File(cmdLineString);
+            if (cmdLine.exists()) {
+                BufferedReader in = null;
+                try {
+                    in = new BufferedReader(new FileReader(cmdLine));
+                    String line = in.readLine();
+                    if ((line != null) && line.startsWith(executable)) {
+                        return Integer.decode(d.getName());
+                    }
+                } finally {
+                    if (in != null) {
+                        in.close();
+                    }
+                }
+            }
+        }
+        throw new RuntimeException("should never get here");
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/VoldExploitTest.java b/tests/tests/security/src/android/security/cts/VoldExploitTest.java
index d7f97ee..74d0f68 100644
--- a/tests/tests/security/src/android/security/cts/VoldExploitTest.java
+++ b/tests/tests/security/src/android/security/cts/VoldExploitTest.java
@@ -58,7 +58,7 @@
      * is the typical failure for this test.
      */
     public void testZergRushCrash() throws Exception {
-        int pid = findVold();
+        int pid = Proc.findPidFor("/system/bin/vold");
 
         StorageManager sm = (StorageManager) getContext().getSystemService(Context.STORAGE_SERVICE);
         sm.getMountedObbPath("AAAA AAAA AAAA AAAA "
@@ -214,29 +214,6 @@
         }
     }
 
-    private static int findVold() throws IOException {
-        File f = new File("/proc");
-        for (File d : f.listFiles()) {
-            String cmdLineString = d.getAbsolutePath() + "/cmdline";
-            File cmdLine = new File(cmdLineString);
-            if (cmdLine.exists()) {
-                BufferedReader in = null;
-                try {
-                    in = new BufferedReader(new FileReader(cmdLine));
-                    String line = in.readLine();
-                    if ((line != null) && line.startsWith("/system/bin/vold")) {
-                        return Integer.decode(d.getName());
-                    }
-                } finally {
-                    if (in != null) {
-                        in.close();
-                    }
-                }
-            }
-        }
-        throw new RuntimeException("should never get here");
-    }
-
     /**
      * Extract all the PIDs listening for netlink messages.
      */
diff --git a/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java b/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java
index 0e8f73e..1e62819 100644
--- a/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java
+++ b/tests/tests/text/src/android/text/format/cts/DateUtilsTest.java
@@ -220,31 +220,6 @@
         assertFalse(DateUtils.isToday(mBaseTime - ONE_DAY_IN_MS));
     }
 
-    /**
-     * DateUtils used to use Time rather than Calendar, which is broken
-     * because Time uses a 32-bit time_t rather than Calendar's 64-bit Java long.
-     * http://code.google.com/p/android/issues/detail?id=13050
-     */
-    public void test2038() {
-        assertEquals("00:00, Thursday, January 1, 1970", formatFull(0L));
-        assertEquals("17:31, Sunday, November 24, 1833",
-                     formatFull(((long) Integer.MIN_VALUE + Integer.MIN_VALUE) * 1000L));
-        assertEquals("20:45, Friday, December 13, 1901", formatFull(Integer.MIN_VALUE * 1000L));
-        assertEquals("03:14, Tuesday, January 19, 2038", formatFull(Integer.MAX_VALUE * 1000L));
-        assertEquals("06:28, Sunday, February 7, 2106",
-                     formatFull((2L + Integer.MAX_VALUE + Integer.MAX_VALUE) * 1000L));
-    }
-
-    private String formatFull(long millis) {
-        Formatter formatter = new Formatter();
-        int flags = DateUtils.FORMAT_SHOW_DATE
-                | DateUtils.FORMAT_SHOW_WEEKDAY
-                | DateUtils.FORMAT_SHOW_TIME
-                | DateUtils.FORMAT_24HOUR;
-        DateUtils.formatDateRange(null, formatter, millis, millis, flags, "UTC");
-        return formatter.toString();
-    }
-
     public void test_bug_7548161() {
         long now = System.currentTimeMillis();
         long today = now;
diff --git a/tests/tests/view/src/android/view/cts/ViewTest.java b/tests/tests/view/src/android/view/cts/ViewTest.java
index e833943..5913892 100644
--- a/tests/tests/view/src/android/view/cts/ViewTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTest.java
@@ -3387,7 +3387,8 @@
         }
 
         @Override
-        public void childAccessibilityStateChanged(View root) {
+        public void notifySubtreeAccessibilityStateChanged(View child,
+            View source, int changeType) {
 
         }
     }
diff --git a/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java b/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java
index 85a616f..e2166d8 100644
--- a/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/GeolocationTest.java
@@ -43,6 +43,7 @@
 import java.io.UnsupportedEncodingException;
 import java.util.concurrent.Callable;
 import java.util.Date;
+import java.util.List;
 import java.util.Random;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -65,7 +66,6 @@
     private static final String JS_INTERFACE_NAME = "Android";
     private static final int POLLING_TIMEOUT = 60 * 1000;
     private static final int LOCATION_THREAD_UPDATE_WAIT_MS = 250;
-    private static final String PROVIDER_NAME = LocationManager.NETWORK_PROVIDER;
 
     // static HTML page always injected instead of the url loaded
     private static final String RAW_HTML =
@@ -105,6 +105,7 @@
     private WebViewOnUiThread mOnUiThread;
     private Thread mLocationUpdateThread;
     private volatile boolean mLocationUpdateThreadExitRequested;
+    private List<String> mProviders;
 
     public GeolocationTest() throws Exception {
         super("com.android.cts.stub", WebViewStubActivity.class);
@@ -154,21 +155,48 @@
         mLocationManager = (LocationManager)getActivity().getApplicationContext()
                 .getSystemService(Context.LOCATION_SERVICE);
         // Add a test provider before each test to inject a location
-        addTestProvider(PROVIDER_NAME);
+        mProviders = mLocationManager.getAllProviders();
+        for (String provider : mProviders) {
+            // Can't mock passive provider.
+            if (provider.equals(LocationManager.PASSIVE_PROVIDER)) {
+                mProviders.remove(provider);
+                break;
+            }
+        }
+        addTestProviders();
     }
 
     @Override
     protected void tearDown() throws Exception {
         stopUpdateLocationThread();
         // Remove the test provider after each test
-        try {
-            mLocationManager.removeTestProvider(PROVIDER_NAME);
-        } catch (IllegalArgumentException e) {} // Not much to do about this
+        for (String provider : mProviders) {
+            try {
+                mLocationManager.removeTestProvider(provider);
+            } catch (IllegalArgumentException e) {} // Not much to do about this
+        }
         mOnUiThread.cleanUp();
         // This will null all member and static variables
         super.tearDown();
     }
 
+    private void addTestProviders() {
+        for (String providerName : mProviders) {
+            LocationProvider provider = mLocationManager.getProvider(providerName);
+            mLocationManager.addTestProvider(provider.getName(),
+                    provider.requiresNetwork(), //requiresNetwork,
+                    provider.requiresSatellite(), // requiresSatellite,
+                    provider.requiresCell(),  // requiresCell,
+                    provider.hasMonetaryCost(), // hasMonetaryCost,
+                    provider.supportsAltitude(), // supportsAltitude,
+                    provider.supportsSpeed(), // supportsSpeed,
+                    provider.supportsBearing(), // supportsBearing,
+                    provider.getPowerRequirement(), // powerRequirement
+                    provider.getAccuracy()); // accuracy
+            mLocationManager.setTestProviderEnabled(provider.getName(), true);
+        }
+    }
+
     private void startUpdateLocationThread() {
         // Only start the thread once
         if (mLocationUpdateThread == null) {
@@ -182,7 +210,7 @@
                         } catch(Exception e) {
                             // Do nothing, an extra update is no problem
                         }
-                        updateLocation(PROVIDER_NAME);
+                        updateLocation();
                     }
                 }
             };
@@ -204,14 +232,16 @@
     }
 
     // Update location with a fixed latitude and longtitude, sets the time to the current time.
-    private void updateLocation(final String providerName) {
-        Location location = new Location(providerName);
-        location.setLatitude(40);
-        location.setLongitude(40);
-        location.setAccuracy(1.0f);
-        location.setTime(java.lang.System.currentTimeMillis());
-        location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
-        mLocationManager.setTestProviderLocation(providerName, location);
+    private void updateLocation() {
+        for (int i = 0; i < mProviders.size(); i++) {
+            Location location = new Location(mProviders.get(i));
+            location.setLatitude(40);
+            location.setLongitude(40);
+            location.setAccuracy(1.0f);
+            location.setTime(java.lang.System.currentTimeMillis());
+            location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
+            mLocationManager.setTestProviderLocation(mProviders.get(i), location);
+        }
     }
 
     // Need to set the location just after loading the url. Setting it after each load instead of
@@ -244,20 +274,6 @@
         }
     }
 
-    private void addTestProvider(final String providerName) {
-        mLocationManager.addTestProvider(providerName,
-                true, //requiresNetwork,
-                false, // requiresSatellite,
-                true,  // requiresCell,
-                false, // hasMonetaryCost,
-                false, // supportsAltitude,
-                false, // supportsSpeed,
-                false, // supportsBearing,
-                Criteria.POWER_MEDIUM, // powerRequirement
-                Criteria.ACCURACY_FINE); // accuracy
-        mLocationManager.setTestProviderEnabled(providerName, true);
-    }
-
     // Test loading a page and accepting the domain for one load
     public void testSimpleGeolocationRequestAcceptOnce() throws Exception {
         final TestSimpleGeolocationRequestWebChromeClient chromeClientAcceptOnce =
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 3353d50..efd3aef 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -192,11 +192,19 @@
     public void testOnScaleChanged() throws Throwable {
         final MockWebViewClient webViewClient = new MockWebViewClient();
         mOnUiThread.setWebViewClient(webViewClient);
+        mWebServer = new CtsTestServer(getActivity());
 
         assertFalse(webViewClient.hasOnScaleChangedCalled());
+        String url1 = mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
+        mOnUiThread.loadUrlAndWaitForCompletion(url1);
+
         mOnUiThread.zoomIn();
-        getInstrumentation().waitForIdleSync();
-        assertTrue(webViewClient.hasOnScaleChangedCalled());
+        new PollingCheck(TEST_TIMEOUT) {
+            @Override
+            protected boolean check() {
+                return webViewClient.hasOnScaleChangedCalled();
+            }
+        }.run();
     }
 
     private void requireLoadedPage() throws Throwable {
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index f8a3df5..69ad3a5 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -854,6 +854,10 @@
         mOnUiThread.loadDataWithBaseURLAndWaitForCompletion("data:foo",
                 HTML_HEADER + "<title>Hello World%21</title></html>", "text/html", "UTF-8", null);
         assertEquals("Hello World!", mOnUiThread.getTitle());
+
+        // Check the method is null input safe.
+        mOnUiThread.loadDataWithBaseURLAndWaitForCompletion(null, null, null, null, null);
+        assertEquals("about:blank", mOnUiThread.getUrl());
     }
 
     private static class WaitForFindResultsListener extends FutureTask<Integer>
@@ -875,12 +879,23 @@
     }
 
     public void testFindAll()  throws Throwable {
-        String p = "<p>Find all instances of find on the page and highlight them.</p>";
+        // Make the page scrollable, so we can detect the scrolling to make sure the
+        // content fully loaded.
+        mOnUiThread.setInitialScale(100);
+        DisplayMetrics metrics = mOnUiThread.getDisplayMetrics();
+        int dimension = Math.max(metrics.widthPixels, metrics.heightPixels);
+        // create a paragraph high enough to take up the entire screen
+        String p = "<p style=\"height:" + dimension + "px;\">" +
+                "Find all instances of find on the page and highlight them.</p>";
 
         mOnUiThread.loadDataAndWaitForCompletion("<html><body>" + p
                 + "</body></html>", "text/html", null);
 
         WaitForFindResultsListener l = new WaitForFindResultsListener();
+        int previousScrollY = mOnUiThread.getScrollY();
+        mOnUiThread.pageDown(true);
+        // Wait for content fully loaded.
+        waitForScrollingComplete(previousScrollY);
         mOnUiThread.setFindListener(l);
         mOnUiThread.findAll("find");
 
@@ -999,9 +1014,15 @@
                 "Scroll by half the size of the page.</p>";
         mOnUiThread.loadDataAndWaitForCompletion("<html><body>" + p
                 + p + "</body></html>", "text/html", null);
-        getInstrumentation().waitForIdleSync();
 
-        assertTrue(mOnUiThread.pageDown(false));
+        // Wait for UI thread to settle and receive page dimentions from renderer
+        // such that we can invoke page down.
+        new PollingCheck() {
+            @Override
+            protected boolean check() {
+                 return mOnUiThread.pageDown(false);
+            }
+        }.run();
 
         do {
             getInstrumentation().waitForIdleSync();
@@ -1102,27 +1123,18 @@
         }.run();
         getInstrumentation().waitForIdleSync();
 
-        int previousScrollX = mOnUiThread.getScrollX();
-        int previousScrollY = mOnUiThread.getScrollY();
+        final int previousScrollX = mOnUiThread.getScrollX();
+        final int previousScrollY = mOnUiThread.getScrollY();
 
         mOnUiThread.flingScroll(100, 100);
 
-        int timeSlice = 500;
-        Thread.sleep(timeSlice);
-        assertTrue(mOnUiThread.getScrollX() > previousScrollX);
-        assertTrue(mOnUiThread.getScrollY() > previousScrollY);
-
-        previousScrollY = mOnUiThread.getScrollY();
-        previousScrollX = mOnUiThread.getScrollX();
-        Thread.sleep(timeSlice);
-        assertTrue(mOnUiThread.getScrollX() >= previousScrollX);
-        assertTrue(mOnUiThread.getScrollY() >= previousScrollY);
-
-        previousScrollY = mOnUiThread.getScrollY();
-        previousScrollX = mOnUiThread.getScrollX();
-        Thread.sleep(timeSlice);
-        assertTrue(mOnUiThread.getScrollX() >= previousScrollX);
-        assertTrue(mOnUiThread.getScrollY() >= previousScrollY);
+        new PollingCheck() {
+            @Override
+            protected boolean check() {
+                return mOnUiThread.getScrollX() > previousScrollX &&
+                        mOnUiThread.getScrollY() > previousScrollY;
+            }
+        }.run();
     }
 
     public void testRequestFocusNodeHref() throws Throwable {
@@ -1481,12 +1493,19 @@
 
         final MockWebViewClient webViewClient = new MockWebViewClient();
         mOnUiThread.setWebViewClient(webViewClient);
-        getInstrumentation().waitForIdleSync();
+        startWebServer(false);
+
         assertFalse(webViewClient.onScaleChangedCalled());
+        String url1 = mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
+        mOnUiThread.loadUrlAndWaitForCompletion(url1);
 
         mOnUiThread.zoomIn();
-        getInstrumentation().waitForIdleSync();
-        assertTrue(webViewClient.onScaleChangedCalled());
+        new PollingCheck() {
+            @Override
+            protected boolean check() {
+                return webViewClient.onScaleChangedCalled();
+            }
+        }.run();
     }
 
     @UiThreadTest
@@ -1688,17 +1707,20 @@
 
     public void testRequestChildRectangleOnScreen() throws Throwable {
         DisplayMetrics metrics = mOnUiThread.getDisplayMetrics();
-        int dimension = 2 * Math.max(metrics.widthPixels, metrics.heightPixels);
+        final int dimension = 2 * Math.max(metrics.widthPixels, metrics.heightPixels);
         String p = "<p style=\"height:" + dimension + "px;width:" + dimension + "px\">&nbsp;</p>";
         mOnUiThread.loadDataAndWaitForCompletion("<html><body>" + p
                 + "</body></html>", "text/html", null);
-        getInstrumentation().waitForIdleSync();
+        new PollingCheck() {
+            @Override
+            protected boolean check() {
+                return mOnUiThread.getContentHeight() >= dimension;
+            }
+        }.run();
 
         int origX = mOnUiThread.getScrollX();
         int origY = mOnUiThread.getScrollY();
 
-        metrics = mOnUiThread.getDisplayMetrics();
-        dimension = 2 * Math.max(metrics.widthPixels, metrics.heightPixels);
         int half = dimension / 2;
         Rect rect = new Rect(half, half, half + 1, half + 1);
         assertTrue(mOnUiThread.requestChildRectangleOnScreen(mWebView, rect, true));