Skip to content

Commit

Permalink
Fix NPE when sending DatagramPacket
Browse files Browse the repository at this point in the history
This is due to code after

  getImpl().connect(address, port);

is not executed if it throws exception, leaving DatagramPacket in an
inconsistant state.

Re-arrange the order of code so that the state is now consistent.

Bug: 31218085
Bug: 31495962

(cherry-picked from commit 6764aa32a4b66a3c589f4a00615a1e36d87f308f)

Test: libcore.java.net.DatagramSocketTest
Change-Id: Iab9bfd9af211666564e49de62fdae964d6330daf
  • Loading branch information
kongy authored and narayank committed Sep 16, 2016
1 parent f8e5fce commit c7099b5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
20 changes: 20 additions & 0 deletions luni/src/test/java/libcore/java/net/DatagramSocketTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@

import junit.framework.TestCase;

import java.lang.reflect.Field;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.DatagramSocketImpl;
import java.net.InetAddress;

public class DatagramSocketTest extends TestCase {

Expand Down Expand Up @@ -55,4 +58,21 @@ public void testStateAfterClose() throws Exception {
assertEquals(-1, ds.getLocalPort());
assertNull(ds.getLocalSocketAddress());
}
// Socket should become connected even if impl.connect() failed and threw exception.
public void test_b31218085() throws Exception {
final int port = 9999;

try (DatagramSocket s = new DatagramSocket()) {
// Set fd of DatagramSocket to null, forcing impl.connect() to throw.
Field f = DatagramSocket.class.getDeclaredField("impl");
f.setAccessible(true);
DatagramSocketImpl impl = (DatagramSocketImpl) f.get(s);
f = DatagramSocketImpl.class.getDeclaredField("fd");
f.setAccessible(true);
f.set(impl, null);

s.connect(InetAddress.getLocalHost(), port);
assertTrue(s.isConnected());
}
}
}
4 changes: 3 additions & 1 deletion ojluni/src/main/java/java/net/DatagramSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,12 @@ private synchronized void connectInternal(InetAddress address, int port) throws
// connection will be emulated by DatagramSocket
connectState = ST_CONNECTED_NO_IMPL;
}*/
getImpl().connect(address, port);

// socket is now connected by the impl
connectState = ST_CONNECTED;

getImpl().connect(address, port);

// ----- END android -----
}

Expand Down

0 comments on commit c7099b5

Please sign in to comment.