Merge "Revert "DO NOT MERGE: CTS test case for CVE-2015-1530" am: 480a3a5017  -s ours" into lollipop-mr1-cts-dev am: d105326d78  -s ours am: f062ffbf44  -s ours am: 76407fe7a5 am: b00f83f42a am: a95d472a0f am: cbf05d421c  -s ours
am: c47189c93f

Change-Id: I4dcfa78f6f4cb57134a27e4f21ec061280cc5d95
diff --git a/OldCtsTestCaseList.mk b/OldCtsTestCaseList.mk
index 685d9a0..739bae0 100644
--- a/OldCtsTestCaseList.mk
+++ b/OldCtsTestCaseList.mk
@@ -193,6 +193,7 @@
     CtsJniTestCases \
     CtsKeystoreTestCases \
     CtsLibcoreLegacy22TestCases \
+    CtsLibcoreFileIOTestCases \
     CtsLocationTestCases \
     CtsLocation2TestCases \
     CtsMediaStressTestCases \
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index 301ea73..52780eb 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -51,7 +51,8 @@
 
     # Get all the scene0 and scene1 tests, which can be run using the same
     # physical setup.
-    scenes = ["scene0", "scene1", "scene2", "scene3", "scene4", "scene5"]
+    scenes = ["scene0", "scene1", "scene2", "scene3", "scene4", "scene5",
+              "sensor_fusion"]
 
     scene_req = {
         "scene0" : None,
diff --git a/apps/CtsVerifier/jni/verifier/Android.mk b/apps/CtsVerifier/jni/verifier/Android.mk
index 2978b06..4840e62 100644
--- a/apps/CtsVerifier/jni/verifier/Android.mk
+++ b/apps/CtsVerifier/jni/verifier/Android.mk
@@ -32,6 +32,4 @@
 
 LOCAL_SHARED_LIBRARIES := liblog
 
-LOCAL_CXX_STL := libstdc++
-
 include $(BUILD_SHARED_LIBRARY)
diff --git a/apps/cts-usb-accessory/Android.mk b/apps/cts-usb-accessory/Android.mk
index f3a7ebd..7699b1a 100644
--- a/apps/cts-usb-accessory/Android.mk
+++ b/apps/cts-usb-accessory/Android.mk
@@ -28,6 +28,7 @@
 
 LOCAL_C_INCLUDES += \
 	bionic/libc/kernel/uapi \
+	bionic/libc/kernel/android/uapi \
 	bionic/libc/kernel/uapi/asm-x86 \
 
 LOCAL_STATIC_LIBRARIES := libusbhost libcutils
diff --git a/build/test_executable.mk b/build/test_executable.mk
index 979f59e..8b93a04 100644
--- a/build/test_executable.mk
+++ b/build/test_executable.mk
@@ -33,11 +33,15 @@
   $(eval $(call copy-one-file, $(fp), $(installed)))\
   $(eval cts_executable_bin += $(installed)))
 
+ifndef LOCAL_CTS_GTEST_LIST_EXECUTABLE
+LOCAL_CTS_GTEST_LIST_EXECUTABLE := $(HOST_OUT_EXECUTABLES)/$(LOCAL_MODULE)_list
+endif
+
 cts_executable_xml := $(CTS_TESTCASES_OUT)/$(LOCAL_MODULE).xml
 $(cts_executable_xml): PRIVATE_TEST_PACKAGE := $(LOCAL_CTS_TEST_PACKAGE)
 $(cts_executable_xml): PRIVATE_EXECUTABLE := $(LOCAL_MODULE)
-$(cts_executable_xml): PRIVATE_LIST_EXECUTABLE := $(HOST_OUT_EXECUTABLES)/$(LOCAL_MODULE)_list
-$(cts_executable_xml): $(HOST_OUT_EXECUTABLES)/$(LOCAL_MODULE)_list
+$(cts_executable_xml): PRIVATE_LIST_EXECUTABLE := $(LOCAL_CTS_GTEST_LIST_EXECUTABLE)
+$(cts_executable_xml): $(LOCAL_CTS_GTEST_LIST_EXECUTABLE)
 $(cts_executable_xml): $(cts_executable_bin)
 $(cts_executable_xml): $(cts_module_test_config)
 $(cts_executable_xml): $(addprefix $(LOCAL_PATH)/,$(LOCAL_SRC_FILES)) $(CTS_EXPECTATIONS) $(CTS_UNSUPPORTED_ABIS) $(CTS_NATIVE_TEST_SCANNER) $(CTS_XML_GENERATOR)
diff --git a/hostsidetests/security/src/android/cts/security/FileSystemPermissionTest.java b/hostsidetests/security/src/android/cts/security/FileSystemPermissionTest.java
new file mode 100644
index 0000000..0cbd1cc
--- /dev/null
+++ b/hostsidetests/security/src/android/cts/security/FileSystemPermissionTest.java
@@ -0,0 +1,137 @@
+package android.cts.security;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.testtype.DeviceTestCase;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+public class FileSystemPermissionTest extends DeviceTestCase {
+
+   /**
+    * A reference to the device under test.
+    */
+    private ITestDevice mDevice;
+
+    /**
+     * Used to build the find command for finding insecure file system components
+     */
+    private static final String INSECURE_DEVICE_ADB_COMMAND = "find %s -type %s -perm /o=rwx 2>/dev/null";
+
+    /**
+     * Whitelist exceptions of allowed world accessbale char files under /dev
+     */
+    private static final Set<String> CHAR_DEV_EXCEPTIONS = new HashSet<String>(
+        Arrays.asList(
+            // All exceptions should be alphabetical and associated with a bug number.
+            "/dev/adsprpc-smd", // b/11710243
+            "/dev/alarm",      // b/9035217
+            "/dev/ashmem",
+            "/dev/binder",
+            "/dev/card0",       // b/13159510
+            "/dev/renderD128",
+            "/dev/renderD129",  // b/23798677
+            "/dev/dri/card0",   // b/13159510
+            "/dev/dri/renderD128",
+            "/dev/dri/renderD129", // b/23798677
+            "/dev/felica",     // b/11142586
+            "/dev/felica_ant", // b/11142586
+            "/dev/felica_cen", // b/11142586
+            "/dev/felica_pon", // b/11142586
+            "/dev/felica_rfs", // b/11142586
+            "/dev/felica_rws", // b/11142586
+            "/dev/felica_uicc", // b/11142586
+            "/dev/full",
+            "/dev/galcore",
+            "/dev/genlock",    // b/9035217
+            "/dev/graphics/galcore",
+            "/dev/ion",
+            "/dev/kgsl-2d0",   // b/11271533
+            "/dev/kgsl-2d1",   // b/11271533
+            "/dev/kgsl-3d0",   // b/9035217
+            "/dev/log/events", // b/9035217
+            "/dev/log/main",   // b/9035217
+            "/dev/log/radio",  // b/9035217
+            "/dev/log/system", // b/9035217
+            "/dev/mali0",       // b/9106968
+            "/dev/mali",        // b/11142586
+            "/dev/mm_interlock", // b/12955573
+            "/dev/mm_isp",      // b/12955573
+            "/dev/mm_v3d",      // b/12955573
+            "/dev/msm_rotator", // b/9035217
+            "/dev/null",
+            "/dev/nvhost-as-gpu",
+            "/dev/nvhost-ctrl", // b/9088251
+            "/dev/nvhost-ctrl-gpu",
+            "/dev/nvhost-dbg-gpu",
+            "/dev/nvhost-gpu",
+            "/dev/nvhost-gr2d", // b/9088251
+            "/dev/nvhost-gr3d", // b/9088251
+            "/dev/nvhost-tsec",
+            "/dev/nvhost-prof-gpu",
+            "/dev/nvhost-vic",
+            "/dev/nvmap",       // b/9088251
+            "/dev/ptmx",        // b/9088251
+            "/dev/pvrsrvkm",    // b/9108170
+            "/dev/pvr_sync",
+            "/dev/quadd",
+            "/dev/random",
+            "/dev/snfc_cen",    // b/11142586
+            "/dev/snfc_hsel",   // b/11142586
+            "/dev/snfc_intu_poll", // b/11142586
+            "/dev/snfc_rfs",    // b/11142586
+            "/dev/tegra-throughput",
+            "/dev/tiler",       // b/9108170
+            "/dev/tty",
+            "/dev/urandom",
+            "/dev/ump",         // b/11142586
+            "/dev/xt_qtaguid",  // b/9088251
+            "/dev/zero",
+            "/dev/fimg2d",      // b/10428016
+            "/dev/mobicore-user" // b/10428016
+    ));
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mDevice = getDevice();
+    }
+
+    public void testAllCharacterDevicesAreSecure() throws DeviceNotAvailableException {
+        Set <String> insecure = getAllInsecureDevicesInDirAndSubdir("/dev", "c");
+        Set <String> insecurePts = getAllInsecureDevicesInDirAndSubdir("/dev/pts", "c");
+        insecure.removeAll(CHAR_DEV_EXCEPTIONS);
+        insecure.removeAll(insecurePts);
+        assertTrue("Found insecure character devices: " + insecure.toString(),
+                insecure.isEmpty());
+    }
+
+    public void testAllBlockDevicesAreSecure() throws Exception {
+        Set<String> insecure = getAllInsecureDevicesInDirAndSubdir("/dev", "b");
+        assertTrue("Found insecure block devices: " + insecure.toString(),
+                insecure.isEmpty());
+    }
+
+    /**
+     * Searches for all world accessable files, note this may need sepolicy to search the desired
+     * location and stat files.
+     * @path The path to search, must be a directory.
+     * @type The type of file to search for, must be a valid find command argument to the type
+     *       option.
+     * @returns The set of insecure fs objects found.
+     */
+    private Set<String> getAllInsecureDevicesInDirAndSubdir(String path, String type) throws DeviceNotAvailableException {
+
+        String cmd = getInsecureDeviceAdbCommand(path, type);
+        String output = mDevice.executeShellCommand(cmd);
+        // Splitting an empty string results in an array of an empty string.
+        String [] found = output.length() > 0 ? output.split("\\s") : new String[0];
+        return new HashSet<String>(Arrays.asList(found));
+    }
+
+    private static String getInsecureDeviceAdbCommand(String path, String type) {
+        return String.format(INSECURE_DEVICE_ADB_COMMAND, path, type);
+    }
+}
diff --git a/suite/audio_quality/Android.mk b/suite/audio_quality/Android.mk
index 491596e..c3404d2 100644
--- a/suite/audio_quality/Android.mk
+++ b/suite/audio_quality/Android.mk
@@ -19,16 +19,19 @@
 
 CTS_AUDIO_TOP:= $(call my-dir)
 
+include $(call all-makefiles-under,$(CTS_AUDIO_TOP))
+
 CTS_AUDIO_INSTALL_DIR := $(HOST_OUT)/cts-audio-quality/android-cts-audio-quality
 CTS_AUDIO_QUALITY_ZIP := $(HOST_OUT)/cts-audio-quality/android-cts-audio-quality.zip
 
 cts_audio_quality_client_apk := $(TARGET_OUT_DATA_APPS)/CtsAudioClient/CtsAudioClient.apk
-cts_audio_quality_host_bins := $(HOST_OUT)/bin/cts_audio_quality_test $(HOST_OUT)/bin/cts_audio_quality
+cts_audio_quality_host_bins := $(ALL_MODULES.cts_audio_quality_test.INSTALLED) $(ALL_MODULES.cts_audio_quality.INSTALLED)
 $(CTS_AUDIO_QUALITY_ZIP): PRIVATE_CLIENT_APK := $(cts_audio_quality_client_apk)
 $(CTS_AUDIO_QUALITY_ZIP): PRIVATE_HOST_BINS := $(cts_audio_quality_host_bins)
 $(CTS_AUDIO_QUALITY_ZIP): PRIVATE_TEST_DESC := $(CTS_AUDIO_TOP)/test_description
 $(CTS_AUDIO_QUALITY_ZIP): $(cts_audio_quality_client_apk) $(cts_audio_quality_host_bins) \
     $(CTS_AUDIO_TOP)/test_description | $(ACP)
+	$(hide) rm -rf $@ $(CTS_AUDIO_INSTALL_DIR)
 	$(hide) mkdir -p $(CTS_AUDIO_INSTALL_DIR)/client
 	$(hide) $(ACP) -fp $(PRIVATE_CLIENT_APK) \
         $(CTS_AUDIO_INSTALL_DIR)/client
@@ -51,6 +54,4 @@
 $(call dist-for-goals, cts, $(CTS_AUDIO_QUALITY_ZIP))
 endif # cts
 
-include $(call all-subdir-makefiles)
-
 endif # linux
diff --git a/suite/audio_quality/executable/Android.mk b/suite/audio_quality/executable/Android.mk
index 8049596..26b5379 100644
--- a/suite/audio_quality/executable/Android.mk
+++ b/suite/audio_quality/executable/Android.mk
@@ -22,7 +22,8 @@
 LOCAL_STATIC_LIBRARIES += libutils liblog libcutils libtinyalsa libtinyxml
 LOCAL_WHOLE_STATIC_LIBRARIES := libcts_audio_quality
 LOCAL_CFLAGS:= -g -fno-exceptions
-LOCAL_LDFLAGS:= -g -lrt -ldl -lstdc++ -lm -fno-exceptions -lpthread
+LOCAL_LDFLAGS:= -g -lrt -ldl -lm -fno-exceptions -lpthread
+LOCAL_CXX_STL := libc++_static
 LOCAL_MODULE_HOST_OS := linux
 LOCAL_MODULE:= cts_audio_quality
 include $(BUILD_HOST_EXECUTABLE)
diff --git a/suite/audio_quality/lib/Android.mk b/suite/audio_quality/lib/Android.mk
index d4aaf84..44fbebb 100644
--- a/suite/audio_quality/lib/Android.mk
+++ b/suite/audio_quality/lib/Android.mk
@@ -17,7 +17,7 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := $(call all-subdir-cpp-files)
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/include $(LOCAL_PATH)/src /usr/include/ \
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/include $(LOCAL_PATH)/src \
 	external/tinyalsa/include/ external/tinyxml/ libcore/include
 LOCAL_STATIC_LIBRARIES += libutils liblog libtinyalsa libcutils libtinyxml
 LOCAL_CFLAGS:= -g -fno-exceptions
diff --git a/suite/audio_quality/test/Android.mk b/suite/audio_quality/test/Android.mk
index 21b0250..5af29f0 100644
--- a/suite/audio_quality/test/Android.mk
+++ b/suite/audio_quality/test/Android.mk
@@ -19,15 +19,26 @@
 LOCAL_SRC_FILES := $(call all-subdir-cpp-files)
 
 #$(info $(LOCAL_SRC_FILES))
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/../lib/include $(LOCAL_PATH)/../lib/src external/gtest/include \
-    external/tinyalsa/include/  libcore/include
-LOCAL_STATIC_LIBRARIES := libutils libgtest_host libgtest_main_host  liblog libcutils libtinyalsa \
-    libtinyxml
+LOCAL_C_INCLUDES := \
+    $(LOCAL_PATH)/../lib/include \
+    $(LOCAL_PATH)/../lib/src \
+    external/tinyalsa/include/ \
+    libcore/include \
+
+LOCAL_STATIC_LIBRARIES := \
+    libutils \
+    liblog \
+    libcutils \
+    libtinyalsa \
+    libtinyxml \
+
 # need to keep everything in libcts_.. Otherwise, linker will drop some
 # functions and linker error happens
 LOCAL_WHOLE_STATIC_LIBRARIES := libcts_audio_quality
 LOCAL_CFLAGS:= -g -fno-exceptions
 LOCAL_LDFLAGS:= -g -lrt -ldl -lm -fno-exceptions -lpthread
+LOCAL_CXX_STL := libc++_static
 LOCAL_MODULE_HOST_OS := linux
-LOCAL_MODULE:= cts_audio_quality_test
-include $(BUILD_HOST_EXECUTABLE)
+LOCAL_MODULE := cts_audio_quality_test
+LOCAL_MULTILIB := first
+include $(BUILD_HOST_NATIVE_TEST)
diff --git a/tests/aslr/Android.mk b/tests/aslr/Android.mk
index ebee2a8..3d1e1a6 100644
--- a/tests/aslr/Android.mk
+++ b/tests/aslr/Android.mk
@@ -18,6 +18,23 @@
 list_executable := $(test_executable)_list
 
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+LOCAL_MODULE := $(list_executable)
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+    src/AslrMallocTest.cpp
+
+LOCAL_CFLAGS := \
+    -DBUILD_ONLY \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog
+
+include $(BUILD_HOST_NATIVE_TEST)
+
+include $(CLEAR_VARS)
 LOCAL_MODULE:= $(test_executable)
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
@@ -42,21 +59,6 @@
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
+LOCAL_CTS_GTEST_LIST_EXECUTABLE := $(ALL_MODULES.$(list_executable).INSTALLED)
+
 include $(BUILD_CTS_EXECUTABLE)
-
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE := $(list_executable)
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := \
-    src/AslrMallocTest.cpp
-
-LOCAL_CFLAGS := \
-    -DBUILD_ONLY \
-
-LOCAL_SHARED_LIBRARIES := \
-    liblog
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/tests/core/libcore/conscrypt/Android.mk b/tests/core/libcore/conscrypt/Android.mk
index cd8559c..55beb9d 100644
--- a/tests/core/libcore/conscrypt/Android.mk
+++ b/tests/core/libcore/conscrypt/Android.mk
@@ -20,6 +20,6 @@
 
 include $(CLEAR_VARS)
 LOCAL_PACKAGE_NAME := android.core.tests.libcore.package.conscrypt
-LOCAL_STATIC_JAVA_LIBRARIES := core-tests conscrypt-tests
+LOCAL_STATIC_JAVA_LIBRARIES := conscrypt-tests mockito-target-minus-junit4
 LOCAL_JAVA_LANGUAGE_VERSION := 1.8
 include $(BUILD_CTSCORE_PACKAGE)
diff --git a/tests/core/runner/AndroidManifest.xml b/tests/core/runner/AndroidManifest.xml
index 05d210b..001e6f2 100644
--- a/tests/core/runner/AndroidManifest.xml
+++ b/tests/core/runner/AndroidManifest.xml
@@ -18,6 +18,8 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="android.core.tests.runner">
     <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
diff --git a/tests/dram/jni/Android.mk b/tests/dram/jni/Android.mk
index a86d4da..4469cc4 100644
--- a/tests/dram/jni/Android.mk
+++ b/tests/dram/jni/Android.mk
@@ -24,8 +24,6 @@
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
 
-LOCAL_SHARED_LIBRARIES := libnativehelper
-
 LOCAL_SDK_VERSION := 14
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/openglperf2/test/Android.mk b/tests/openglperf2/test/Android.mk
index e83e584..a9ec558 100644
--- a/tests/openglperf2/test/Android.mk
+++ b/tests/openglperf2/test/Android.mk
@@ -18,9 +18,9 @@
 LOCAL_SRC_FILES := $(call all-subdir-cpp-files)
 LOCAL_SRC_FILES += ../jni/graphics/Matrix.cpp
 
-LOCAL_C_INCLUDES += external/gtest/include $(LOCAL_PATH)/../jni/graphics/
-LOCAL_STATIC_LIBRARIES := libgtest_host libgtest_main_host liblog
+LOCAL_C_INCLUDES += $(LOCAL_PATH)/../jni/graphics/
+LOCAL_STATIC_LIBRARIES := liblog
 LOCAL_LDFLAGS:= -g -lpthread
 LOCAL_MODULE_HOST_OS := linux
 LOCAL_MODULE:= cts_device_opengl_test
-include $(BUILD_HOST_EXECUTABLE)
+include $(BUILD_HOST_NATIVE_TEST)
diff --git a/tests/simplecpu/jni/Android.mk b/tests/simplecpu/jni/Android.mk
index 946aa37..877f1b6 100644
--- a/tests/simplecpu/jni/Android.mk
+++ b/tests/simplecpu/jni/Android.mk
@@ -24,8 +24,6 @@
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
 
-LOCAL_SHARED_LIBRARIES := libnativehelper
-
 LOCAL_SDK_VERSION := 14
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/bionic/Android.mk b/tests/tests/bionic/Android.mk
index 627841f..fb9e0b9 100644
--- a/tests/tests/bionic/Android.mk
+++ b/tests/tests/bionic/Android.mk
@@ -3,6 +3,34 @@
 test_executable := CtsBionicTestCases
 list_executable := $(test_executable)_list
 
+ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE := $(list_executable)
+LOCAL_MULTILIB := both
+# Use the 32 bit list executable since it will include some 32 bit only tests.
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_LDLIBS += \
+    -lresolv -lrt -ldl -lutil \
+
+LOCAL_WHOLE_STATIC_LIBRARIES += \
+    libBionicTests \
+    libBionicCtsGtestMain \
+
+LOCAL_STATIC_LIBRARIES += \
+    libbase \
+    liblog \
+    libcutils \
+
+LOCAL_CXX_STL := libc++
+
+include $(BUILD_HOST_NATIVE_TEST)
+endif  # ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
+
 include $(CLEAR_VARS)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
@@ -26,36 +54,11 @@
     liblog \
     libgtest \
 
+# Use the 32 bit list executable since it will include some 32 bit only tests.
+LOCAL_CTS_GTEST_LIST_EXECUTABLE := $(ALL_MODULES.$(list_executable)$(HOST_2ND_ARCH_MODULE_SUFFIX).INSTALLED)
+
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
 LOCAL_CTS_TEST_PACKAGE := android.bionic
 include $(BUILD_CTS_EXECUTABLE)
-
-ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE := $(list_executable)
-LOCAL_MULTILIB := both
-# Use the 32 bit list executable since it will include some 32 bit only tests.
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-
-LOCAL_LDLIBS += \
-    -lrt -ldl -lutil \
-
-LOCAL_WHOLE_STATIC_LIBRARIES += \
-    libBionicTests \
-    libBionicCtsGtestMain \
-
-LOCAL_STATIC_LIBRARIES += \
-    libbase \
-    liblog \
-    libcutils \
-
-LOCAL_CXX_STL := libc++
-
-include $(BUILD_HOST_NATIVE_TEST)
-endif  # ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
diff --git a/tests/tests/graphics/jni/Android.mk b/tests/tests/graphics/jni/Android.mk
index 8c225a4..dd0d7e4 100644
--- a/tests/tests/graphics/jni/Android.mk
+++ b/tests/tests/graphics/jni/Android.mk
@@ -24,11 +24,7 @@
 	CtsGraphicsJniOnLoad.cpp \
 	android_graphics_cts_VulkanFeaturesTest.cpp
 
-LOCAL_C_INCLUDES := \
-	$(JNI_H_INCLUDE) \
-	external/vulkan-validation-layers/libs/vkjson
-
-LOCAL_STATIC_LIBRARIES := libvkjson
+LOCAL_STATIC_LIBRARIES := libvkjson_ndk
 LOCAL_SHARED_LIBRARIES := libvulkan liblog libdl
 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
index 8c74158..8a82706 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
+++ b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
@@ -45,10 +45,10 @@
 static const std::string kVendorLibraryPath = "/vendor/lib";
 #endif
 
-// This is not complete list - just a small subset
+// This is not the complete list - just a small subset
 // of the libraries that should reside in /system/lib
 // (in addition to kSystemPublicLibraries)
-static std::unordered_set<std::string> kSystemLibraries = {
+static std::vector<std::string> kSystemLibraries = {
     "libart.so",
     "libandroid_runtime.so",
     "libbinder.so",
@@ -61,39 +61,6 @@
     "libutils.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& public_library_path,
-                                 const std::unordered_set<std::string>& public_libraries,
-                                 const std::string& path) {
-  std::string name = basename(path.c_str());
-  return (public_libraries.find(name) != public_libraries.end()) &&
-         (public_library_path + "/" + name == path);
-}
-
 static bool is_directory(const std::string path) {
   struct stat sb;
   if (stat(path.c_str(), &sb) != -1) {
@@ -107,10 +74,18 @@
   return kSystemLibraryPath + "/libdl.so" == path;
 }
 
-static bool check_lib(const std::string& public_library_path,
-                      const std::unordered_set<std::string>& public_libraries,
-                      const std::string& path,
-                      std::string* error_msg) {
+static bool already_loaded(const std::string& library, const std::string& err) {
+  if (err.find("dlopen failed: library \"" + library + "\"") != 0 ||
+      err.find("is not accessible for the namespace \"classloader-namespace\"") == std::string::npos) {
+    return false;
+  }
+  return true;
+}
+
+static bool check_lib(const std::string& path,
+                      const std::string& library_path,
+                      const std::unordered_set<std::string>& libraries,
+                      std::vector<std::string>* errors) {
   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)
@@ -119,76 +94,118 @@
     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(public_library_path, public_libraries, path)) {
+  std::unique_ptr<void, int (*)(void*)> handle(dlopen(path.c_str(), RTLD_NOW), dlclose);
+
+  // The current restrictions on public libraries:
+  //  - It must exist only in the top level directory of "library_path".
+  //  - No library with the same name can be found in a sub directory.
+  //  - Each public library does not contain any directory components.
+
+  // Check if this library should be considered a public library.
+  std::string baselib = basename(path.c_str());
+  if (libraries.find(baselib) != libraries.end() &&
+      library_path + "/" + baselib == path) {
     if (handle.get() == nullptr) {
-      *error_msg = "The library \"" + path + "\" should be accessible but isn't: " + dlerror();
+      errors->push_back("The library \"" + path +
+                        "\" is a public library but it cannot be loaded: " + dlerror());
       return false;
     }
-  } else if (handle != nullptr) {
-    *error_msg = "The library \"" + path + "\" should not be accessible";
+  } else if (handle.get() != nullptr) {
+    errors->push_back("The library \"" + path + "\" is not a public library but it loaded.");
     return false;
   } else { // (handle == nullptr && !shouldBeAccessible(path))
     // Check the error message
     std::string err = dlerror();
-
-    if (err.find("dlopen failed: library \"" + path + "\"") != 0 ||
-        err.find("is not accessible for the namespace \"classloader-namespace\"") == std::string::npos) {
-      *error_msg = "unexpected dlerror: " + err;
+    if (!already_loaded(path, err)) {
+      errors->push_back("unexpected dlerror: " + err);
       return false;
     }
   }
   return true;
 }
 
-static bool check_libs(const std::string& public_library_path,
-                       const std::unordered_set<std::string>& public_libraries,
-                       const std::unordered_set<std::string>& mandatory_files,
-                       std::string* error) {
-  std::list<std::string> dirs;
-  dirs.push_back(public_library_path);
-
+static bool check_path(const std::string& library_path,
+                       const std::unordered_set<std::string> libraries,
+                       std::vector<std::string>* errors) {
+  bool success = true;
+  std::list<std::string> dirs = { library_path };
   while (!dirs.empty()) {
-    const auto dir = dirs.front();
+    std::string dir = dirs.front();
     dirs.pop_front();
-    bool success = for_each_file(dir, [&](const char* name, std::string* error_msg) {
-      std::string path = dir + "/" + name;
+
+    auto dir_deleter = [](DIR* handle) { closedir(handle); };
+    std::unique_ptr<DIR, decltype(dir_deleter)> dirp(opendir(dir.c_str()), dir_deleter);
+    if (dirp == nullptr) {
+      errors->push_back("Failed to open " + dir + ": " + strerror(errno));
+      success = false;
+      continue;
+    }
+
+    dirent* dp;
+    while ((dp = readdir(dirp.get())) != nullptr) {
+      // skip "." and ".."
+      if (strcmp(".", dp->d_name) == 0 || strcmp("..", dp->d_name) == 0) {
+        continue;
+      }
+
+      std::string path = dir + "/" + dp->d_name;
       if (is_directory(path)) {
         dirs.push_back(path);
-        return true;
-      }
-
-      return check_lib(public_library_path, public_libraries, path, error_msg);
-    }, error);
-
-    if (!success) {
-      return false;
-    }
-
-    // Check mandatory files - the grey list
-    for (const auto& name : mandatory_files) {
-      std::string path = public_library_path + "/" + name;
-      if (!check_lib(public_library_path, public_libraries, path, error)) {
-        return false;
+      } else if (!check_lib(path, library_path, libraries, errors)) {
+        success = false;
       }
     }
   }
 
-  return true;
+  return success;
 }
 
-static void jobject_array_to_set(JNIEnv* env,
+static bool jobject_array_to_set(JNIEnv* env,
                                  jobjectArray java_libraries_array,
-                                 std::unordered_set<std::string>* libraries) {
+                                 std::unordered_set<std::string>* libraries,
+                                 std::string* error_msg) {
+  error_msg->clear();
   size_t size = env->GetArrayLength(java_libraries_array);
+  bool success = true;
   for (size_t i = 0; i<size; ++i) {
     ScopedLocalRef<jstring> java_soname(
         env, (jstring) env->GetObjectArrayElement(java_libraries_array, i));
+    std::string soname(ScopedUtfChars(env, java_soname.get()).c_str());
 
-    ScopedUtfChars soname(env, java_soname.get());
-    libraries->insert(soname.c_str());
+    // Verify that the name doesn't contain any directory components.
+    if (soname.rfind('/') != std::string::npos) {
+      *error_msg += "\n---Illegal value, no directories allowed: " + soname;
+      continue;
+    }
+
+    // Check to see if the string ends in " 32" or " 64" to indicate the
+    // library is only public for one bitness.
+    size_t space_pos = soname.rfind(' ');
+    if (space_pos != std::string::npos) {
+      std::string type = soname.substr(space_pos + 1);
+      if (type != "32" && type != "64") {
+        *error_msg += "\n---Illegal value at end of line (only 32 or 64 allowed): " + soname;
+        success = false;
+        continue;
+      }
+#if defined(__LP64__)
+      if (type == "32") {
+        // Skip this, it's a 32 bit only public library.
+        continue;
+      }
+#else
+      if (type == "64") {
+        // Skip this, it's a 64 bit only public library.
+        continue;
+      }
+#endif
+      soname.resize(space_pos);
+    }
+
+    libraries->insert(soname);
   }
+
+  return success;
 }
 
 extern "C" JNIEXPORT jstring JNICALL
@@ -197,17 +214,55 @@
         jclass clazz __attribute__((unused)),
         jobjectArray java_system_public_libraries,
         jobjectArray java_vendor_public_libraries) {
-  std::string error;
-
+  bool success = true;
+  std::vector<std::string> errors;
+  std::string error_msg;
   std::unordered_set<std::string> vendor_public_libraries;
-  std::unordered_set<std::string> system_public_libraries;
-  std::unordered_set<std::string> empty_set;
-  jobject_array_to_set(env, java_vendor_public_libraries, &vendor_public_libraries);
-  jobject_array_to_set(env, java_system_public_libraries, &system_public_libraries);
+  if (!jobject_array_to_set(env, java_vendor_public_libraries, &vendor_public_libraries,
+                            &error_msg)) {
+    success = false;
+    errors.push_back("Errors in vendor public library file:" + error_msg);
+  }
 
-  if (!check_libs(kSystemLibraryPath, system_public_libraries, kSystemLibraries, &error) ||
-      !check_libs(kVendorLibraryPath, vendor_public_libraries, empty_set, &error)) {
-    return env->NewStringUTF(error.c_str());
+  std::unordered_set<std::string> system_public_libraries;
+  if (!jobject_array_to_set(env, java_system_public_libraries, &system_public_libraries,
+                            &error_msg)) {
+    success = false;
+    errors.push_back("Errors in system public library file:" + error_msg);
+  }
+
+  // Check the system libraries.
+  if (!check_path(kSystemLibraryPath, system_public_libraries, &errors)) {
+    success = false;
+  }
+
+  // Check that the mandatory system libraries are present - the grey list
+  for (const auto& name : kSystemLibraries) {
+    std::string library = kSystemLibraryPath + "/" + name;
+    void* handle = dlopen(library.c_str(), RTLD_NOW);
+    if (handle == nullptr) {
+      std::string err = dlerror();
+      // If the library is already loaded, then dlopen failing is okay.
+      if (!already_loaded(library, err)) {
+          errors.push_back("Mandatory system library \"" + library + "\" failed to load: " + err);
+          success = false;
+      }
+    } else {
+      dlclose(handle);
+    }
+  }
+
+  // Check the vendor libraries.
+  if (!check_path(kVendorLibraryPath, vendor_public_libraries, &errors)) {
+    success = false;
+  }
+
+  if (!success) {
+    std::string error_str;
+    for (const auto& line : errors) {
+      error_str += line + '\n';
+    }
+    return env->NewStringUTF(error_str.c_str());
   }
 
   return nullptr;
diff --git a/tests/tests/jni/libjnitest/helper.h b/tests/tests/jni/libjnitest/helper.h
index 58a3407..f811055 100644
--- a/tests/tests/jni/libjnitest/helper.h
+++ b/tests/tests/jni/libjnitest/helper.h
@@ -37,7 +37,7 @@
  * the given name. The function is static, returns a (char *), and
  * takes a (JNIEnv *) named "env".
  */
-#define TEST_DECLARATION(name) static char *test_##name(JNIEnv *env)
+#define TEST_DECLARATION(name) static char *test_##name(JNIEnv *env) /* NOLINT */
     
 /**
  * Logs and returns an error message, passed and formatted in printf()
diff --git a/tests/tests/libcorefileio/Android.mk b/tests/tests/libcorefileio/Android.mk
new file mode 100644
index 0000000..29226bf
--- /dev/null
+++ b/tests/tests/libcorefileio/Android.mk
@@ -0,0 +1,33 @@
+# 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# don't include this package in any target
+LOCAL_MODULE_TAGS := optional
+# and when built explicitly put it in the data partition
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := CtsLibcoreFileIOTestCases
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/libcorefileio/AndroidManifest.xml b/tests/tests/libcorefileio/AndroidManifest.xml
new file mode 100644
index 0000000..411aa9d
--- /dev/null
+++ b/tests/tests/libcorefileio/AndroidManifest.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.libcorefileio.cts">
+
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+
+    <application>
+        <uses-library android:name="android.test.runner"/>
+        <service android:name="android.cts.LockHoldingService"
+                 android:process=":lockHoldingService"
+                 android:permission="android.permission.WRITE_EXTERNAL_STORAGE"
+        />
+        <receiver android:name="android.cts.FileChannelInterProcessLockTest$IntentReceiver">
+
+            <intent-filter>
+                <action android:name="android.cts.CtsLibcoreFileIOTestCases">
+                </action>
+            </intent-filter>
+
+        </receiver>
+    </application>
+
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.libcorefileio.cts">
+        <meta-data android:name="listener"
+                   android:value="com.android.cts.runner.CtsTestRunListener"/>
+    </instrumentation>
+
+</manifest>
+
diff --git a/tests/tests/libcorefileio/AndroidTest.xml b/tests/tests/libcorefileio/AndroidTest.xml
new file mode 100644
index 0000000..9baa713
--- /dev/null
+++ b/tests/tests/libcorefileio/AndroidTest.xml
@@ -0,0 +1,23 @@
+<!-- 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.
+-->
+<configuration description="Config for CTS Legacy Libcore test cases">
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.ApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsLibcoreFileIOTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.libcorefileio.cts" />
+    </test>
+</configuration>
\ No newline at end of file
diff --git a/tests/tests/libcorefileio/src/android/cts/FileChannelInterProcessLockTest.java b/tests/tests/libcorefileio/src/android/cts/FileChannelInterProcessLockTest.java
new file mode 100644
index 0000000..4259e4c
--- /dev/null
+++ b/tests/tests/libcorefileio/src/android/cts/FileChannelInterProcessLockTest.java
@@ -0,0 +1,551 @@
+/*
+ * 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.cts;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Environment;
+import android.test.AndroidTestCase;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.channels.FileLock;
+import java.util.concurrent.CountDownLatch;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@SuppressWarnings("deprecation")
+public class FileChannelInterProcessLockTest extends AndroidTestCase {
+
+    /** The directory where file locks are created */
+    final static String DIR_NAME = "CtsFileIOTest";
+
+    /** The name of the file used when acquiring a lock. */
+    final static String FILE_NAME = "file";
+
+    /** The position in the lock file used when acquiring a region lock. */
+    final static int LOCK_POSITION = 10;
+
+    /** The extent of the lock file locked when acquiring a region lock. */
+    final static int LOCK_SIZE = 10;
+
+    /**
+     * This is the maximum waiting time in seconds for the test to wait for a response from
+     * the service. This provides ample amount of time for the service to receive the request from
+     * the test, then act, and respond back.
+     */
+    final static int MAX_WAIT_TIME = 7;
+
+    @Override
+    public void tearDown() throws Exception {
+        stopService();
+        super.tearDown();
+    }
+
+    /**
+     * java.nio.channels.FileChannel#tryLock()
+     *
+     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
+     * and checks the behavior.
+     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
+     * expectedLockLockResult: {@code true} if the returned lock should be valid,
+     * {@code false} otherwise.
+     */
+    public void test_tryLock() throws Exception {
+        checkTryLockBehavior(LockType.TRY_LOCK, LockType.TRY_LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.TRY_LOCK, LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.TRY_LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.TRY_LOCK, LockType.LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.TRY_LOCK, LockType.LOCK_ON_REGION_WITH_LOCK,
+                false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.TRY_LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                false /* expectToGetLock */);
+    }
+
+    /**
+     * java.nio.channels.FileChannel#tryLock(long, long, boolean)
+     *
+     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
+     * and checks the behavior.
+     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
+     * expectedLockLockResult: {@code true} if the returned lock should be valid,
+     * {@code false} otherwise.
+     */
+    public void test_tryLockJJZ_Exclusive() throws Exception {
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
+                false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_REGION_WITH_TRY_LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK, true /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
+                true /* expectToGetLock */);
+
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK, LockType.LOCK,
+                false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_REGION_WITH_LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK, true /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
+                true /* expectToGetLock */);
+    }
+
+    /**
+     * java.nio.channels.FileChannel#tryLock(long, long, boolean)
+     *
+     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
+     * and checks the behavior.
+     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
+     * expectedLockLockResult: {@code true} if the returned lock should be valid,
+     * {@code false} otherwise.
+     */
+    public void test_tryLockJJZ_Shared() throws Exception {
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, LockType.TRY_LOCK,
+                false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_REGION_WITH_TRY_LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK, true /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, true /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
+                true /* expectToGetLock */);
+
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, LockType.LOCK,
+                false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_REGION_WITH_LOCK, false /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK, true /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, true /* expectToGetLock */);
+        checkTryLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
+                true /* expectToGetLock */);
+    }
+
+    /**
+     * java.nio.channels.FileChannel#lock()
+     *
+     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
+     * and checks the behavior.
+     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
+     * expectedLockLockResult: {@code true} if it blocks the local thread, {@code false} otherwise.
+     */
+    public void test_lock() throws Exception {
+        checkLockBehavior(LockType.LOCK, LockType.LOCK, true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK, LockType.LOCK_ON_REGION_WITH_LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                true /* expectToWait */);
+
+        checkLockBehavior(LockType.LOCK, LockType.TRY_LOCK, true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK, LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK, LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+                true /* expectToWait */);
+    }
+
+    /**
+     * java.nio.channels.FileChannel#lock(long, long, boolean)
+     *
+     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
+     * and checks the behavior.
+     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
+     * expectedLockLockResult: {@code true} if blocks the local thread, {@code false} otherwise.
+     */
+    public void test_lockJJZ_Exclusive() throws Exception {
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK_ON_REGION_WITH_LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK, false /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK, false /* expectToWait */);
+
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.TRY_LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK, LockType.LOCK_ON_REGION_WITH_TRY_LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, true /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK, false /* expectToWait */);
+        checkLockBehavior(LockType.LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
+                false /* expectToWait */);
+    }
+
+    /**
+     * java.nio.channels.FileChannel#lock(long, long, boolean)
+     *
+     * Obtains a remote lock, then attempts to acquire a local lock on the same file,
+     * and checks the behavior.
+     * checkTryLockBehavior(localLockType, remoteLockType, expectedLocalLockResult)
+     * expectedLockLockResult: {@code true} if blocks the local thread, {@code false} otherwise.
+     */
+    public void test_lockJJZ_Shared() throws Exception {
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, LockType.LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.LOCK_ON_REGION_WITH_LOCK, true /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, false /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK, false /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK, false /* expectToWait */);
+
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK, LockType.TRY_LOCK,
+                true /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.LOCK_ON_REGION_WITH_TRY_LOCK, true /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_REGION_WITH_TRY_LOCK, false /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK, false /* expectToWait */);
+        checkLockBehavior(LockType.SHARED_LOCK_ON_REGION_WITH_LOCK,
+                LockType.SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
+                false /* expectToWait */);
+    }
+
+    /**
+     * Checks the behavior of java.nio.Channels.FileChannel#tryLock() and #tryLock(J, J, Z)
+     *
+     * @param localLockType the type of lock to be acquired by the test
+     * @param remoteLockType the type of lock to be acquired by the remote service
+     * @param expectToGetLock {@code true}, if the lock should be acquired even when the
+     *         service holds a {@code remoteLockType} lock, false otherwise.
+     */
+    private void checkTryLockBehavior(LockType localLockType, LockType remoteLockType,
+            boolean expectToGetLock) throws Exception {
+        IntentReceiver.resetReceiverState();
+
+        // Request that the remote lock be obtained.
+        getContext().startService(new Intent(getContext(), LockHoldingService.class)
+                .putExtra(LockHoldingService.LOCK_TYPE_KEY, remoteLockType));
+
+        // Wait for a signal that the remote lock is definitely held.
+        assertTrue(IntentReceiver.lockHeldLatch.await(MAX_WAIT_TIME, SECONDS));
+
+        // Try to acquire the local lock in all cases and check whether it could be acquired or
+        // not as expected.
+        if (expectToGetLock) {
+            FileLock fileLock = acquire(localLockType);
+            assertNotNull(fileLock);
+            assertTrue(fileLock.isValid());
+        } else {
+            assertNull(acquire(localLockType));
+        }
+        // Release the remote lock.
+        stopService();
+    }
+
+    /**
+     * Checks the java.nio.channels.FileChannel.lock()/lock(J, J, Z) behavior.
+     *
+     * @param localLockType type of lock to be acquired by the test
+     * @param remoteLockType type of lock to be acquired by the remote service.
+     * @param expectToWait {@code true}, if the local thread must wait for the remote
+     *         service to release the lock, {@code false} otherwise.
+     */
+    private void checkLockBehavior(LockType localLockType, LockType remoteLockType,
+            boolean expectToWait) throws Exception {
+        IntentReceiver.resetReceiverState();
+
+        // The amount of time the remote service should hold lock.
+        long remoteLockHoldTimeMillis = 5000;
+
+        // The amount of time test should get to try to acquire the lock.
+        long sufficientOverlappingTimeInMillis = 2000;
+
+        // This is the allowable delta in the time between the time recorded after the service
+        // released the lock and the time recorded after the test obtained the lock.
+        long lockReleasedAndReacquiredTimeDeltaInMillis = 500;
+
+        // Tell the service to acquire a remote lock.
+        Intent sendIntent = new Intent(getContext(), LockHoldingService.class)
+                .putExtra(LockHoldingService.TIME_TO_HOLD_LOCK_KEY, remoteLockHoldTimeMillis)
+                .putExtra(LockHoldingService.LOCK_TYPE_KEY, remoteLockType)
+                .putExtra(LockHoldingService.LOCK_BEHAVIOR_RELEASE_AND_NOTIFY_KEY, true);
+
+        getContext().startService(sendIntent);
+
+        // Wait for the service to hold the lock and notify for the same.
+        assertTrue(IntentReceiver.lockHeldLatch.await(MAX_WAIT_TIME, SECONDS));
+
+        long localLockNotObtainedTime = System.currentTimeMillis();
+
+        // Acquire the lock locally.
+        FileLock fileLock = acquire(localLockType);
+        long localLockObtainedTime = System.currentTimeMillis();
+
+        // Wait until the remote lock has definitely been released.
+        assertTrue(IntentReceiver.lockReleasedLatch.await(MAX_WAIT_TIME, SECONDS));
+
+        Bundle remoteLockReleasedBundle = IntentReceiver.lockReleasedBundle;
+        long remoteLockNotReleasedTime =
+                remoteLockReleasedBundle.getLong(LockHoldingService.LOCK_NOT_YET_RELEASED_TIMESTAMP);
+        long remoteLockReleasedTime =
+                remoteLockReleasedBundle.getLong(LockHoldingService.LOCK_DEFINITELY_RELEASED_TIMESTAMP);
+
+        // We want the test to be notified well before the service releases the lock, so that
+        // we can be sure that it tried obtaining the lock before the service actually released it.
+        // Therefore, a two seconds time interval provides the test to get prepare and try to obtain
+        // the lock. If this fails, it doesn't mean they definitely didn't overlap
+        // but we can't be sure and the test may not be valid. This is why we hold the lock
+        // remotely for a long time compared to the delays we expect for intents to propagate
+        // between processes.
+        assertTrue(remoteLockNotReleasedTime - localLockNotObtainedTime >
+                sufficientOverlappingTimeInMillis);
+
+        if (expectToWait) {
+
+            // The remoteLockReleaseTime is captured after the lock was released by the
+            // service. The localLockObtainedTime is captured after the lock was obtained by this
+            // thread. Therefore, there is a degree of slop inherent in the two times. We assert
+            // that they are "close" to each other, but we cannot assert any ordering.
+            assertTrue(Math.abs(localLockObtainedTime - remoteLockReleasedTime) <
+                    lockReleasedAndReacquiredTimeDeltaInMillis);
+        } else {
+            // The remoteLockNotReleaseTime is captured before the lock was released by the
+            // service. The localLockObtainedTime is captured after the lock was obtained by this
+            // thread. The local thread should be able to get the lock before the remote thread
+            // definitely release it. If this test fails it may not indicate a problem, but it
+            // indicates we cannot be sure the test was successful the local lock attempt and the
+            // remote lock attempt did not overlap.
+            assertTrue(localLockObtainedTime < remoteLockNotReleasedTime);
+        }
+
+        // Asserting if the fileLock is valid.
+        assertTrue(fileLock.isValid());
+        stopService();
+    }
+
+    /**
+     * Requests and waits for the service to stop
+     */
+    void stopService() throws Exception {
+        getContext().stopService(new Intent(getContext(), LockHoldingService.class));
+        assertTrue(IntentReceiver.onStopLatch.await(MAX_WAIT_TIME, SECONDS));
+        deleteDir();
+    }
+
+    enum LockType {
+
+        /** Equivalent to {@code tryLock()} */
+        TRY_LOCK,
+
+        /** Equivalent to  {@code tryLock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, false)} */
+        LOCK_ON_REGION_WITH_TRY_LOCK,
+
+        /**
+         * Equivalent to  {@code tryLock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
+         * {@link #LOCK_SIZE}, false)}
+         */
+        LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
+
+        /** Equivalent to  {@code tryLock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, true)} */
+        SHARED_LOCK_ON_REGION_WITH_TRY_LOCK,
+
+        /**
+         * Equivalent to  {@code tryLock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
+         * {@link #LOCK_SIZE}, true)}
+         */
+        SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK,
+
+        /** Equivalent to  {@code lock()} */
+        LOCK,
+
+        /** Equivalent to  {code lock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, false)} */
+        LOCK_ON_REGION_WITH_LOCK,
+
+        /**
+         * Equivalent to  {@code lock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
+         * {@link #LOCK_SIZE}, false)}
+         */
+        LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
+
+        /** Equivalent to  {@code lock({@link #LOCK_POSITION}, {@link #LOCK_SIZE}, true)} */
+        SHARED_LOCK_ON_REGION_WITH_LOCK,
+
+        /**
+         * Equivalent to {@code lock({@code {@link #LOCK_POSITION} + {@link #LOCK_SIZE}},
+         * {@link #LOCK_SIZE}, true)}
+         */
+        SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK,
+    }
+
+    /**
+     * Tries to acquire a lock of {@code lockType} on the file returned by
+     * {@link #createFileInDir()} method.
+     *
+     * @param lockType a {@link LockType} enum.
+     *         Permitted lock types:
+     *         {@link LockType#TRY_LOCK}
+     *         {@link LockType#LOCK_ON_REGION_WITH_TRY_LOCK}
+     *         {@link LockType#LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK}
+     *         {@link LockType#SHARED_LOCK_ON_REGION_WITH_TRY_LOCK}
+     *         {@link LockType#SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK}
+     *         {@link LockType#LOCK}
+     *         {@link LockType#LOCK_ON_REGION_WITH_LOCK}
+     *         {@link LockType#LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK}
+     *         {@link LockType#SHARED_LOCK_ON_REGION_WITH_LOCK}
+     *         {@link LockType#SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK}
+     * @return Returns the lock returned by the lock method.
+     * @throws UnsupportedOperationException
+     *         If the {@code lockType} is of non recognized type.
+     */
+    static FileLock acquire(LockType lockType) throws IOException {
+        File file = createFileInDir();
+        file.createNewFile();
+        switch (lockType) {
+            case TRY_LOCK:
+                return new FileOutputStream(file).getChannel().tryLock();
+            case LOCK_ON_REGION_WITH_TRY_LOCK:
+                return new FileOutputStream(file).getChannel()
+                        .tryLock(LOCK_POSITION, LOCK_SIZE, false /*isShared*/);
+            case LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK:
+                return new FileOutputStream(file).getChannel()
+                        .tryLock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, false /*isShared*/);
+            case SHARED_LOCK_ON_REGION_WITH_TRY_LOCK:
+                return new FileInputStream(file).getChannel()
+                        .tryLock(LOCK_POSITION, LOCK_SIZE, true /*isShared*/);
+            case SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_TRY_LOCK:
+                return new FileInputStream(file).getChannel()
+                        .tryLock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, true /*isShared*/);
+            case LOCK:
+                return new FileOutputStream(file).getChannel().lock();
+            case LOCK_ON_REGION_WITH_LOCK:
+                return new FileOutputStream(file).getChannel()
+                        .lock(LOCK_POSITION, LOCK_SIZE, false /*isShared*/);
+            case LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK:
+                return new FileOutputStream(file).getChannel()
+                        .lock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, false /*isShared*/);
+            case SHARED_LOCK_ON_REGION_WITH_LOCK:
+                return new FileInputStream(file).getChannel()
+                        .lock(LOCK_POSITION, LOCK_SIZE, true /*isShared*/);
+            case SHARED_LOCK_ON_NON_OVERLAPPING_REGION_WITH_LOCK:
+                return new FileInputStream(file).getChannel()
+                        .lock(LOCK_POSITION + LOCK_SIZE, LOCK_SIZE, true /*isShared*/);
+            default:
+                throw new UnsupportedOperationException("Unknown lock type");
+        }
+    }
+
+    /**
+     * Creates a file named {@link #FILE_NAME} inside a directory named {@link #DIR_NAME} on
+     * the external storage directory.
+     */
+    static File createFileInDir() throws IOException {
+        File dir = new File(Environment.getExternalStorageDirectory(), DIR_NAME);
+        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+            throw new IOException("External storage is not mounted");
+        } else if (!dir.mkdirs() && !dir.isDirectory()) {
+            throw new IOException("Cannot create directory for device info files");
+        } else {
+            return new File(dir, FILE_NAME);
+        }
+    }
+
+    /**
+     * Deletes the folder {@link #DIR_NAME} on the external storage directory along with all the
+     * files inside it.
+     */
+    static void deleteDir() {
+        File dir = new File(Environment.getExternalStorageDirectory(), DIR_NAME);
+        if (dir.isDirectory()) {
+            String[] children = dir.list();
+            for (String child : children) {
+                new File(dir, child).delete();
+            }
+            dir.delete();
+        }
+    }
+
+    /**
+     * Listens to broadcasts sent by the LockHoldingService and records information / provides
+     * latches so the test code can synchronize until it is informed the service has acted on
+     * requests it has sent.
+     */
+    public static class IntentReceiver extends BroadcastReceiver {
+
+        static CountDownLatch onStartLatch;
+
+        static CountDownLatch onStopLatch;
+
+        static CountDownLatch lockHeldLatch;
+
+        static volatile Bundle lockHeldBundle;
+
+        static CountDownLatch lockReleasedLatch;
+
+        static volatile Bundle lockReleasedBundle;
+
+        /**
+         * Reset the IntentReceiver for a new test. Assumes no intents will be received from prior
+         *  tests.
+         */
+        public static synchronized void resetReceiverState() {
+            onStartLatch = new CountDownLatch(1);
+            onStopLatch = new CountDownLatch(1);
+            lockHeldLatch = new CountDownLatch(1);
+            lockReleasedLatch = new CountDownLatch(1);
+            lockHeldBundle = null;
+            lockReleasedBundle = null;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            String msg = intent.getStringExtra(LockHoldingService.NOTIFICATION_KEY);
+            switch (msg) {
+                case LockHoldingService.NOTIFICATION_START:
+                    onStartLatch.countDown();
+                    break;
+                case LockHoldingService.NOTIFICATION_STOP:
+                    onStopLatch.countDown();
+                    break;
+                case LockHoldingService.NOTIFICATION_LOCK_HELD:
+                    lockHeldBundle = intent.getExtras();
+                    lockHeldLatch.countDown();
+                    break;
+                case LockHoldingService.NOTIFICATION_LOCK_RELEASED:
+                    lockReleasedBundle = intent.getExtras();
+                    lockReleasedLatch.countDown();
+                    break;
+            }
+        }
+    }
+}
+
diff --git a/tests/tests/libcorefileio/src/android/cts/LockHoldingService.java b/tests/tests/libcorefileio/src/android/cts/LockHoldingService.java
new file mode 100644
index 0000000..6ac73b0
--- /dev/null
+++ b/tests/tests/libcorefileio/src/android/cts/LockHoldingService.java
@@ -0,0 +1,177 @@
+/*
+ * 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.cts;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.util.Log;
+
+import java.io.IOException;
+import java.nio.channels.FileLock;
+
+/**
+ * A Service that listens for commands from the FileChannelInterProcessLockTest to acquire locks of
+ * different types. It exists to test the behavior when file locks are acquired/released across
+ * multiple processes.
+ */
+public class LockHoldingService extends Service {
+
+    /**
+     *  The key of the Bundle extra used to record a time after a lock is released by the service.
+     */
+    static final String LOCK_DEFINITELY_RELEASED_TIMESTAMP = "lockReleasedTimestamp";
+
+    /**
+     * The key of the Bundle extra used to record just before the lock is released by the service.
+     */
+    static final String LOCK_NOT_YET_RELEASED_TIMESTAMP = "lockNotReleasedTimestamp";
+
+    /**
+     * The key of the Bundle extra used to send general notifications to the test.
+     */
+    static final String NOTIFICATION_KEY = "notification";
+
+    /**
+     * The value for the notification sent to the test after the service starts.
+     */
+    static final String NOTIFICATION_START = "onStart";
+
+    /**
+     * The value for the notification sent to the test just before the service stops.
+     */
+    static final String NOTIFICATION_STOP = "onStop";
+
+    /**
+     * The value for the notification sent to the test after the lock is acquired.
+     */
+    static final String NOTIFICATION_LOCK_HELD = "lockHeld";
+
+    /**
+     * The value for the notification sent to the test after the lock is released
+     */
+    static final String NOTIFICATION_LOCK_RELEASED = "lockReleased";
+
+    /**
+     * The key of the Bundle extra used to send time for which the service should wait before
+     * releasing the lock.
+     */
+    static final String TIME_TO_HOLD_LOCK_KEY = "timeToHoldLock";
+
+    /**
+     * The key of the Bundle extra used for the type of lock to be held.
+     */
+    static final String LOCK_TYPE_KEY = "lockType";
+
+    /**
+     * The key of the Bundle extra used to let he service know whether to release the lock after
+     * some time.
+     */
+    static final String LOCK_BEHAVIOR_RELEASE_AND_NOTIFY_KEY = "releaseAndNotify";
+
+    static final String ACTION_TYPE_FOR_INTENT_COMMUNICATION
+            = "android.cts.CtsLibcoreFileIOTestCases";
+
+    final String LOG_MESSAGE_TAG = "CtsLibcoreFileIOTestCases";
+
+    private FileLock fileLock = null;
+
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startID) {
+        try {
+            if (intent.getBooleanExtra(LOCK_BEHAVIOR_RELEASE_AND_NOTIFY_KEY, false)) {
+                acquireLockAndThenWaitThenRelease(intent);
+            } else {
+                acquireLock(intent);
+            }
+        } catch (Exception e) {
+            Log.e(LOG_MESSAGE_TAG, e.getMessage());
+        }
+        return START_STICKY;
+    }
+
+    /**
+     * Acquires the lock asked by the test indefinitely.
+     */
+    private void acquireLock(Intent intent) throws IOException {
+        FileChannelInterProcessLockTest.LockType lockType =
+                (FileChannelInterProcessLockTest.LockType)intent.getSerializableExtra(
+                        LOCK_TYPE_KEY);
+
+        // Acquire the lock based on the information contained in the intent received.
+        this.fileLock = FileChannelInterProcessLockTest.acquire(lockType);
+        Intent responseIntent = new Intent().putExtra(NOTIFICATION_KEY, NOTIFICATION_LOCK_HELD)
+                .setAction(ACTION_TYPE_FOR_INTENT_COMMUNICATION);
+        sendBroadcast(responseIntent);
+    }
+
+    /**
+     * Acquires and holds the lock for a time specified by the test. Sends a broadcast message after
+     * releasing the lock.
+     */
+    private void acquireLockAndThenWaitThenRelease(Intent intent)
+            throws IOException, InterruptedException {
+        long lockHoldTimeMillis = intent.getLongExtra(TIME_TO_HOLD_LOCK_KEY, 0);
+
+        // Acquire the lock.
+        FileChannelInterProcessLockTest.LockType lockType =
+                (FileChannelInterProcessLockTest.LockType)intent.getSerializableExtra(
+                        LOCK_TYPE_KEY);
+        this.fileLock = FileChannelInterProcessLockTest.acquire(lockType);
+
+        // Signal the lock is now held.
+        Intent heldIntent = new Intent()
+                .putExtra(NOTIFICATION_KEY, NOTIFICATION_LOCK_HELD)
+                .setAction(ACTION_TYPE_FOR_INTENT_COMMUNICATION);
+        sendBroadcast(heldIntent);
+
+        Thread.sleep(lockHoldTimeMillis);
+
+        long lockNotReleasedTimestamp = System.currentTimeMillis();
+
+        // Release the lock
+        fileLock.release();
+
+        long lockReleasedTimestamp = System.currentTimeMillis();
+
+        // Signal the lock is released and some information about timing.
+        Intent releaseIntent = new Intent()
+                .putExtra(NOTIFICATION_KEY, NOTIFICATION_LOCK_RELEASED)
+                .putExtra(LOCK_NOT_YET_RELEASED_TIMESTAMP, lockNotReleasedTimestamp)
+                .putExtra(LOCK_DEFINITELY_RELEASED_TIMESTAMP, lockReleasedTimestamp)
+                .setAction(ACTION_TYPE_FOR_INTENT_COMMUNICATION);
+        sendBroadcast(releaseIntent);
+    }
+
+    @Override
+    public void onDestroy() {
+        try {
+            if (fileLock != null) {
+                fileLock.release();
+            }
+        } catch (IOException e) {
+            Log.e(LOG_MESSAGE_TAG, e.getMessage());
+        }
+        Intent intent = new Intent().putExtra(NOTIFICATION_KEY, NOTIFICATION_STOP)
+                .setAction(ACTION_TYPE_FOR_INTENT_COMMUNICATION);
+        sendBroadcast(intent);
+    }
+}
diff --git a/tests/tests/media/libaudiojni/sl-utils.cpp b/tests/tests/media/libaudiojni/sl-utils.cpp
index 4dbb08d..e6debd9 100644
--- a/tests/tests/media/libaudiojni/sl-utils.cpp
+++ b/tests/tests/media/libaudiojni/sl-utils.cpp
@@ -20,7 +20,7 @@
 #include "sl-utils.h"
 #include <utils/Mutex.h>
 
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
 
 // These will wind up in <SLES/OpenSLES_Android.h>
 #define SL_ANDROID_SPEAKER_QUAD (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT \
diff --git a/tests/tests/nativemedia/sl/Android.mk b/tests/tests/nativemedia/sl/Android.mk
index e782994..7b369e5 100644
--- a/tests/tests/nativemedia/sl/Android.mk
+++ b/tests/tests/nativemedia/sl/Android.mk
@@ -22,6 +22,24 @@
 include $(CLEAR_VARS)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
+LOCAL_MODULE := $(list_executable)
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+    src/SLObjectCreationTest.cpp
+
+LOCAL_CFLAGS := \
+    -DBUILD_ONLY \
+    -Werror -Wall
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+
+include $(BUILD_HOST_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
 LOCAL_MODULE := $(test_executable)
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
@@ -30,7 +48,6 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 LOCAL_C_INCLUDES := \
-    external/gtest/include \
     $(call include-path-for, wilhelm) \
     $(call include-path-for, wilhelm-ut)
 
@@ -46,6 +63,8 @@
     libOpenSLESUT \
     libgtest
 
+LOCAL_CTS_GTEST_LIST_EXECUTABLE := $(ALL_MODULES.$(list_executable).INSTALLED)
+
 LOCAL_CTS_TEST_PACKAGE := android.nativemedia.sl
 
 # Tag this module as a cts test artifact
@@ -54,21 +73,3 @@
 LOCAL_CFLAGS := -Werror -Wall
 
 include $(BUILD_CTS_EXECUTABLE)
-
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE := $(list_executable)
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := \
-    src/SLObjectCreationTest.cpp
-
-LOCAL_CFLAGS := \
-    -DBUILD_ONLY \
-    -Werror -Wall
-
-LOCAL_SHARED_LIBRARIES := \
-    liblog \
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/tests/tests/nativemedia/xa/Android.mk b/tests/tests/nativemedia/xa/Android.mk
index f71d853..38650af 100644
--- a/tests/tests/nativemedia/xa/Android.mk
+++ b/tests/tests/nativemedia/xa/Android.mk
@@ -22,6 +22,23 @@
 include $(CLEAR_VARS)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
+LOCAL_MODULE := $(list_executable)
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+    src/XAObjectCreationTest.cpp
+
+LOCAL_CFLAGS := \
+    -DBUILD_ONLY \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+
+include $(BUILD_HOST_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
 LOCAL_MODULE:= $(test_executable)
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
@@ -30,7 +47,6 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 LOCAL_C_INCLUDES := \
-    external/gtest/include \
     $(call include-path-for, wilhelm) \
     $(call include-path-for, wilhelm-ut)
 
@@ -45,26 +61,11 @@
 LOCAL_STATIC_LIBRARIES := \
   libgtest \
 
+LOCAL_CTS_GTEST_LIST_EXECUTABLE := $(ALL_MODULES.$(list_executable).INSTALLED)
+
 LOCAL_CTS_TEST_PACKAGE := android.nativemedia.xa
 
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts
 
 include $(BUILD_CTS_EXECUTABLE)
-
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE := $(list_executable)
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := \
-    src/XAObjectCreationTest.cpp
-
-LOCAL_CFLAGS := \
-    -DBUILD_ONLY \
-
-LOCAL_SHARED_LIBRARIES := \
-    liblog \
-
-include $(BUILD_HOST_NATIVE_TEST)
diff --git a/tests/tests/net/jni/NativeDnsJni.c b/tests/tests/net/jni/NativeDnsJni.c
index 4eb3c7a..352c0c5 100644
--- a/tests/tests/net/jni/NativeDnsJni.c
+++ b/tests/tests/net/jni/NativeDnsJni.c
@@ -126,7 +126,7 @@
         return JNI_FALSE;
     }
 
-    memset(buf, sizeof(buf), 0);
+    memset(buf, 0, sizeof(buf));
     res = getnameinfo((const struct sockaddr*)&sa6, sizeof(sa6), buf, sizeof(buf), NULL, 0, flags);
     if (res != 0) {
         ALOGD("getnameinfo(%s (GoogleDNS) ) gave error %d (%s)", GoogleDNSIpV6Address2,
diff --git a/tests/tests/net/jni/NativeMultinetworkJni.c b/tests/tests/net/jni/NativeMultinetworkJni.c
index ad56b51..6990efa 100644
--- a/tests/tests/net/jni/NativeMultinetworkJni.c
+++ b/tests/tests/net/jni/NativeMultinetworkJni.c
@@ -30,7 +30,7 @@
 #include <sys/time.h>
 #include <android/multinetwork.h>
 
-#define UNUSED(X) ((void) X)
+#define UNUSED(X) ((void) (X))
 
 static const char kHostname[] = "connectivitycheck.android.com";
 
diff --git a/tests/tests/net/src/android/net/http/cts/HttpResponseCacheTest.java b/tests/tests/net/src/android/net/http/cts/HttpResponseCacheTest.java
index 545541d..7987a50 100644
--- a/tests/tests/net/src/android/net/http/cts/HttpResponseCacheTest.java
+++ b/tests/tests/net/src/android/net/http/cts/HttpResponseCacheTest.java
@@ -38,10 +38,11 @@
 public final class HttpResponseCacheTest extends TestCase {
 
     private File cacheDir;
-    private MockWebServer server = new MockWebServer();
+    private MockWebServer server;
 
     @Override public void setUp() throws Exception {
         super.setUp();
+        server = new MockWebServer();
         String tmp = System.getProperty("java.io.tmpdir");
         cacheDir = new File(tmp, "HttpCache-" + UUID.randomUUID());
         cacheDir.mkdirs();
diff --git a/tests/tests/os/jni/seccomp-tests/README.android b/tests/tests/os/jni/seccomp-tests/README.android
index a819ee5..cad678a 100644
--- a/tests/tests/os/jni/seccomp-tests/README.android
+++ b/tests/tests/os/jni/seccomp-tests/README.android
@@ -10,6 +10,8 @@
 - Rename main() to seccomp_test_main()
 - Add get_seccomp_test_list()
 - Backport TEST(syscall_restart) from upstream
+- Add parentheses in macro IS_SECCOMP_EVENT(status),
+  __TEST_IMPL, __TEST_F_IMPL, __EXPECT_STR, and _CONSTRUCTOR_ORDER_BACKWARD.
 
 The diff of modifications can be found in local-modifications-android.diff
 and local-modifications-android-2.diff. Note, the TEST(syscall_restart)
diff --git a/tests/tests/os/jni/seccomp-tests/tests/seccomp_bpf_tests.c b/tests/tests/os/jni/seccomp-tests/tests/seccomp_bpf_tests.c
index 7481dd2..a813361 100644
--- a/tests/tests/os/jni/seccomp-tests/tests/seccomp_bpf_tests.c
+++ b/tests/tests/os/jni/seccomp-tests/tests/seccomp_bpf_tests.c
@@ -878,7 +878,7 @@
 #define PTRACE_EVENT_SECCOMP 7
 #endif
 
-#define IS_SECCOMP_EVENT(status) ((status >> 16) == PTRACE_EVENT_SECCOMP)
+#define IS_SECCOMP_EVENT(status) (((status) >> 16) == PTRACE_EVENT_SECCOMP)
 bool tracer_running;
 void tracer_stop(int sig)
 {
diff --git a/tests/tests/os/jni/seccomp-tests/tests/test_harness.h b/tests/tests/os/jni/seccomp-tests/tests/test_harness.h
index 597e40c..b7d44f1 100644
--- a/tests/tests/os/jni/seccomp-tests/tests/test_harness.h
+++ b/tests/tests/os/jni/seccomp-tests/tests/test_harness.h
@@ -222,7 +222,7 @@
 #define __TEST_IMPL(test_name, _signal) \
   static void test_name(struct __test_metadata *_metadata); \
   static struct __test_metadata _##test_name##_object = \
-    { name: "global." #test_name, fn: &test_name, termsig: _signal }; \
+    { name: "global." #test_name, fn: &(test_name), termsig: (_signal) }; \
   static void __attribute__((constructor)) _register_##test_name(void) { \
     __register_test(&_##test_name##_object); \
   } \
@@ -280,7 +280,7 @@
   static struct __test_metadata _##fixture_name##_##test_name##_object = { \
     name: #fixture_name "." #test_name, \
     fn: &wrapper_##fixture_name##_##test_name, \
-    termsig: signal, \
+    termsig: (signal), \
    }; \
   static void __attribute__((constructor)) \
       _register_##fixture_name##_##test_name(void) { \
@@ -378,7 +378,7 @@
 #define __EXPECT_STR(_expected, _seen, _t, _assert) do { \
   const char *__exp = (_expected); \
   const char *__seen = (_seen); \
-  if (!(strcmp(__exp, __seen) _t 0))  { \
+  if (!(strcmp(__exp, __seen) _t (0)))  { \
     __TH_LOG("Expected '%s' %s '%s'.", __exp, #_t, __seen); \
     _metadata->passed = 0; \
     _metadata->trigger = 1; \
@@ -402,7 +402,7 @@
 static int __constructor_order = 0;
 
 #define _CONSTRUCTOR_ORDER_FORWARD   1
-#define _CONSTRUCTOR_ORDER_BACKWARD -1
+#define _CONSTRUCTOR_ORDER_BACKWARD (-1)
 
 /*
  * Since constructors are called in reverse order, reverse 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 617f0ab..6841b28 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -816,91 +816,6 @@
         assertTrue("/data is not mounted NODEV", (vfs.f_flag & OsConstants.ST_NODEV) != 0);
     }
 
-    public void testAllBlockDevicesAreSecure() throws Exception {
-        Set<File> insecure = getAllInsecureDevicesInDirAndSubdir(new File("/dev"), FileUtils.S_IFBLK);
-        assertTrue("Found insecure block devices: " + insecure.toString(),
-                insecure.isEmpty());
-    }
-
-    private static final Set<File> CHAR_DEV_EXCEPTIONS = new HashSet<File>(
-            Arrays.asList(
-                // All exceptions should be alphabetical and associated with a bug number.
-                new File("/dev/adsprpc-smd"), // b/11710243
-                new File("/dev/alarm"),      // b/9035217
-                new File("/dev/ashmem"),
-                new File("/dev/binder"),
-                new File("/dev/card0"),       // b/13159510
-                new File("/dev/renderD128"),
-                new File("/dev/renderD129"),  // b/23798677
-                new File("/dev/dri/card0"),   // b/13159510
-                new File("/dev/dri/renderD128"),
-                new File("/dev/dri/renderD129"), // b/23798677
-                new File("/dev/felica"),     // b/11142586
-                new File("/dev/felica_ant"), // b/11142586
-                new File("/dev/felica_cen"), // b/11142586
-                new File("/dev/felica_pon"), // b/11142586
-                new File("/dev/felica_rfs"), // b/11142586
-                new File("/dev/felica_rws"), // b/11142586
-                new File("/dev/felica_uicc"), // b/11142586
-                new File("/dev/full"),
-                new File("/dev/galcore"),
-                new File("/dev/genlock"),    // b/9035217
-                new File("/dev/graphics/galcore"),
-                new File("/dev/ion"),
-                new File("/dev/kgsl-2d0"),   // b/11271533
-                new File("/dev/kgsl-2d1"),   // b/11271533
-                new File("/dev/kgsl-3d0"),   // b/9035217
-                new File("/dev/log/events"), // b/9035217
-                new File("/dev/log/main"),   // b/9035217
-                new File("/dev/log/radio"),  // b/9035217
-                new File("/dev/log/system"), // b/9035217
-                new File("/dev/mali0"),       // b/9106968
-                new File("/dev/mali"),        // b/11142586
-                new File("/dev/mm_interlock"), // b/12955573
-                new File("/dev/mm_isp"),      // b/12955573
-                new File("/dev/mm_v3d"),      // b/12955573
-                new File("/dev/msm_rotator"), // b/9035217
-                new File("/dev/null"),
-                new File("/dev/nvhost-as-gpu"),
-                new File("/dev/nvhost-ctrl"), // b/9088251
-                new File("/dev/nvhost-ctrl-gpu"),
-                new File("/dev/nvhost-dbg-gpu"),
-                new File("/dev/nvhost-gpu"),
-                new File("/dev/nvhost-gr2d"), // b/9088251
-                new File("/dev/nvhost-gr3d"), // b/9088251
-                new File("/dev/nvhost-tsec"),
-                new File("/dev/nvhost-prof-gpu"),
-                new File("/dev/nvhost-vic"),
-                new File("/dev/nvmap"),       // b/9088251
-                new File("/dev/ptmx"),        // b/9088251
-                new File("/dev/pvrsrvkm"),    // b/9108170
-                new File("/dev/pvr_sync"),
-                new File("/dev/quadd"),
-                new File("/dev/random"),
-                new File("/dev/snfc_cen"),    // b/11142586
-                new File("/dev/snfc_hsel"),   // b/11142586
-                new File("/dev/snfc_intu_poll"), // b/11142586
-                new File("/dev/snfc_rfs"),    // b/11142586
-                new File("/dev/tegra-throughput"),
-                new File("/dev/tiler"),       // b/9108170
-                new File("/dev/tty"),
-                new File("/dev/urandom"),
-                new File("/dev/ump"),         // b/11142586
-                new File("/dev/xt_qtaguid"),  // b/9088251
-                new File("/dev/zero"),
-                new File("/dev/fimg2d"),      // b/10428016
-                new File("/dev/mobicore-user") // b/10428016
-            ));
-
-    public void testAllCharacterDevicesAreSecure() throws Exception {
-        Set<File> insecure = getAllInsecureDevicesInDirAndSubdir(new File("/dev"), FileUtils.S_IFCHR);
-        Set<File> insecurePts = getAllInsecureDevicesInDirAndSubdir(new File("/dev/pts"), FileUtils.S_IFCHR);
-        insecure.removeAll(CHAR_DEV_EXCEPTIONS);
-        insecure.removeAll(insecurePts);
-        assertTrue("Found insecure character devices: " + insecure.toString(),
-                insecure.isEmpty());
-    }
-
     public void testDevRandomWorldReadableAndWritable() throws Exception {
         File f = new File("/dev/random");
 
@@ -1014,67 +929,6 @@
                 .fileHasOnly("/system/bin/run-as"));
     }
 
-    private static Set<File>
-    getAllInsecureDevicesInDirAndSubdir(File dir, int type) throws Exception {
-        assertTrue(dir.isDirectory());
-        Set<File> retval = new HashSet<File>();
-
-        if (isSymbolicLink(dir)) {
-            // don't examine symbolic links.
-            return retval;
-        }
-
-        File[] subDirectories = dir.listFiles(new FileFilter() {
-            @Override public boolean accept(File pathname) {
-                return pathname.isDirectory();
-            }
-        });
-
-
-        /* recurse into subdirectories */
-        if (subDirectories != null) {
-            for (File f : subDirectories) {
-                retval.addAll(getAllInsecureDevicesInDirAndSubdir(f, type));
-            }
-        }
-
-        File[] filesInThisDirectory = dir.listFiles();
-        if (filesInThisDirectory == null) {
-            return retval;
-        }
-
-        for (File f: filesInThisDirectory) {
-            FileUtils.FileStatus status = new FileUtils.FileStatus();
-            FileUtils.getFileStatus(f.getAbsolutePath(), status, false);
-            if (status.isOfType(type)) {
-                if (f.canRead() || f.canWrite() || f.canExecute()) {
-                    retval.add(f);
-                }
-                if (status.uid == 2000) {
-                    // The shell user should not own any devices
-                    retval.add(f);
-                }
-
-                // Don't allow devices owned by GIDs
-                // accessible to non-privileged applications.
-                if ((status.gid == 1007)           // AID_LOG
-                          || (status.gid == 1015)  // AID_SDCARD_RW
-                          || (status.gid == 1023)  // AID_MEDIA_RW
-                          || (status.gid == 1028)  // AID_SDCARD_R
-                          || (status.gid == 2000)) // AID_SHELL
-                {
-                    if (status.hasModeFlag(FileUtils.S_IRGRP)
-                            || status.hasModeFlag(FileUtils.S_IWGRP)
-                            || status.hasModeFlag(FileUtils.S_IXGRP))
-                    {
-                        retval.add(f);
-                    }
-                }
-            }
-        }
-        return retval;
-    }
-
     private Set<File> getWritableDirectoriesAndSubdirectoriesOf(File dir) throws Exception {
         Set<File> retval = new HashSet<File>();
         if (!dir.isDirectory()) {
diff --git a/tests/tests/renderscript/libcoremathtestcpp/Android.mk b/tests/tests/renderscript/libcoremathtestcpp/Android.mk
index c62f20e..ad528571 100644
--- a/tests/tests/renderscript/libcoremathtestcpp/Android.mk
+++ b/tests/tests/renderscript/libcoremathtestcpp/Android.mk
@@ -32,5 +32,5 @@
 LOCAL_C_INCLUDES += frameworks/rs
 
 LOCAL_LDFLAGS := -llog -ldl
-LOCAL_STATIC_LIBRARIES := libRScpp_static libcutils
+LOCAL_STATIC_LIBRARIES := libRScpp_static
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/rscpp/librscpptest/Android.mk b/tests/tests/rscpp/librscpptest/Android.mk
index 73d2234..36eafe2 100644
--- a/tests/tests/rscpp/librscpptest/Android.mk
+++ b/tests/tests/rscpp/librscpptest/Android.mk
@@ -48,7 +48,7 @@
 LOCAL_CPPFLAGS := -std=c++11
 
 LOCAL_SHARED_LIBRARIES := libdl liblog
-LOCAL_STATIC_LIBRARIES := libRScpp_static libcutils
+LOCAL_STATIC_LIBRARIES := libRScpp_static
 
 LOCAL_SDK_VERSION := 21
 
diff --git a/tests/tests/simpleperf/Android.mk b/tests/tests/simpleperf/Android.mk
index 040e153..e09e76b 100644
--- a/tests/tests/simpleperf/Android.mk
+++ b/tests/tests/simpleperf/Android.mk
@@ -8,43 +8,6 @@
 include $(LLVM_ROOT_PATH)/llvm.mk
 
 include $(CLEAR_VARS)
-LOCAL_MODULE := $(test_executable)
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-
-LOCAL_SHARED_LIBRARIES += \
-  libbacktrace \
-  libunwind \
-  libbase \
-  liblog \
-  libutils \
-  libLLVM \
-
-LOCAL_WHOLE_STATIC_LIBRARIES = \
-  libsimpleperf_cts_test \
-
-LOCAL_STATIC_LIBRARIES += \
-  libgtest \
-  libbacktrace_offline \
-  libziparchive \
-  libz \
-  liblzma \
-
-LOCAL_POST_LINK_CMD =  \
-  TMP_FILE=`mktemp $(OUT_DIR)/simpleperf-post-link-XXXXXXXXXX` && \
-  (cd $(simpleperf_src_path)/testdata && zip - -0 -r .) > $$TMP_FILE && \
-  $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_OBJCOPY) --add-section .testzipdata=$$TMP_FILE $(linked_module) && \
-  rm -f $$TMP_FILE
-
-LOCAL_COMPATIBILITY_SUITE := cts
-
-LOCAL_CTS_TEST_PACKAGE := android.simpleperf
-include $(BUILD_CTS_EXECUTABLE)
-
-
-include $(CLEAR_VARS)
 LOCAL_MODULE := $(list_executable)
 LOCAL_MODULE_HOST_OS := linux
 LOCAL_MULTILIB := first
@@ -70,6 +33,56 @@
   libLLVMMCParser \
   libLLVMCore \
   libLLVMSupport \
+  libprotobuf-cpp-lite \
+  libevent \
 
 include $(LLVM_HOST_BUILD_MK)
 include $(BUILD_HOST_NATIVE_TEST)
+
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(test_executable)
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_WHOLE_STATIC_LIBRARIES = \
+  libsimpleperf_cts_test \
+
+LOCAL_STATIC_LIBRARIES += \
+  libbacktrace_offline \
+  libbacktrace \
+  libunwind \
+  libziparchive \
+  libz \
+  libgtest \
+  libbase \
+  libcutils \
+  liblog \
+  libutils \
+  liblzma \
+  libLLVMObject \
+  libLLVMBitReader \
+  libLLVMMC \
+  libLLVMMCParser \
+  libLLVMCore \
+  libLLVMSupport \
+  libprotobuf-cpp-lite \
+  libevent \
+  libc \
+
+LOCAL_POST_LINK_CMD =  \
+  TMP_FILE=`mktemp $(OUT_DIR)/simpleperf-post-link-XXXXXXXXXX` && \
+  (cd $(simpleperf_src_path)/testdata && zip - -0 -r .) > $$TMP_FILE && \
+  $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_OBJCOPY) --add-section .testzipdata=$$TMP_FILE $(linked_module) && \
+  rm -f $$TMP_FILE
+
+LOCAL_CTS_GTEST_LIST_EXECUTABLE := $(ALL_MODULES.$(list_executable).INSTALLED)
+
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_CTS_TEST_PACKAGE := android.simpleperf
+LOCAL_FORCE_STATIC_EXECUTABLE := true
+include $(LLVM_DEVICE_BUILD_MK)
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/tests/tests/text/src/android/text/format/cts/DateFormatTest.java b/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
index 756e4eb..f72111b 100644
--- a/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
+++ b/tests/tests/text/src/android/text/format/cts/DateFormatTest.java
@@ -264,10 +264,6 @@
 
     public void test_bug_82144() {
         for (Locale locale : Locale.getAvailableLocales()) {
-            if (locale.toString().startsWith("haw")) {
-                // http://b/26397197 - remove this when fixed.
-                continue;
-            }
             Locale.setDefault(locale);
             char[] order = DateFormat.getDateFormatOrder(mContext);
             boolean seenDay = false, seenMonth = false, seenYear = false;
diff --git a/tools/cfassembler/Android.mk b/tools/cfassembler/Android.mk
index 8e0f351..df736ed 100644
--- a/tools/cfassembler/Android.mk
+++ b/tools/cfassembler/Android.mk
@@ -22,14 +22,9 @@
 LOCAL_IS_HOST_MODULE := true
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_MODULE := cfassembler
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(HOST_OUT_JAVA_LIBRARIES)/cfassembler$(COMMON_JAVA_PACKAGE_SUFFIX)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/cfassembler | $(ACP)
-	@echo "Copy: $(PRIVATE_MODULE) ($@)"
-	$(copy-file-to-new-target)
-	$(hide) chmod 755 $@
+LOCAL_SRC_FILES := etc/cfassembler
+LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/cfassembler$(COMMON_JAVA_PACKAGE_SUFFIX)
+include $(BUILD_PREBUILT)
 
 INTERNAL_DALVIK_MODULES += $(LOCAL_INSTALLED_MODULE)
 
diff --git a/tools/cts-api-coverage/Android.mk b/tools/cts-api-coverage/Android.mk
index 2382d61..3f66961 100644
--- a/tools/cts-api-coverage/Android.mk
+++ b/tools/cts-api-coverage/Android.mk
@@ -14,25 +14,15 @@
 
 LOCAL_PATH := $(call my-dir)
 
-# We use copy-file-to-new-target so that the installed
-# script file's timestamp is at least as new as the
-# .jar file it wraps.
-
 # the hat script
 # ============================================================
 include $(CLEAR_VARS)
 LOCAL_IS_HOST_MODULE := true
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_MODULE := cts-api-coverage
-LOCAL_MODULE_TAGS := optional
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/$(LOCAL_MODULE) | $(ACP)
-	@echo "Copy: $(PRIVATE_MODULE) ($@)"
-	$(copy-file-to-new-target)
-	$(hide) chmod 755 $@
+LOCAL_SRC_FILES := etc/$(LOCAL_MODULE)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
+include $(BUILD_PREBUILT)
 
 # the other stuff
 # ============================================================
diff --git a/tools/cts-device-info/jni/Android.mk b/tools/cts-device-info/jni/Android.mk
index eda845c..30bde53 100644
--- a/tools/cts-device-info/jni/Android.mk
+++ b/tools/cts-device-info/jni/Android.mk
@@ -24,11 +24,7 @@
 	CtsDeviceInfoJniOnLoad.cpp \
 	com_android_cts_deviceinfo_VulkanDeviceInfo.cpp
 
-LOCAL_C_INCLUDES := \
-	$(JNI_H_INCLUDE) \
-	external/vulkan-validation-layers/libs/vkjson
-
-LOCAL_STATIC_LIBRARIES := libvkjson
+LOCAL_STATIC_LIBRARIES := libvkjson_ndk
 LOCAL_SHARED_LIBRARIES := libvulkan liblog libdl
 LOCAL_NDK_STL_VARIANT := c++_static
 
diff --git a/tools/cts-java-scanner/Android.mk b/tools/cts-java-scanner/Android.mk
index 8b6c906..644f1c0 100644
--- a/tools/cts-java-scanner/Android.mk
+++ b/tools/cts-java-scanner/Android.mk
@@ -14,25 +14,15 @@
 
 LOCAL_PATH := $(call my-dir)
 
-# We use copy-file-to-new-target so that the installed
-# script file's timestamp is at least as new as the
-# .jar file it wraps.
-
 # the hat script
 # ============================================================
 include $(CLEAR_VARS)
 LOCAL_IS_HOST_MODULE := true
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_MODULE := cts-java-scanner
-LOCAL_MODULE_TAGS := optional
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/$(LOCAL_MODULE) | $(ACP)
-	@echo "Copy: $(PRIVATE_MODULE) ($@)"
-	$(copy-file-to-new-target)
-	$(hide) chmod 755 $@
+LOCAL_SRC_FILES := etc/$(LOCAL_MODULE)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
+include $(BUILD_PREBUILT)
 
 # the other stuff
 # ============================================================
diff --git a/tools/cts-native-scanner/Android.mk b/tools/cts-native-scanner/Android.mk
index 8bcff1c..203b482 100644
--- a/tools/cts-native-scanner/Android.mk
+++ b/tools/cts-native-scanner/Android.mk
@@ -14,25 +14,15 @@
 
 LOCAL_PATH := $(call my-dir)
 
-# We use copy-file-to-new-target so that the installed
-# script file's timestamp is at least as new as the
-# .jar file it wraps.
-
 # the hat script
 # ============================================================
 include $(CLEAR_VARS)
 LOCAL_IS_HOST_MODULE := true
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_MODULE := cts-native-scanner
-LOCAL_MODULE_TAGS := optional
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/$(LOCAL_MODULE) | $(ACP)
-	@echo "Copy: $(PRIVATE_MODULE) ($@)"
-	$(copy-file-to-new-target)
-	$(hide) chmod 755 $@
+LOCAL_SRC_FILES := etc/$(LOCAL_MODULE)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
+include $(BUILD_PREBUILT)
 
 # Build all sub-directories
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tools/cts-xml-generator/Android.mk b/tools/cts-xml-generator/Android.mk
index 5842dd8..23256f3 100644
--- a/tools/cts-xml-generator/Android.mk
+++ b/tools/cts-xml-generator/Android.mk
@@ -14,25 +14,15 @@
 
 LOCAL_PATH := $(call my-dir)
 
-# We use copy-file-to-new-target so that the installed
-# script file's timestamp is at least as new as the
-# .jar file it wraps.
-
 # the hat script
 # ============================================================
 include $(CLEAR_VARS)
 LOCAL_IS_HOST_MODULE := true
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_MODULE := cts-xml-generator
-LOCAL_MODULE_TAGS := optional
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/$(LOCAL_MODULE) | $(ACP)
-	@echo "Copy: $(PRIVATE_MODULE) ($@)"
-	$(copy-file-to-new-target)
-	$(hide) chmod 755 $@
+LOCAL_SRC_FILES := etc/$(LOCAL_MODULE)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
+include $(BUILD_PREBUILT)
 
 # the other stuff
 # ============================================================
diff --git a/tools/dasm/Android.mk b/tools/dasm/Android.mk
index c18e677..1b1f328 100644
--- a/tools/dasm/Android.mk
+++ b/tools/dasm/Android.mk
@@ -22,14 +22,9 @@
 LOCAL_IS_HOST_MODULE := true
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_MODULE := dasm
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(HOST_OUT_JAVA_LIBRARIES)/dasm$(COMMON_JAVA_PACKAGE_SUFFIX)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/dasm | $(ACP)
-	@echo "Copy: $(PRIVATE_MODULE) ($@)"
-	$(copy-file-to-new-target)
-	$(hide) chmod 755 $@
+LOCAL_SRC_FILES := etc/dasm
+LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/dasm$(COMMON_JAVA_PACKAGE_SUFFIX)
+include $(BUILD_PREBUILT)
 
 INTERNAL_DALVIK_MODULES += $(LOCAL_INSTALLED_MODULE)
 
diff --git a/tools/vm-tests-tf/Android.mk b/tools/vm-tests-tf/Android.mk
index ef6aa84..4a4e7ae 100644
--- a/tools/vm-tests-tf/Android.mk
+++ b/tools/vm-tests-tf/Android.mk
@@ -55,7 +55,6 @@
 #
 include $(CLEAR_VARS)
 
-LOCAL_JACK_ENABLED := $(strip $(LOCAL_JACK_ENABLED))
 LOCAL_MODULE := vm-tests-tf
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 LOCAL_MODULE_SUFFIX := $(COMMON_JAVA_PACKAGE_SUFFIX)
@@ -75,9 +74,7 @@
 
 $(LOCAL_BUILT_MODULE): PRIVATE_JACK_EXTRA_ARGS := $(LOCAL_JACK_EXTRA_ARGS)
 
-ifdef LOCAL_JACK_ENABLED
-    vmteststf_dep_jars += $(cts-tf-dalvik-lib.jack)
-endif
+vmteststf_dep_jars += $(cts-tf-dalvik-lib.jack)
 
 $(LOCAL_BUILT_MODULE): PRIVATE_SRC_FOLDER := $(LOCAL_PATH)/src
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_CLASSES := $(call intermediates-dir-for,JAVA_LIBRARIES,cts-tf-dalvik-buildutil,HOST)/classes
@@ -87,23 +84,6 @@
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES := $(intermediates)/hostjunit_files
 $(LOCAL_BUILT_MODULE): PRIVATE_CLASS_PATH := $(subst $(space),:,$(vmteststf_dep_jars)):$(HOST_JDK_TOOLS_JAR)
 $(LOCAL_BUILT_MODULE): PRIVATE_JACK_VERSION := $(LOCAL_JACK_VERSION)
-ifndef LOCAL_JACK_ENABLED
-$(LOCAL_BUILT_MODULE) : $(vmteststf_dep_jars) $(HOST_OUT_JAVA_LIBRARIES)/tradefed-prebuilt.jar
-	$(hide) rm -rf $(dir $@) && mkdir -p $(dir $@)
-	$(hide) mkdir -p $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/dot/junit $(dir $(PRIVATE_INTERMEDIATES_DEXCORE_JAR))
-	# generated and compile the host side junit tests
-	@echo "Write generated Main_*.java files to $(PRIVATE_INTERMEDIATES_MAIN_FILES)"
-	$(hide) java -cp $(PRIVATE_CLASS_PATH) util.build.BuildDalvikSuite $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
-		$(HOST_OUT_JAVA_LIBRARIES)/cts-tf-dalvik-buildutil.jar:$(HOST_OUT_JAVA_LIBRARIES)/tradefed-prebuilt.jar \
-		$(PRIVATE_INTERMEDIATES_MAIN_FILES) $(PRIVATE_INTERMEDIATES_CLASSES) $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES) $$RUN_VM_TESTS_RTO
-	@echo "Generate $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)"
-	$(hide) jar -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar \
-		$(addprefix -C $(PRIVATE_INTERMEDIATES_CLASSES) , dot/junit/DxUtil.class dot/junit/DxAbstractMain.class)
-	$(hide) $(DX) -JXms16M -JXmx768M --dex --output=$(PRIVATE_INTERMEDIATES_DEXCORE_JAR) \
-		$(if $(NO_OPTIMIZE_DX), --no-optimize) $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar && rm -f $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar
-	$(hide) cd $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/classes && zip -q -r ../../$(notdir $@) .
-	$(hide) cd $(dir $@) && zip -q -r $(notdir $@) tests
-else # LOCAL_JACK_ENABLED
 oj_jack := $(call intermediates-dir-for,JAVA_LIBRARIES,core-oj,,COMMON)/classes.jack
 libart_jack := $(call intermediates-dir-for,JAVA_LIBRARIES,core-libart,,COMMON)/classes.jack
 $(LOCAL_BUILT_MODULE): PRIVATE_DALVIK_SUITE_CLASSPATH := $(oj_jack):$(libart_jack):$(cts-tf-dalvik-lib.jack):$(HOST_OUT_JAVA_LIBRARIES)/tradefed-prebuilt.jar
@@ -127,7 +107,6 @@
 	$(hide) cd $(dir $@) && zip -q -r $(notdir $@) tests
 oj_jack :=
 libart_jack :=
-endif # LOCAL_JACK_ENABLED
 
 # Clean up temp vars
 intermediates :=