Merge "Android feels strongly about .rtx files."
diff --git a/luni/src/main/java/libcore/io/ForwardingOs.java b/luni/src/main/java/libcore/io/ForwardingOs.java
index 48c4e1c..2e0ce9f 100644
--- a/luni/src/main/java/libcore/io/ForwardingOs.java
+++ b/luni/src/main/java/libcore/io/ForwardingOs.java
@@ -71,6 +71,9 @@
     public void chown(String path, int uid, int gid) throws ErrnoException { os.chown(path, uid, gid); }
     public void close(FileDescriptor fd) throws ErrnoException { os.close(fd); }
     public void android_fdsan_exchange_owner_tag(FileDescriptor fd, long previousOwnerId, long newOwnerId) { os.android_fdsan_exchange_owner_tag(fd, previousOwnerId, newOwnerId); }
+    public long android_fdsan_get_owner_tag(FileDescriptor fd) { return os.android_fdsan_get_owner_tag(fd); }
+    public String android_fdsan_get_tag_type(long tag) { return os.android_fdsan_get_tag_type(tag); }
+    public long android_fdsan_get_tag_value(long tag) { return os.android_fdsan_get_tag_value(tag); }
 
     public void connect(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException { os.connect(fd, address, port); }
     public void connect(FileDescriptor fd, SocketAddress address) throws ErrnoException, SocketException { os.connect(fd, address); }
diff --git a/luni/src/main/java/libcore/io/IoUtils.java b/luni/src/main/java/libcore/io/IoUtils.java
index 43b800c..54afacc 100644
--- a/luni/src/main/java/libcore/io/IoUtils.java
+++ b/luni/src/main/java/libcore/io/IoUtils.java
@@ -64,6 +64,47 @@
         return rawFd;
     }
 
+    private static boolean isParcelFileDescriptor(Object object) {
+        // We need to look up ParcelFileDescriptor dynamically, because there are cases where the
+        // framework classes will not be found on the classpath such as on-host development.
+        try {
+            Class<?> pfdClass = Class.forName("android.os.ParcelFileDescriptor");
+            if (pfdClass.isInstance(object)) {
+                return true;
+            }
+            return false;
+        } catch (ClassNotFoundException ex) {
+            return false;
+        }
+    }
+
+    private static long generateFdOwnerId(Object owner) {
+        if (owner == null) {
+            return 0;
+        }
+
+        // Type values from bionic's <android/fdsan.h>.
+        long tagType;
+        if (owner instanceof java.io.FileInputStream) {
+            tagType = 5;
+        } else if (owner instanceof java.io.FileOutputStream) {
+            tagType = 6;
+        } else if (owner instanceof java.io.RandomAccessFile) {
+            tagType = 7;
+        } else if (isParcelFileDescriptor(owner)) {
+            tagType = 8;
+        } else {
+            // Generic Java type.
+            tagType = 255;
+        }
+
+        // The owner ID is not required to be unique but should be stable and attempt to avoid
+        // collision with identifiers generated both here and in native code (which are simply the
+        // address of the owning object). identityHashCode(Object) meets these requirements.
+        long tagValue = System.identityHashCode(owner);
+        return tagType << 56 | tagValue;
+    }
+
     /**
      * Assigns ownership of an unowned FileDescriptor.
      *
@@ -88,10 +129,7 @@
                                             "FileDescriptor");
         }
 
-        // ownerId is not required to be unique but should be stable and should attempt to avoid
-        // collision with identifiers generated both here and in native code (which are simply the
-        // address of the owning object). identityHashCode(Object) meets these requirements.
-        int ownerId = System.identityHashCode(owner);
+        long ownerId = generateFdOwnerId(owner);
         fd.setOwnerId$(ownerId);
 
         // Set the file descriptor's owner ID, aborting if the previous value isn't as expected.
diff --git a/luni/src/main/java/libcore/io/Linux.java b/luni/src/main/java/libcore/io/Linux.java
index bdbdcf7..3766ac1 100644
--- a/luni/src/main/java/libcore/io/Linux.java
+++ b/luni/src/main/java/libcore/io/Linux.java
@@ -63,6 +63,9 @@
 
     public native void close(FileDescriptor fd) throws ErrnoException;
     public native void android_fdsan_exchange_owner_tag(FileDescriptor fd, long previousOwnerId, long newOwnerId);
+    public native long android_fdsan_get_owner_tag(FileDescriptor fd);
+    public native String android_fdsan_get_tag_type(long tag);
+    public native long android_fdsan_get_tag_value(long tag);
 
     public native void connect(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException;
     public native void connect(FileDescriptor fd, SocketAddress address) throws ErrnoException, SocketException;
diff --git a/luni/src/main/java/libcore/io/Os.java b/luni/src/main/java/libcore/io/Os.java
index f791915..3f1c809 100644
--- a/luni/src/main/java/libcore/io/Os.java
+++ b/luni/src/main/java/libcore/io/Os.java
@@ -57,6 +57,9 @@
 
     public void close(FileDescriptor fd) throws ErrnoException;
     public void android_fdsan_exchange_owner_tag(FileDescriptor fd, long previousOwnerId, long newOwnerId);
+    public long android_fdsan_get_owner_tag(FileDescriptor fd);
+    public String android_fdsan_get_tag_type(long tag);
+    public long android_fdsan_get_tag_value(long tag);
 
     public void connect(FileDescriptor fd, InetAddress address, int port) throws ErrnoException, SocketException;
     public void connect(FileDescriptor fd, SocketAddress address) throws ErrnoException, SocketException;
diff --git a/luni/src/main/native/libcore_io_Linux.cpp b/luni/src/main/native/libcore_io_Linux.cpp
index 098136d..8a3e1be 100644
--- a/luni/src/main/native/libcore_io_Linux.cpp
+++ b/luni/src/main/native/libcore_io_Linux.cpp
@@ -1123,6 +1123,35 @@
 #endif
 }
 
+static jlong Linux_android_fdsan_get_owner_tag(JNIEnv* env, jclass, jobject javaFd) {
+#if defined(__BIONIC__)
+    int fd = jniGetFDFromFileDescriptor(env, javaFd);
+    return android_fdsan_get_owner_tag(fd);
+#else
+    UNUSED(env, javaFd);
+    return 0;
+#endif
+}
+
+static jstring Linux_android_fdsan_get_tag_type(JNIEnv* env, jclass, jlong tag) {
+#if defined(__BIONIC__)
+    return env->NewStringUTF(android_fdsan_get_tag_type(tag));
+#else
+    UNUSED(tag);
+    return env->NewStringUTF("unknown");
+#endif
+}
+
+static jlong Linux_android_fdsan_get_tag_value(JNIEnv* env, jclass, jlong tag) {
+#if defined(__BIONIC__)
+    UNUSED(env);
+    return android_fdsan_get_tag_value(tag);
+#else
+    UNUSED(env, tag);
+    return 0;
+#endif
+}
+
 static void Linux_connect(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) {
     (void) NET_IPV4_FALLBACK(env, int, connect, javaFd, javaAddress, port, NULL_ADDR_FORBIDDEN);
 }
@@ -2504,6 +2533,9 @@
     NATIVE_METHOD(Linux, accept, "(Ljava/io/FileDescriptor;Ljava/net/SocketAddress;)Ljava/io/FileDescriptor;"),
     NATIVE_METHOD(Linux, access, "(Ljava/lang/String;I)Z"),
     NATIVE_METHOD(Linux, android_fdsan_exchange_owner_tag, "(Ljava/io/FileDescriptor;JJ)V"),
+    NATIVE_METHOD(Linux, android_fdsan_get_owner_tag, "(Ljava/io/FileDescriptor;)J"),
+    NATIVE_METHOD(Linux, android_fdsan_get_tag_type, "(J)Ljava/lang/String;"),
+    NATIVE_METHOD(Linux, android_fdsan_get_tag_value, "(J)J"),
     NATIVE_METHOD(Linux, android_getaddrinfo, "(Ljava/lang/String;Landroid/system/StructAddrinfo;I)[Ljava/net/InetAddress;"),
     NATIVE_METHOD(Linux, bind, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"),
     NATIVE_METHOD_OVERLOAD(Linux, bind, "(Ljava/io/FileDescriptor;Ljava/net/SocketAddress;)V", SocketAddress),
diff --git a/luni/src/test/java/libcore/libcore/io/BlockGuardOsTest.java b/luni/src/test/java/libcore/libcore/io/BlockGuardOsTest.java
index 698b98b..aea709f 100644
--- a/luni/src/test/java/libcore/libcore/io/BlockGuardOsTest.java
+++ b/luni/src/test/java/libcore/libcore/io/BlockGuardOsTest.java
@@ -120,6 +120,9 @@
     public void test_checkNewMethodsInPosix() {
         List<String> methodsNotRequireBlockGuardChecks = Arrays.asList(
                 "android_fdsan_exchange_owner_tag(java.io.FileDescriptor,long,long)",
+                "android_fdsan_get_owner_tag(java.io.FileDescriptor)",
+                "android_fdsan_get_tag_type(long)",
+                "android_fdsan_get_tag_value(long)",
                 "bind(java.io.FileDescriptor,java.net.InetAddress,int)",
                 "bind(java.io.FileDescriptor,java.net.SocketAddress)",
                 "capget(android.system.StructCapUserHeader)",
diff --git a/luni/src/test/java/libcore/libcore/io/FdsanTest.java b/luni/src/test/java/libcore/libcore/io/FdsanTest.java
new file mode 100644
index 0000000..420fb7e
--- /dev/null
+++ b/luni/src/test/java/libcore/libcore/io/FdsanTest.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package libcore.libcore.io;
+
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.RandomAccessFile;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import junit.framework.TestCase;
+
+import libcore.io.Libcore;
+
+public class FdsanTest extends TestCase {
+    public void testFileInputStream() throws Exception {
+        try (FileInputStream fis = new FileInputStream("/dev/null")) {
+            FileDescriptor fd = fis.getFD();
+            long tag = Libcore.os.android_fdsan_get_owner_tag(fd);
+            assertTrue(tag != 0);
+            assertEquals("FileInputStream", Libcore.os.android_fdsan_get_tag_type(tag));
+            assertEquals(System.identityHashCode(fis), Libcore.os.android_fdsan_get_tag_value(tag));
+        }
+    }
+
+    public void testFileOutputStream() throws Exception {
+        try (FileOutputStream fis = new FileOutputStream("/dev/null")) {
+            FileDescriptor fd = fis.getFD();
+            long tag = Libcore.os.android_fdsan_get_owner_tag(fd);
+            assertTrue(tag != 0);
+            assertEquals("FileOutputStream", Libcore.os.android_fdsan_get_tag_type(tag));
+            assertEquals(System.identityHashCode(fis), Libcore.os.android_fdsan_get_tag_value(tag));
+        }
+    }
+
+    public void testRandomAccessFile() throws Exception {
+        try (RandomAccessFile fis = new RandomAccessFile("/dev/null", "r")) {
+            FileDescriptor fd = fis.getFD();
+            long tag = Libcore.os.android_fdsan_get_owner_tag(fd);
+            assertTrue(tag != 0);
+            assertEquals("RandomAccessFile", Libcore.os.android_fdsan_get_tag_type(tag));
+            assertEquals(System.identityHashCode(fis), Libcore.os.android_fdsan_get_tag_value(tag));
+        }
+    }
+
+    public void testParcelFileDescriptor() throws Exception {
+        Class pfdClass;
+        try {
+            pfdClass = Class.forName("android.os.ParcelFileDescriptor");
+        } catch (ClassNotFoundException ex) {
+            // Don't fail if ParcelFileDescriptor isn't on our classpath, e.g. in ART host tests.
+            return;
+        }
+
+        try (FileInputStream fis = new FileInputStream("/dev/null")) {
+            Method pfdMethodDup = pfdClass.getMethod("dup", FileDescriptor.class);
+            Method pfdMethodClose = pfdClass.getMethod("close");
+            Method pfdMethodGetFileDescriptor = pfdClass.getMethod("getFileDescriptor");
+            Field readonly = pfdClass.getField("MODE_READ_ONLY");
+
+            Object pfd = pfdMethodDup.invoke(null, fis.getFD());
+            FileDescriptor fd = (FileDescriptor)pfdMethodGetFileDescriptor.invoke(pfd);
+            long tag = Libcore.os.android_fdsan_get_owner_tag(fd);
+            assertTrue(tag != 0);
+            assertEquals("ParcelFileDescriptor", Libcore.os.android_fdsan_get_tag_type(tag));
+            assertEquals(System.identityHashCode(pfd), Libcore.os.android_fdsan_get_tag_value(tag));
+            pfdMethodClose.invoke(pfd);
+        }
+    }
+}
diff --git a/ojluni/src/main/java/java/util/zip/ZipFile.java b/ojluni/src/main/java/java/util/zip/ZipFile.java
index d44785b..851aab1 100644
--- a/ojluni/src/main/java/java/util/zip/ZipFile.java
+++ b/ojluni/src/main/java/java/util/zip/ZipFile.java
@@ -669,32 +669,46 @@
         if (closeRequested)
             return;
         // Android-added: CloseGuard support
-        guard.close();
+        if (guard != null) {
+            guard.close();
+        }
         closeRequested = true;
 
         synchronized (this) {
             // Close streams, release their inflaters
-            synchronized (streams) {
-                if (false == streams.isEmpty()) {
-                    Map<InputStream, Inflater> copy = new HashMap<>(streams);
-                    streams.clear();
-                    for (Map.Entry<InputStream, Inflater> e : copy.entrySet()) {
-                        e.getKey().close();
-                        Inflater inf = e.getValue();
-                        if (inf != null) {
-                            inf.end();
+            // BEGIN Android-added: null field check to avoid NullPointerException during finalize.
+            // If the constructor threw an exception then the streams / inflaterCache fields can
+            // be null and close() can be called by the finalizer.
+            if (streams != null) {
+            // END Android-added: null field check to avoid NullPointerException during finalize.
+                synchronized (streams) {
+                    if (false == streams.isEmpty()) {
+                        Map<InputStream, Inflater> copy = new HashMap<>(streams);
+                        streams.clear();
+                        for (Map.Entry<InputStream, Inflater> e : copy.entrySet()) {
+                            e.getKey().close();
+                            Inflater inf = e.getValue();
+                            if (inf != null) {
+                                inf.end();
+                            }
                         }
                     }
                 }
+            // BEGIN Android-added: null field check to avoid NullPointerException during finalize.
             }
 
-            // Release cached inflaters
-            Inflater inf;
-            synchronized (inflaterCache) {
-                while (null != (inf = inflaterCache.poll())) {
-                    inf.end();
+            if (inflaterCache != null) {
+            // END Android-added: null field check to avoid NullPointerException during finalize.
+                // Release cached inflaters
+                Inflater inf;
+                synchronized (inflaterCache) {
+                    while (null != (inf = inflaterCache.poll())) {
+                        inf.end();
+                    }
                 }
+            // BEGIN Android-added: null field check to avoid NullPointerException during finalize.
             }
+            // END Android-added: null field check to avoid NullPointerException during finalize.
 
             if (jzfile != 0) {
                 // Close the zip file