Merge "Use jack script to build vm-tests-tf"
diff --git a/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java b/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
index c80d676..2048185 100644
--- a/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
+++ b/hostsidetests/security/src/android/cts/security/SELinuxHostTest.java
@@ -34,7 +34,6 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.lang.String;
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -724,10 +723,11 @@
 
             /* take the output of a ps -Z to do our analysis */
             CollectingOutputReceiver psOut = new CollectingOutputReceiver();
-            tDevice.executeShellCommand("ps -Z", psOut);
+            // TODO: remove "toybox" below and just run "ps"
+            tDevice.executeShellCommand("toybox ps -A -o label,user,pid,ppid,cmdline", psOut);
             String psOutString = psOut.getOutput();
             Pattern p = Pattern.compile(
-                    "^([\\w_:]+)\\s+([\\w_]+)\\s+(\\d+)\\s+(\\d+)\\s+(\\p{Graph}+)\\s*$",
+                    "^([\\w_:]+)\\s+([\\w_]+)\\s+(\\d+)\\s+(\\d+)\\s+(\\p{Graph}+)(\\s\\p{Graph}+)*\\s*$",
                     Pattern.MULTILINE);
             Matcher m = p.matcher(psOutString);
             procMap = new HashMap<String, ArrayList<ProcessDetails>>();
@@ -743,7 +743,7 @@
                     procMap.put(domainLabel, new ArrayList<ProcessDetails>());
                 }
                 procMap.get(domainLabel).add(proc);
-                if (procTitle.equals("kthreadd") && ppid == 0) {
+                if (procTitle.equals("[kthreadd]") && ppid == 0) {
                     kernelParentThreadpid = pid;
                 }
                 if (exeMap.get(procTitle) == null) {
diff --git a/tests/core/libcore/libcore/Android.mk b/tests/core/libcore/libcore/Android.mk
index d8e3fcb..a547166 100644
--- a/tests/core/libcore/libcore/Android.mk
+++ b/tests/core/libcore/libcore/Android.mk
@@ -16,5 +16,5 @@
 
 include $(CLEAR_VARS)
 LOCAL_PACKAGE_NAME := android.core.tests.libcore.package.libcore
-LOCAL_STATIC_JAVA_LIBRARIES := core-tests mockito-target
+LOCAL_STATIC_JAVA_LIBRARIES := core-tests mockito-api
 include $(BUILD_CTSCORE_PACKAGE)
diff --git a/tests/tests/jni/libjnitest/Android.mk b/tests/tests/jni/libjnitest/Android.mk
index 7a2d577..7140de4 100644
--- a/tests/tests/jni/libjnitest/Android.mk
+++ b/tests/tests/jni/libjnitest/Android.mk
@@ -30,13 +30,14 @@
 	android_jni_cts_JniCTest.c \
 	android_jni_cts_JniCppTest.cpp \
 	android_jni_cts_JniStaticTest.cpp \
+	android_jni_cts_LinkerNamespacesTest.cpp \
 	android_jni_cts_StaticNonce.c \
 	helper.c \
 	register.c
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
 
-LOCAL_SHARED_LIBRARIES := liblog libnativehelper_compat_libc++
+LOCAL_SHARED_LIBRARIES := libdl liblog libnativehelper_compat_libc++
 
 LOCAL_SDK_VERSION := 23
 LOCAL_NDK_STL_VARIANT := c++_static
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
new file mode 100644
index 0000000..5876532
--- /dev/null
+++ b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Tests accessibility of platform native libraries
+ */
+
+#include <dirent.h>
+#include <dlfcn.h>
+#include <jni.h>
+#include <JNIHelp.h>
+#include <libgen.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <list>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+static std::vector<std::string> kDefaultLibraryPaths = {
+#if defined(__LP64__)
+    "/system/lib64",
+    "/vendor/lib64",
+#else
+    "/system/lib",
+    "/vendor/lib",
+#endif
+  };
+
+static std::unordered_set<std::string> kPublicLibraries = {
+    "libandroid.so",
+    "libc.so",
+    "libdl.so",
+    "libEGL.so",
+    "libGLESv1_CM.so",
+    "libGLESv2.so",
+    "libGLESv3.so",
+    "libicui18n.so",
+    "libicuuc.so",
+    "libjnigraphics.so",
+    "liblog.so",
+    "libmediandk.so",
+    "libm.so",
+    "libOpenMAXAL.so",
+    "libOpenSLES.so",
+    "libRS.so",
+    "libstdc++.so",
+    "libwebviewchromium_plat_support.so",
+    "libz.so"
+  };
+
+template <typename F>
+static bool for_each_file(const std::string& dir, F functor, std::string* error_msg) {
+  auto dir_deleter = [](DIR* handle) { closedir(handle); };
+  std::unique_ptr<DIR, decltype(dir_deleter)> dirp(opendir(dir.c_str()), dir_deleter);
+  if (dirp == nullptr) {
+    *error_msg = strerror(errno);
+    return false;
+  }
+
+  dirent* dp;
+  while ((dp = readdir(dirp.get())) != nullptr) {
+    // skip "." and ".."
+    if (strcmp(".", dp->d_name) == 0 ||
+        strcmp("..", dp->d_name) == 0) {
+      continue;
+    }
+
+    if (!functor(dp->d_name, error_msg)) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+static bool should_be_accessible(const std::string& path) {
+  std::string name = basename(path.c_str());
+  return (kPublicLibraries.find(name) != kPublicLibraries.end()) &&
+         (kDefaultLibraryPaths.front() + "/" + name == path);
+}
+
+static bool is_directory(const std::string path) {
+  struct stat sb;
+  if (stat(path.c_str(), &sb) != -1) {
+    return S_ISDIR(sb.st_mode);
+  }
+
+  return false;
+}
+
+static bool is_libdl(const std::string path) {
+  return kDefaultLibraryPaths.front() + "/libdl.so" == path;
+}
+
+extern "C" JNIEXPORT jstring JNICALL Java_android_jni_cts_LinkerNamespacesHelper_runAccessibilityTest(
+        JNIEnv* env, jclass clazz __attribute__((unused))) {
+  std::list<std::string> dirs(kDefaultLibraryPaths.begin(), kDefaultLibraryPaths.end());
+  while (!dirs.empty()) {
+    const auto dir = dirs.front();
+    dirs.pop_front();
+    std::string error;
+    bool success = for_each_file(dir, [&dirs,&dir](const char* name, std::string* error_msg) {
+      std::string path = dir + "/" + name;
+      if (is_directory(path)) {
+        dirs.push_back(path);
+        return true;
+      }
+
+      if (is_libdl(path)) {
+        // TODO (dimitry): we skip check for libdl.so because
+        // 1. Linker will fail to check accessibility because it imposes as libdl.so (see http://b/27106625)
+        // 2. It is impractical to dlopen libdl.so because this library already depends
+        //    on it in order to have dlopen()
+        return true;
+      }
+
+      auto dlcloser = [](void* handle) { dlclose(handle); };
+      std::unique_ptr<void, decltype(dlcloser)> handle(dlopen(path.c_str(), RTLD_NOW), dlcloser);
+      if (should_be_accessible(path)) {
+        if (handle.get() == nullptr) {
+          *error_msg = "The library \"" + path + "\" should be accessible but isn't: " + dlerror();
+          return false;
+        }
+      } else if (handle != nullptr) {
+        *error_msg = "The library \"" + path + "\" should not be accessible";
+        return false;
+      } else { // (handle == nullptr && !shouldBeAccessible(path))
+        // Check the error message
+        std::string err = dlerror();
+
+        if (err != "dlopen failed: library \"" + path + "\" is not accessible for the namespace \"classloader-namespace\"") {
+          *error_msg = "unexpected dlerror: " + err;
+          return false;
+        }
+      }
+      return true;
+    }, &error);
+
+    if (!success) {
+      return env->NewStringUTF(error.c_str());
+    }
+  }
+
+  return nullptr;
+}
+
diff --git a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
index d4b51b9..8a91c44 100644
--- a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
+++ b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
@@ -31,6 +31,17 @@
     }
 
     /**
+     * Test library accessibility. Internal platform libraries should not
+     * be accessible from the jni code.
+     */
+    public void test_linker_namespaces() {
+        String error = LinkerNamespacesHelper.runAccessibilityTest();
+        if (error != null) {
+            fail(error);
+        }
+    }
+
+    /**
      * Test that accessing classes true JNI works as expected. b/19382130
      */
     public void test_classload() {
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
new file mode 100644
index 0000000..2dff019
--- /dev/null
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.jni.cts;
+
+class LinkerNamespacesHelper {
+    public static native String runAccessibilityTest();
+}
diff --git a/tests/tests/net/src/android/net/wifi/cts/ConcurrencyTest.java b/tests/tests/net/src/android/net/wifi/cts/ConcurrencyTest.java
index 343c1e6..a066ba8 100644
--- a/tests/tests/net/src/android/net/wifi/cts/ConcurrencyTest.java
+++ b/tests/tests/net/src/android/net/wifi/cts/ConcurrencyTest.java
@@ -20,12 +20,20 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.net.ConnectivityManager;
+import android.net.ConnectivityManager.NetworkCallback;
+import android.net.Network;
+import android.net.NetworkCapabilities;
+import android.net.NetworkRequest;
 import android.net.wifi.WifiManager;
 import android.net.wifi.p2p.WifiP2pManager;
 import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_DISABLED;
 import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_STATE_ENABLED;
 import android.test.AndroidTestCase;
 
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 public class ConcurrencyTest extends AndroidTestCase {
     private class MySync {
         int expectedWifiState;
@@ -94,10 +102,7 @@
         }
         mContext.unregisterReceiver(mReceiver);
 
-        if (!mWifiManager.isWifiEnabled()) {
-            assertTrue(mWifiManager.setWifiEnabled(true));
-            Thread.sleep(DURATION);
-        }
+        enableWifi();
         super.tearDown();
     }
 
@@ -114,6 +119,33 @@
         }
     }
 
+    /*
+     * Enables Wifi and block until connection is established.
+     */
+    private void enableWifi() throws InterruptedException {
+        if (!mWifiManager.isWifiEnabled()) {
+            assertTrue(mWifiManager.setWifiEnabled(true));
+        }
+
+        ConnectivityManager cm =
+            (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+        NetworkRequest request =
+            new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
+                                        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
+                                        .build();
+        final CountDownLatch latch = new CountDownLatch(1);
+        NetworkCallback networkCallback = new NetworkCallback() {
+            @Override
+            public void onAvailable(Network network) {
+                latch.countDown();
+            }
+        };
+        cm.registerNetworkCallback(request, networkCallback);
+        latch.await(DURATION, TimeUnit.MILLISECONDS);
+
+        cm.unregisterNetworkCallback(networkCallback);
+    }
+
     public void testConcurrency() {
         // Cannot support p2p alone
         if (!WifiFeature.isWifiSupported(getContext())) {
diff --git a/tests/tests/net/src/org/apache/http/conn/ssl/cts/AbstractVerifierTest.java b/tests/tests/net/src/org/apache/http/conn/ssl/cts/AbstractVerifierTest.java
index 16d3ac4..5e2a55e 100644
--- a/tests/tests/net/src/org/apache/http/conn/ssl/cts/AbstractVerifierTest.java
+++ b/tests/tests/net/src/org/apache/http/conn/ssl/cts/AbstractVerifierTest.java
@@ -107,7 +107,7 @@
     public void testGetCns_whitespace() {
         assertCns("cn= p", "p");
         assertCns("cn=\np", "p");
-        assertCns("cn=\tp", "p");
+        assertCns("cn=\tp", "\tp");
     }
 
     public void testGetCnsWithOid() {
diff --git a/tests/tests/os/src/android/os/cts/AbiTest.java b/tests/tests/os/src/android/os/cts/AbiTest.java
index ee2c168..1d343e6 100644
--- a/tests/tests/os/src/android/os/cts/AbiTest.java
+++ b/tests/tests/os/src/android/os/cts/AbiTest.java
@@ -17,16 +17,35 @@
 package android.os.cts;
 
 import android.cts.util.ReadElf;
+import android.util.ArraySet;
 
 import java.io.File;
+import java.util.Arrays;
 
 import junit.framework.TestCase;
 
 public class AbiTest extends TestCase {
     public void testNo64() throws Exception {
-        for (String dir : new File("/").list()) {
-            if (!dir.equals("data") && !dir.equals("dev") && !dir.equals("proc") && !dir.equals("sys")) {
-                checkElfFilesInDirectory(new File("/" + dir));
+        ArraySet<String> abiDirs = new ArraySet(Arrays.asList(
+            "/sbin",
+            "/system",
+            "/vendor"));
+        String pathVar = System.getenv("PATH");
+        if (pathVar != null) {
+            abiDirs.addAll(Arrays.asList(pathVar.split(":")));
+        }
+        for (String dir : abiDirs) {
+            boolean skip_dir = false;
+            for (String dirOther : abiDirs) {
+                if (dir.equals(dirOther)) {
+                    continue;
+                } else if (dir.startsWith(dirOther + "/")) {
+                    skip_dir = true;
+                    break;
+                }
+            }
+            if (!skip_dir) {
+                checkElfFilesInDirectory(new File(dir));
             }
         }
     }
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index f1bd9ea..05079d7 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -527,6 +527,7 @@
                     "/data/misc/bluetooth",
                     "/data/misc/dhcp",
                     "/data/misc/lockscreen",
+                    "/data/misc/sensor",
                     "/data/misc/webwidgets",
                     "/data/misc/webwidgets/chess",
                     "/data/misc/widgets",
diff --git a/tests/tests/renderscript/AndroidManifest.xml b/tests/tests/renderscript/AndroidManifest.xml
index 6e67f9e..b7e1e1a 100644
--- a/tests/tests/renderscript/AndroidManifest.xml
+++ b/tests/tests/renderscript/AndroidManifest.xml
@@ -24,7 +24,7 @@
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-    <application>
+    <application android:largeHeap="true">
         <uses-library android:name="android.test.runner" />
     </application>
 
diff --git a/tests/tests/rsblas/libbnnmdata/Android.mk b/tests/tests/rsblas/libbnnmdata/Android.mk
index 471d74a..bbfd289 100644
--- a/tests/tests/rsblas/libbnnmdata/Android.mk
+++ b/tests/tests/rsblas/libbnnmdata/Android.mk
@@ -19,6 +19,8 @@
 LOCAL_MODULE := libbnnmdata_jni
 LOCAL_MODULE_TAGS := optional
 LOCAL_SRC_FILES := test_data.cpp
+LOCAL_SDK_VERSION := 23
+LOCAL_NDK_STL_VARIANT := c++_static
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
 
diff --git a/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java b/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java
index 19866de..4ee1480 100644
--- a/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java
+++ b/tests/tests/security/src/android/security/cts/ClonedSecureRandomTest.java
@@ -21,7 +21,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.ServiceConnection;
-import android.os.DeadObjectException;
+import android.os.RemoteException;
 import android.os.IBinder;
 import android.security.cts.activity.ISecureRandomService;
 import android.security.cts.activity.SecureRandomService;
@@ -145,7 +145,13 @@
                 }
             }, 0);
 
-            pid = mSecureRandomService.getRandomBytesAndPid(output);
+            try {
+                pid = mSecureRandomService.getRandomBytesAndPid(output);
+            } catch (RemoteException e) {
+                // The process died before we could query. Try again.
+                continue;
+            }
+
             getContext().unbindService(mServiceConnection);
 
             /*
diff --git a/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super/Test_invoke_super.java b/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super/Test_invoke_super.java
index 0995fb0..733c2b7 100644
--- a/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super/Test_invoke_super.java
+++ b/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super/Test_invoke_super.java
@@ -236,8 +236,8 @@
      * @title attempt to invoke interface method
      */
     public void testVFE18() {
-        loadAndRun("dot.junit.opcodes.invoke_super.d.T_invoke_super_24", 
-                   IncompatibleClassChangeError.class);
+        loadAndRun("dot.junit.opcodes.invoke_super.d.T_invoke_super_24",
+                   AbstractMethodError.class);
     }
 
     /**
diff --git a/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super_range/Test_invoke_super_range.java b/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super_range/Test_invoke_super_range.java
index 9007ef4..566b84f 100644
--- a/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super_range/Test_invoke_super_range.java
+++ b/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_super_range/Test_invoke_super_range.java
@@ -243,7 +243,7 @@
     public void testVFE18() {
         //@uses dot.junit.opcodes.invoke_super_range.d.T_invoke_super_range_24
         loadAndRun("dot.junit.opcodes.invoke_super_range.d.T_invoke_super_range_24",
-                   IncompatibleClassChangeError.class);
+                   AbstractMethodError.class);
     }
 
     /**