Merge "Revert "Convert libcore native code to Android.bp""
diff --git a/dalvik/src/main/java/dalvik/system/ZygoteHooks.java b/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
index c96016f..47e4ad4 100644
--- a/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
+++ b/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
@@ -53,12 +53,12 @@
     }
 
     /**
-     * Called by the zygote in the child process after every fork. The debug
-     * flags from {@code debugFlags} are applied to the child process. The string
+     * Called by the zygote in the child process after every fork. The runtime
+     * flags from {@code runtimeFlags} are applied to the child process. The string
      * {@code instructionSet} determines whether to use a native bridge.
      */
-    public void postForkChild(int debugFlags, boolean isSystemServer, String instructionSet) {
-        nativePostForkChild(token, debugFlags, isSystemServer, instructionSet);
+    public void postForkChild(int runtimeFlags, boolean isSystemServer, String instructionSet) {
+        nativePostForkChild(token, runtimeFlags, isSystemServer, instructionSet);
 
         Math.setRandomSeedInternal(System.currentTimeMillis());
     }
@@ -73,7 +73,7 @@
     }
 
     private static native long nativePreFork();
-    private static native void nativePostForkChild(long token, int debugFlags,
+    private static native void nativePostForkChild(long token, int runtimeFlags,
                                                    boolean isSystemServer, String instructionSet);
 
     /**
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
index d9a7b4f..eed6b11 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
@@ -33,6 +33,7 @@
 import javax.net.ssl.SSLEngine;
 import javax.net.ssl.SSLEngineResult;
 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import javax.net.ssl.SSLEngineResult.Status;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLHandshakeException;
 import javax.net.ssl.SSLParameters;
@@ -850,4 +851,33 @@
             server.get();
         }
     }
+
+    public void test_SSLEngine_CloseOutbound() throws Exception {
+        try (final TestSSLEnginePair pair = TestSSLEnginePair.create()) {
+            assertConnected(pair);
+
+            pair.client.closeOutbound();
+            ByteBuffer clientOut = ByteBuffer.allocate(pair.client.getSession().getPacketBufferSize());
+            SSLEngineResult res = pair.client.wrap(ByteBuffer.wrap(new byte[0]), clientOut);
+            assertEquals(Status.CLOSED, res.getStatus());
+            assertEquals(HandshakeStatus.NOT_HANDSHAKING, res.getHandshakeStatus());
+
+            clientOut.flip();
+            ByteBuffer serverIn = ByteBuffer.allocate(pair.server.getSession().getApplicationBufferSize());
+            res = pair.server.unwrap(clientOut, serverIn);
+            assertEquals(Status.CLOSED, res.getStatus());
+            assertEquals(HandshakeStatus.NEED_WRAP, res.getHandshakeStatus());
+
+            ByteBuffer serverOut = ByteBuffer.allocate(pair.server.getSession().getPacketBufferSize());
+            res = pair.server.wrap(ByteBuffer.wrap(new byte[0]), serverOut);
+            assertEquals(Status.CLOSED, res.getStatus());
+            assertEquals(HandshakeStatus.NOT_HANDSHAKING, res.getHandshakeStatus());
+
+            serverOut.flip();
+            ByteBuffer clientIn = ByteBuffer.allocate(pair.client.getSession().getApplicationBufferSize());
+            res = pair.client.unwrap(serverOut, clientIn);
+            assertEquals(Status.CLOSED, res.getStatus());
+            assertEquals(HandshakeStatus.NOT_HANDSHAKING, res.getHandshakeStatus());
+        }
+    }
 }
diff --git a/ojluni/src/main/java/java/net/DatagramSocket.java b/ojluni/src/main/java/java/net/DatagramSocket.java
index 5beab30..3e3faf7 100755
--- a/ojluni/src/main/java/java/net/DatagramSocket.java
+++ b/ojluni/src/main/java/java/net/DatagramSocket.java
@@ -1355,24 +1355,4 @@
         return impl.fd;
     }
 
-    // Android-added: setNetworkInterface() to set the network interface used by this socket.
-    /**
-     * Sets the network interface used by this socket.  Any packets sent
-     * via this socket are transmitted via the specified interface.  Any
-     * packets received by this socket will come from the specified
-     * interface.  Broadcast datagrams received on this interface will
-     * be processed by this socket. This corresponds to Linux's SO_BINDTODEVICE.
-     *
-     * @hide used by GoogleTV for DHCP
-     */
-    public void setNetworkInterface(NetworkInterface netInterface) throws SocketException {
-        if (netInterface == null) {
-            throw new NullPointerException("netInterface == null");
-        }
-        try {
-            Libcore.os.setsockoptIfreq(impl.fd, SOL_SOCKET, SO_BINDTODEVICE, netInterface.getName());
-        } catch (ErrnoException errnoException) {
-            throw errnoException.rethrowAsSocketException();
-        }
-    }
 }
diff --git a/ojluni/src/main/java/java/net/HttpURLConnection.java b/ojluni/src/main/java/java/net/HttpURLConnection.java
index db05c5f..b72168b 100644
--- a/ojluni/src/main/java/java/net/HttpURLConnection.java
+++ b/ojluni/src/main/java/java/net/HttpURLConnection.java
@@ -315,7 +315,7 @@
      * server. In this case, {@link #getHeaderField(int) getHeaderField(0)} returns the status
      * line, but {@code getHeaderFieldKey(0)} returns null.
      *
-     * @param   n   an index, where n >=0.
+     * @param   n   an index, where {@code n >=0}.
      * @return  the key for the {@code n}<sup>th</sup> header field,
      *          or {@code null} if the key does not exist.
      */
@@ -466,7 +466,7 @@
      * {@link #getHeaderFieldKey getHeaderFieldKey} method to iterate through all
      * the headers in the message.
      *
-     * @param   n   an index, where n>=0.
+     * @param   n   an index, where {@code n>=0}.
      * @return  the value of the {@code n}<sup>th</sup> header field,
      *          or {@code null} if the value does not exist.
      * @see     java.net.HttpURLConnection#getHeaderFieldKey(int)
diff --git a/ojluni/src/main/java/java/net/IDN.java b/ojluni/src/main/java/java/net/IDN.java
index 8ea32c8..4639c8f 100644
--- a/ojluni/src/main/java/java/net/IDN.java
+++ b/ojluni/src/main/java/java/net/IDN.java
@@ -77,9 +77,6 @@
      */
     public static final int USE_STD3_ASCII_RULES = 0x02;
 
-    private IDN() {
-    }
-
 
     /**
      * Translates a string from Unicode to ASCII Compatible Encoding (ACE),
@@ -106,11 +103,13 @@
      * @throws IllegalArgumentException   if the input string doesn't conform to RFC 3490 specification
      */
     public static String toASCII(String input, int flag) {
+        // BEGIN Android-changed: Use ICU4J implementation
         try {
             return IDNA.convertIDNToASCII(input, flag).toString();
         } catch (android.icu.text.StringPrepParseException e) {
             throw new IllegalArgumentException("Invalid input to toASCII: " + input, e);
         }
+        // END Android-changed: Use ICU4J implementation
     }
 
 
@@ -154,6 +153,7 @@
      * @return          the translated {@code String}
      */
     public static String toUnicode(String input, int flag) {
+        // BEGIN Android-changed: Use ICU4J implementation
         try {
             // ICU only translates separators to ASCII for toASCII.
             // Java expects the translation for toUnicode too.
@@ -163,8 +163,10 @@
             // the original string is returned.
             return input;
         }
+        // END Android-changed: Use ICU4J implementation
     }
 
+    // BEGIN Android-added: Use ICU4J implementation
     private static boolean isLabelSeperator(char c) {
         return (c == '\u3002' || c == '\uff0e' || c == '\uff61');
     }
@@ -177,7 +179,7 @@
         }
         return input;
     }
-
+    // END Android-added: Use ICU4J implementation
 
     /**
      * Translates a string from ASCII Compatible Encoding (ACE) to Unicode,
@@ -196,4 +198,296 @@
     public static String toUnicode(String input) {
         return toUnicode(input, 0);
     }
+
+
+    /* ---------------- Private members -------------- */
+
+    // Android-removed: Private helper methods, unused because we use ICU.
+    /*
+    // ACE Prefix is "xn--"
+    private static final String ACE_PREFIX = "xn--";
+    private static final int ACE_PREFIX_LENGTH = ACE_PREFIX.length();
+
+    private static final int MAX_LABEL_LENGTH   = 63;
+
+    // single instance of nameprep
+    private static StringPrep namePrep = null;
+
+    static {
+        InputStream stream = null;
+
+        try {
+            final String IDN_PROFILE = "uidna.spp";
+            if (System.getSecurityManager() != null) {
+                stream = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
+                    public InputStream run() {
+                        return StringPrep.class.getResourceAsStream(IDN_PROFILE);
+                    }
+                });
+            } else {
+                stream = StringPrep.class.getResourceAsStream(IDN_PROFILE);
+            }
+
+            namePrep = new StringPrep(stream);
+            stream.close();
+        } catch (IOException e) {
+            // should never reach here
+            assert false;
+        }
+    }
+    */
+
+    /* ---------------- Private operations -------------- */
+
+
+    //
+    // to suppress the default zero-argument constructor
+    //
+    private IDN() {}
+
+    // Android-removed: Private helper methods, unused because we use ICU.
+    /*
+    //
+    // toASCII operation; should only apply to a single label
+    //
+    private static String toASCIIInternal(String label, int flag)
+    {
+        // step 1
+        // Check if the string contains code points outside the ASCII range 0..0x7c.
+        boolean isASCII  = isAllASCII(label);
+        StringBuffer dest;
+
+        // step 2
+        // perform the nameprep operation; flag ALLOW_UNASSIGNED is used here
+        if (!isASCII) {
+            UCharacterIterator iter = UCharacterIterator.getInstance(label);
+            try {
+                dest = namePrep.prepare(iter, flag);
+            } catch (java.text.ParseException e) {
+                throw new IllegalArgumentException(e);
+            }
+        } else {
+            dest = new StringBuffer(label);
+        }
+
+        // step 8, move forward to check the smallest number of the code points
+        // the length must be inside 1..63
+        if (dest.length() == 0) {
+            throw new IllegalArgumentException(
+                        "Empty label is not a legal name");
+        }
+
+        // step 3
+        // Verify the absence of non-LDH ASCII code points
+        //   0..0x2c, 0x2e..0x2f, 0x3a..0x40, 0x5b..0x60, 0x7b..0x7f
+        // Verify the absence of leading and trailing hyphen
+        boolean useSTD3ASCIIRules = ((flag & USE_STD3_ASCII_RULES) != 0);
+        if (useSTD3ASCIIRules) {
+            for (int i = 0; i < dest.length(); i++) {
+                int c = dest.charAt(i);
+                if (isNonLDHAsciiCodePoint(c)) {
+                    throw new IllegalArgumentException(
+                        "Contains non-LDH ASCII characters");
+                }
+            }
+
+            if (dest.charAt(0) == '-' ||
+                dest.charAt(dest.length() - 1) == '-') {
+
+                throw new IllegalArgumentException(
+                        "Has leading or trailing hyphen");
+            }
+        }
+
+        if (!isASCII) {
+            // step 4
+            // If all code points are inside 0..0x7f, skip to step 8
+            if (!isAllASCII(dest.toString())) {
+                // step 5
+                // verify the sequence does not begin with ACE prefix
+                if(!startsWithACEPrefix(dest)){
+
+                    // step 6
+                    // encode the sequence with punycode
+                    try {
+                        dest = Punycode.encode(dest, null);
+                    } catch (java.text.ParseException e) {
+                        throw new IllegalArgumentException(e);
+                    }
+
+                    dest = toASCIILower(dest);
+
+                    // step 7
+                    // prepend the ACE prefix
+                    dest.insert(0, ACE_PREFIX);
+                } else {
+                    throw new IllegalArgumentException("The input starts with the ACE Prefix");
+                }
+
+            }
+        }
+
+        // step 8
+        // the length must be inside 1..63
+        if (dest.length() > MAX_LABEL_LENGTH) {
+            throw new IllegalArgumentException("The label in the input is too long");
+        }
+
+        return dest.toString();
+    }
+
+    //
+    // toUnicode operation; should only apply to a single label
+    //
+    private static String toUnicodeInternal(String label, int flag) {
+        boolean[] caseFlags = null;
+        StringBuffer dest;
+
+        // step 1
+        // find out if all the codepoints in input are ASCII
+        boolean isASCII = isAllASCII(label);
+
+        if(!isASCII){
+            // step 2
+            // perform the nameprep operation; flag ALLOW_UNASSIGNED is used here
+            try {
+                UCharacterIterator iter = UCharacterIterator.getInstance(label);
+                dest = namePrep.prepare(iter, flag);
+            } catch (Exception e) {
+                // toUnicode never fails; if any step fails, return the input string
+                return label;
+            }
+        } else {
+            dest = new StringBuffer(label);
+        }
+
+        // step 3
+        // verify ACE Prefix
+        if(startsWithACEPrefix(dest)) {
+
+            // step 4
+            // Remove the ACE Prefix
+            String temp = dest.substring(ACE_PREFIX_LENGTH, dest.length());
+
+            try {
+                // step 5
+                // Decode using punycode
+                StringBuffer decodeOut = Punycode.decode(new StringBuffer(temp), null);
+
+                // step 6
+                // Apply toASCII
+                String toASCIIOut = toASCII(decodeOut.toString(), flag);
+
+                // step 7
+                // verify
+                if (toASCIIOut.equalsIgnoreCase(dest.toString())) {
+                    // step 8
+                    // return output of step 5
+                    return decodeOut.toString();
+                }
+            } catch (Exception ignored) {
+                // no-op
+            }
+        }
+
+        // just return the input
+        return label;
+    }
+
+
+    //
+    // LDH stands for "letter/digit/hyphen", with characters restricted to the
+    // 26-letter Latin alphabet <A-Z a-z>, the digits <0-9>, and the hyphen
+    // <->.
+    // Non LDH refers to characters in the ASCII range, but which are not
+    // letters, digits or the hypen.
+    //
+    // non-LDH = 0..0x2C, 0x2E..0x2F, 0x3A..0x40, 0x5B..0x60, 0x7B..0x7F
+    //
+    private static boolean isNonLDHAsciiCodePoint(int ch){
+        return (0x0000 <= ch && ch <= 0x002C) ||
+               (0x002E <= ch && ch <= 0x002F) ||
+               (0x003A <= ch && ch <= 0x0040) ||
+               (0x005B <= ch && ch <= 0x0060) ||
+               (0x007B <= ch && ch <= 0x007F);
+    }
+
+    //
+    // search dots in a string and return the index of that character;
+    // or if there is no dots, return the length of input string
+    // dots might be: \u002E (full stop), \u3002 (ideographic full stop), \uFF0E (fullwidth full stop),
+    // and \uFF61 (halfwidth ideographic full stop).
+    //
+    private static int searchDots(String s, int start) {
+        int i;
+        for (i = start; i < s.length(); i++) {
+            if (isLabelSeparator(s.charAt(i))) {
+                break;
+            }
+        }
+
+        return i;
+    }
+
+    //
+    // to check if a string is a root label, ".".
+    //
+    private static boolean isRootLabel(String s) {
+        return (s.length() == 1 && isLabelSeparator(s.charAt(0)));
+    }
+
+    //
+    // to check if a character is a label separator, i.e. a dot character.
+    //
+    private static boolean isLabelSeparator(char c) {
+        return (c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61');
+    }
+
+    //
+    // to check if a string only contains US-ASCII code point
+    //
+    private static boolean isAllASCII(String input) {
+        boolean isASCII = true;
+        for (int i = 0; i < input.length(); i++) {
+            int c = input.charAt(i);
+            if (c > 0x7F) {
+                isASCII = false;
+                break;
+            }
+        }
+        return isASCII;
+    }
+
+    //
+    // to check if a string starts with ACE-prefix
+    //
+    private static boolean startsWithACEPrefix(StringBuffer input){
+        boolean startsWithPrefix = true;
+
+        if(input.length() < ACE_PREFIX_LENGTH){
+            return false;
+        }
+        for(int i = 0; i < ACE_PREFIX_LENGTH; i++){
+            if(toASCIILower(input.charAt(i)) != ACE_PREFIX.charAt(i)){
+                startsWithPrefix = false;
+            }
+        }
+        return startsWithPrefix;
+    }
+
+    private static char toASCIILower(char ch){
+        if('A' <= ch && ch <= 'Z'){
+            return (char)(ch + 'a' - 'A');
+        }
+        return ch;
+    }
+
+    private static StringBuffer toASCIILower(StringBuffer input){
+        StringBuffer dest = new StringBuffer();
+        for(int i = 0; i < input.length();i++){
+            dest.append(toASCIILower(input.charAt(i)));
+        }
+        return dest;
+    }
+    */
 }
diff --git a/ojluni/src/main/java/java/net/InMemoryCookieStore.java b/ojluni/src/main/java/java/net/InMemoryCookieStore.java
index 288dddb..3ee98dc 100644
--- a/ojluni/src/main/java/java/net/InMemoryCookieStore.java
+++ b/ojluni/src/main/java/java/net/InMemoryCookieStore.java
@@ -36,6 +36,13 @@
 import java.util.Iterator;
 import java.util.concurrent.locks.ReentrantLock;
 
+// Android-changed: App compat changes and bug fixes
+// b/26456024 Add targetSdkVersion based compatibility for domain matching
+// b/33034917 Support clearing cookies by adding it with "max-age=0"
+// b/25897688 InMemoryCookieStore ignores scheme (http/https) port and path of the cookie
+// Remove cookieJar and domainIndex. Use urlIndex as single Cookie storage
+// Fix InMemoryCookieStore#remove to verify cookie URI before removal
+// Fix InMemoryCookieStore#removeAll to return false if it's empty.
 /**
  * A simple in-memory java.net.CookieStore implementation
  *
@@ -45,11 +52,23 @@
  */
 public class InMemoryCookieStore implements CookieStore {
     // the in-memory representation of cookies
+    // BEGIN Android-removed: Remove cookieJar and domainIndex
+    /*
+    private List<HttpCookie> cookieJar = null;
+
+    // the cookies are indexed by its domain and associated uri (if present)
+    // CAUTION: when a cookie removed from main data structure (i.e. cookieJar),
+    //          it won't be cleared in domainIndex & uriIndex. Double-check the
+    //          presence of cookie when retrieve one form index store.
+    private Map<String, List<HttpCookie>> domainIndex = null;
+    */
+    // END Android-removed: Remove cookieJar and domainIndex
     private Map<URI, List<HttpCookie>> uriIndex = null;
 
     // use ReentrantLock instead of syncronized for scalability
     private ReentrantLock lock = null;
 
+    // BEGIN Android-changed: Add targetSdkVersion and remove cookieJar and domainIndex
     private final boolean applyMCompatibility;
 
     /**
@@ -64,6 +83,7 @@
         lock = new ReentrantLock(false);
         applyMCompatibility = (targetSdkVersion <= 23);
     }
+    // END Android-changed: Add targetSdkVersion and remove cookieJar and domainIndex
 
     /**
      * Add one cookie into cookie store.
@@ -101,6 +121,7 @@
         }
 
         List<HttpCookie> cookies = new ArrayList<HttpCookie>();
+        // BEGIN Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https)
         lock.lock();
         try {
             // check domainIndex first
@@ -110,7 +131,7 @@
         } finally {
             lock.unlock();
         }
-
+        // END Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https)
         return cookies;
     }
 
@@ -118,6 +139,7 @@
      * Get all cookies in cookie store, except those have expired
      */
     public List<HttpCookie> getCookies() {
+        // BEGIN Android-changed: Remove cookieJar and domainIndex
         List<HttpCookie> rt = new ArrayList<HttpCookie>();
 
         lock.lock();
@@ -137,6 +159,7 @@
             rt = Collections.unmodifiableList(rt);
             lock.unlock();
         }
+        // END Android-changed: Remove cookieJar and domainIndex
 
         return rt;
     }
@@ -169,6 +192,7 @@
             throw new NullPointerException("cookie is null");
         }
 
+        // BEGIN Android-changed: Fix uri not being removed from uriIndex
         lock.lock();
         try {
             uri = getEffectiveURI(uri);
@@ -185,6 +209,7 @@
         } finally {
             lock.unlock();
         }
+        // END Android-changed: Fix uri not being removed from uriIndex
     }
 
 
@@ -193,6 +218,7 @@
      */
     public boolean removeAll() {
         lock.lock();
+        // BEGIN Android-change: Return false if it's empty.
         boolean result = false;
 
         try {
@@ -203,6 +229,7 @@
         }
 
         return result;
+        // END Android-change: Return false if it's empty.
     }
 
 
@@ -251,6 +278,7 @@
             // need to check H & D component
             String D = host.substring(lengthDiff);
 
+            // Android-changed: b/26456024 targetSdkVersion based compatibility for domain matching
             // Android M and earlier: Cookies with domain "foo.com" would not match "bar.foo.com".
             // The RFC dictates that the user agent must treat those domains as if they had a
             // leading period and must therefore match "bar.foo.com".
@@ -270,6 +298,7 @@
 
     private void getInternal1(List<HttpCookie> cookies, Map<URI, List<HttpCookie>> cookieIndex,
             String host) {
+        // BEGIN Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https)
         // Use a separate list to handle cookies that need to be removed so
         // that there is no conflict with iterators.
         ArrayList<HttpCookie> toRemove = new ArrayList<HttpCookie>();
@@ -298,6 +327,7 @@
             }
             toRemove.clear();
         }
+        // END Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https)
     }
 
     // @param cookies           [OUT] contains the found cookies
@@ -308,6 +338,7 @@
         void getInternal2(List<HttpCookie> cookies, Map<T, List<HttpCookie>> cookieIndex,
                           T comparator)
     {
+        // BEGIN Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https)
         // Removed cookieJar
         for (T index : cookieIndex.keySet()) {
             if ((index == comparator) || (index != null && comparator.compareTo(index) == 0)) {
@@ -329,6 +360,7 @@
                 } // end of indexedCookies != null
             } // end of comparator.compareTo(index) == 0
         } // end of cookieIndex iteration
+        // END Android-changed: b/25897688 InMemoryCookieStore ignores scheme (http/https)
     }
 
     // add 'cookie' indexed by 'index' into 'indexStore'
@@ -339,6 +371,7 @@
         // Android-changed: "index" can be null. We only use the URI based
         // index on Android and we want to support null URIs. The underlying
         // store is a HashMap which will support null keys anyway.
+        // if (index != null) {
         List<HttpCookie> cookies = indexStore.get(index);
         if (cookies != null) {
             // there may already have the same cookie, so remove it first
@@ -359,6 +392,7 @@
     //
     private URI getEffectiveURI(URI uri) {
         URI effectiveURI = null;
+        // Android-added: Fix NullPointerException
         if (uri == null) {
             return null;
         }
diff --git a/ojluni/src/main/java/java/net/Inet4Address.java b/ojluni/src/main/java/java/net/Inet4Address.java
index 9c8e5fb..1fb7b92 100644
--- a/ojluni/src/main/java/java/net/Inet4Address.java
+++ b/ojluni/src/main/java/java/net/Inet4Address.java
@@ -93,6 +93,7 @@
      *  serialized */
     private static final long serialVersionUID = 3286316764910316507L;
 
+    // BEGIN Android-added: Define special-purpose IPv4 address
     /** @hide */
     public static final InetAddress ANY = new Inet4Address(null, new byte[] { 0, 0, 0, 0 });
 
@@ -103,7 +104,18 @@
     /** @hide */
     public static final InetAddress LOOPBACK =
             new Inet4Address("localhost", new byte[] { 127, 0, 0, 1 });
+    // END Android-added: Define special-purpose IPv4 address
 
+
+    // BEGIN Android-removed: Android doesn't need to call native init
+    /*
+     * Perform initializations.
+     *
+    static {
+        init();
+    }
+    */
+    // END Android-removed: Android doesn't need to call native init
     Inet4Address() {
         super();
         holder().hostName = null;
@@ -378,4 +390,12 @@
     {
         return (src[0] & 0xff) + "." + (src[1] & 0xff) + "." + (src[2] & 0xff) + "." + (src[3] & 0xff);
     }
+
+    // BEGIN Android-removed: Android doesn't need to call native init
+    /*
+     * Perform class load-time initializations.
+     *
+    private static native void init();
+    */
+    // END Android-removed: Android doesn't need to call native init
 }
diff --git a/ojluni/src/main/java/java/net/Inet6Address.java b/ojluni/src/main/java/java/net/Inet6Address.java
index ee946ee..c0aadb3 100644
--- a/ojluni/src/main/java/java/net/Inet6Address.java
+++ b/ojluni/src/main/java/java/net/Inet6Address.java
@@ -178,6 +178,15 @@
 class Inet6Address extends InetAddress {
     final static int INADDRSZ = 16;
 
+    // BEGIN Android-removed: Remove special handling for link-local addresses
+    /*
+    * cached scope_id - for link-local address use only.
+    *
+    private transient int cached_scope_id;  // 0
+    */
+    // END Android-removed: Remove special handling for link-local addresses
+
+    // BEGIN Android-added: Define special-purpose IPv6 address
     /** @hide */
     public static final InetAddress ANY =
             new Inet6Address("::", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
@@ -185,6 +194,7 @@
     /** @hide */
     public static final InetAddress LOOPBACK = new Inet6Address("ip6-localhost",
             new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 0);
+    // END Android-added: Define special-purpose IPv6 address
 
     private class Inet6AddressHolder {
 
@@ -379,6 +389,13 @@
 
     private static final long serialVersionUID = 6880410070516793377L;
 
+    // BEGIN Android-removed: Android doesn't need to call native init
+    /*
+    // Perform native initialization
+    static { init(); }
+    // END Android-removed: Android doesn't need to call native init
+    */
+
     Inet6Address() {
         super();
         holder.init(null, AF_INET6);
@@ -401,12 +418,16 @@
         } catch (UnknownHostException e) {} /* cant happen if ifname is null */
     }
 
-    Inet6Address (String hostName, byte addr[], NetworkInterface nif) throws UnknownHostException {
+    Inet6Address (String hostName, byte addr[], NetworkInterface nif)
+        throws UnknownHostException
+    {
         holder6 = new Inet6AddressHolder();
         initif (hostName, addr, nif);
     }
 
-    Inet6Address (String hostName, byte addr[], String ifname) throws UnknownHostException {
+    Inet6Address (String hostName, byte addr[], String ifname)
+        throws UnknownHostException
+    {
         holder6 = new Inet6AddressHolder();
         initstr (hostName, addr, ifname);
     }
@@ -495,8 +516,9 @@
         }
     }
 
-    private void initif(String hostName, byte addr[],NetworkInterface nif) throws UnknownHostException {
-        holder().hostName = hostName;
+    private void initif(String hostName, byte addr[], NetworkInterface nif)
+        throws UnknownHostException
+    {
         int family = -1;
         holder6.init(addr, nif);
 
@@ -948,4 +970,12 @@
         }
         return sb.toString();
     }
+
+    // BEGIN Android-removed: Android doesn't need to call native init
+    /*
+     * Perform class load-time initializations.
+     *
+    private static native void init();
+    */
+    // END Android-removed: Android doesn't need to call native init
 }
diff --git a/ojluni/src/main/java/java/net/URLStreamHandler.java b/ojluni/src/main/java/java/net/URLStreamHandler.java
index eac8a78..d5380c1 100644
--- a/ojluni/src/main/java/java/net/URLStreamHandler.java
+++ b/ojluni/src/main/java/java/net/URLStreamHandler.java
@@ -134,9 +134,9 @@
 
         boolean isRelPath = false;
         boolean queryOnly = false;
-        // BEGIN Android-changed
+        // BEGIN Android-changed: App compat
         boolean querySet = false;
-        // END Android-changed
+        // END Android-changed: App compat
 
 // FIX: should not assume query if opaque
         // Strip off the query part
@@ -148,22 +148,22 @@
                 if (limit > queryStart)
                     limit = queryStart;
                 spec = spec.substring(0, queryStart);
-                // BEGIN Android-changed
+                // BEGIN Android-changed: App compat
                 querySet = true;
-                // END Android-changed
+                // END Android-changed: App compat
             }
         }
 
         int i = 0;
         // Parse the authority part if any
-        // BEGIN Android-changed
+        // BEGIN Android-changed: App compat
         // boolean isUNCName = (start <= limit - 4) &&
         //                 (spec.charAt(start) == '/') &&
         //                 (spec.charAt(start + 1) == '/') &&
         //                 (spec.charAt(start + 2) == '/') &&
         //                 (spec.charAt(start + 3) == '/');
         boolean isUNCName = false;
-        // END Android-changed
+        // END Android-changed: App compat
         if (!isUNCName && (start <= limit - 2) && (spec.charAt(start) == '/') &&
             (spec.charAt(start + 1) == '/')) {
             start += 2;
@@ -226,7 +226,7 @@
                     if (ind >= 0) {
                         // port can be null according to RFC2396
                         if (host.length() > (ind + 1)) {
-                            // BEGIN Android-changed
+                            // BEGIN Android-changed: App compat
                             // port = Integer.parseInt(host.substring(ind + 1));
                             char firstPortChar = host.charAt(ind+1);
                             if (firstPortChar >= '0' && firstPortChar <= '9') {
@@ -235,7 +235,7 @@
                                 throw new IllegalArgumentException("invalid port: " +
                                                                    host.substring(ind + 1));
                             }
-                            // END Android-changed
+                            // END Android-changed: App compat
                         }
                         host = host.substring(0, ind);
                     }
@@ -248,16 +248,16 @@
                                                    port);
             start = i;
 
-            // BEGIN Android-changed
             // If the authority is defined then the path is defined by the
             // spec only; See RFC 2396 Section 5.2.4.
+            // BEGIN Android-changed: App compat
             // if (authority != null && authority.length() > 0)
             //   path = "";
             path = null;
             if (!querySet) {
                 query = null;
             }
-            // END Android-changed
+            // END Android-changed: App compat
         }
 
         if (host == null) {
@@ -282,14 +282,14 @@
                 path = seperator + spec.substring(start, limit);
             }
         }
-        // BEGIN Android-changed
+        // BEGIN Android-changed: App compat
         //else if (queryOnly && path != null) {
         //    int ind = path.lastIndexOf('/');
         //    if (ind < 0)
         //        ind = 0;
         //    path = path.substring(0, ind) + "/";
         //}
-        // END Android-changed
+        // END Android-changed: App compat
         if (path == null)
             path = "";
 
@@ -304,20 +304,22 @@
             // Remove embedded /../ if possible
             i = 0;
             while ((i = path.indexOf("/../", i)) >= 0) {
-                // BEGIN Android-changed
+                // BEGIN Android-changed: App compat
                 /*
                  * Trailing /../
                  */
                 if (i == 0) {
                     path = path.substring(i + 3);
                     i = 0;
-                // END Android-changed
+                // END Android-changed: App compat
                 /*
                  * A "/../" will cancel the previous segment and itself,
                  * unless that segment is a "/../" itself
                  * i.e. "/a/b/../c" becomes "/a/c"
                  * but "/../../a" should stay unchanged
                  */
+                // Android-changed: App compat
+                // if (i > 0 && (limit = path.lastIndexOf('/', i - 1)) >= 0 &&
                 } else if (i > 0 && (limit = path.lastIndexOf('/', i - 1)) >= 0 &&
                     (path.indexOf("/../", limit) != 0)) {
                     path = path.substring(0, limit) + path.substring(i + 3);
@@ -343,7 +345,7 @@
             if (path.endsWith("/."))
                 path = path.substring(0, path.length() -1);
 
-            // Remove trailing ?
+            // Android-changed: App compat: Remove trailing ?
             if (path.endsWith("?"))
                 path = path.substring(0, path.length() -1);
         }
@@ -374,6 +376,7 @@
      * @since 1.3
      */
     protected boolean equals(URL u1, URL u2) {
+        // Android-changed: Avoid network I/O
         return Objects.equals(u1.getRef(), u2.getRef()) &&
                Objects.equals(u1.getQuery(), u2.getQuery()) &&
                // sameFile compares the protocol, file, port & host components of
@@ -390,6 +393,7 @@
      * @since 1.3
      */
     protected int hashCode(URL u) {
+        // Android-changed: Avoid network I/O
         // Hash on the same set of fields that we compare in equals().
         return Objects.hash(
                 u.getRef(),
@@ -503,6 +507,8 @@
         if (u.getRef() != null)
             len += 1 + u.getRef().length();
 
+        // BEGIN Android-changed: Add a toExternalForm variant that optionally escapes illegal chars
+        // TODO: The variant has been removed. We can potentially revert the change
         StringBuilder result = new StringBuilder(len);
         result.append(u.getProtocol());
         result.append(":");
@@ -514,6 +520,7 @@
         if (fileAndQuery != null) {
             result.append(fileAndQuery);
         }
+        // END Android-changed: Add a toExternalForm variant that optionally escapes illegal chars
         if (u.getRef() != null) {
             result.append("#");
             result.append(u.getRef());