diff options
author | jfrijters <jfrijters> | 2008-06-11 13:04:56 +0400 |
---|---|---|
committer | jfrijters <jfrijters> | 2008-06-11 13:04:56 +0400 |
commit | 9baab31e8c2ec69b4e098a164fb6ea6d0b8bb56c (patch) | |
tree | cb6ea0550c8653b7614e2d221e848180249e27b7 /openjdk/sun/nio/ch | |
parent | db4720da166361f480586decec8581648c0b7ab0 (diff) |
Converted tabs to spaces.
Diffstat (limited to 'openjdk/sun/nio/ch')
-rw-r--r-- | openjdk/sun/nio/ch/DatagramChannelImpl.java | 912 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/DefaultSelectorProvider.java | 10 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/DotNetSelectorImpl.java | 410 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/FileChannelImpl.java | 1310 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/FileKey.java | 24 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/IOUtil.java | 26 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/Net.java | 692 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/SelectionKeyImpl.java | 20 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/ServerSocketChannelImpl.java | 382 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/SocketChannelImpl.java | 1148 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/Util.java | 214 |
11 files changed, 2574 insertions, 2574 deletions
diff --git a/openjdk/sun/nio/ch/DatagramChannelImpl.java b/openjdk/sun/nio/ch/DatagramChannelImpl.java index 889ab510..13477e6a 100644 --- a/openjdk/sun/nio/ch/DatagramChannelImpl.java +++ b/openjdk/sun/nio/ch/DatagramChannelImpl.java @@ -43,7 +43,7 @@ class DatagramChannelImpl implements SelChImpl { // Our file descriptor - FileDescriptor fd = null; + FileDescriptor fd = null; // IDs of native threads doing reads and writes, for signalling private volatile long readerThread = 0; @@ -87,66 +87,66 @@ class DatagramChannelImpl public DatagramChannelImpl(SelectorProvider sp) - throws IOException + throws IOException { - super(sp); - this.fd = Net.socket(false); - this.state = ST_UNCONNECTED; + super(sp); + this.fd = Net.socket(false); + this.state = ST_UNCONNECTED; } public DatagramChannelImpl(SelectorProvider sp, FileDescriptor fd) - throws IOException + throws IOException { - super(sp); - this.fd = fd; - this.state = ST_UNCONNECTED; + super(sp); + this.fd = fd; + this.state = ST_UNCONNECTED; } public DatagramSocket socket() { - synchronized (stateLock) { - if (socket == null) - socket = DatagramSocketAdaptor.create(this); - return socket; - } + synchronized (stateLock) { + if (socket == null) + socket = DatagramSocketAdaptor.create(this); + return socket; + } } private void ensureOpen() throws ClosedChannelException { - if (!isOpen()) - throw new ClosedChannelException(); + if (!isOpen()) + throw new ClosedChannelException(); } - private SocketAddress sender; // Set by receive0 (## ugh) + private SocketAddress sender; // Set by receive0 (## ugh) public SocketAddress receive(ByteBuffer dst) throws IOException { - if (dst.isReadOnly()) - throw new IllegalArgumentException("Read-only buffer"); - if (dst == null) - throw new NullPointerException(); - synchronized (readLock) { + if (dst.isReadOnly()) + throw new IllegalArgumentException("Read-only buffer"); + if (dst == null) + throw new NullPointerException(); + synchronized (readLock) { ensureOpen(); // If socket is not bound then behave as if nothing received - if (!isBound()) // ## NotYetBoundException ?? + if (!isBound()) // ## NotYetBoundException ?? return null; - int n = 0; + int n = 0; ByteBuffer bb = null; - try { - begin(); - if (!isOpen()) - return null; + try { + begin(); + if (!isOpen()) + return null; SecurityManager security = System.getSecurityManager(); - readerThread = NativeThread.current(); + readerThread = NativeThread.current(); if (isConnected() || (security == null)) { - do { - n = receive0(dst); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - if (n == IOStatus.UNAVAILABLE) - return null; + do { + n = receive0(dst); + } while ((n == IOStatus.INTERRUPTED) && isOpen()); + if (n == IOStatus.UNAVAILABLE) + return null; } else { bb = ByteBuffer.allocate(dst.remaining()); for (;;) { - do { - n = receive0(bb); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); + do { + n = receive0(bb); + } while ((n == IOStatus.INTERRUPTED) && isOpen()); if (n == IOStatus.UNAVAILABLE) return null; InetSocketAddress isa = (InetSocketAddress)sender; @@ -165,13 +165,13 @@ class DatagramChannelImpl break; } } - return sender; - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } + return sender; + } finally { + readerThread = 0; + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } } public int send(ByteBuffer src, SocketAddress target) @@ -180,200 +180,200 @@ class DatagramChannelImpl if (src == null) throw new NullPointerException(); - synchronized (writeLock) { + synchronized (writeLock) { ensureOpen(); InetSocketAddress isa = (InetSocketAddress)target; InetAddress ia = isa.getAddress(); if (ia == null) throw new IOException("Target address not resolved"); - synchronized (stateLock) { - if (!isConnected()) { - if (target == null) - throw new NullPointerException(); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - if (ia.isMulticastAddress()) { - sm.checkMulticast(isa.getAddress()); - } else { - sm.checkConnect(isa.getAddress().getHostAddress(), - isa.getPort()); - } - } - } else { // Connected case; Check address then write - if (!target.equals(remoteAddress)) { - throw new IllegalArgumentException( + synchronized (stateLock) { + if (!isConnected()) { + if (target == null) + throw new NullPointerException(); + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + if (ia.isMulticastAddress()) { + sm.checkMulticast(isa.getAddress()); + } else { + sm.checkConnect(isa.getAddress().getHostAddress(), + isa.getPort()); + } + } + } else { // Connected case; Check address then write + if (!target.equals(remoteAddress)) { + throw new IllegalArgumentException( "Connected address not equal to target address"); - } + } return write(src); - } - } - - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - do { - n = sendImpl(src, isa); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); + } + } + + int n = 0; + try { + begin(); + if (!isOpen()) + return 0; + writerThread = NativeThread.current(); + do { + n = sendImpl(src, isa); + } while ((n == IOStatus.INTERRUPTED) && isOpen()); return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } + } finally { + writerThread = 0; + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } } public int read(ByteBuffer buf) throws IOException { - if (buf == null) - throw new NullPointerException(); - synchronized (readLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; - readerThread = NativeThread.current(); - do { - n = readImpl(buf); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } + if (buf == null) + throw new NullPointerException(); + synchronized (readLock) { + synchronized (stateLock) { + ensureOpen(); + if (!isConnected()) + throw new NotYetConnectedException(); + } + int n = 0; + try { + begin(); + if (!isOpen()) + return 0; + readerThread = NativeThread.current(); + do { + n = readImpl(buf); + } while ((n == IOStatus.INTERRUPTED) && isOpen()); + return IOStatus.normalize(n); + } finally { + readerThread = 0; + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } } private long read0(ByteBuffer[] bufs) throws IOException { if (bufs == null) throw new NullPointerException(); - synchronized (readLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; - readerThread = NativeThread.current(); - do { - n = readImpl(bufs); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } + synchronized (readLock) { + synchronized (stateLock) { + ensureOpen(); + if (!isConnected()) + throw new NotYetConnectedException(); + } + long n = 0; + try { + begin(); + if (!isOpen()) + return 0; + readerThread = NativeThread.current(); + do { + n = readImpl(bufs); + } while ((n == IOStatus.INTERRUPTED) && isOpen()); + return IOStatus.normalize(n); + } finally { + readerThread = 0; + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } } public long read(ByteBuffer[] dsts, int offset, int length) - throws IOException + throws IOException { if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) throw new IndexOutOfBoundsException(); - // ## Fix IOUtil.write so that we can avoid this array copy - return read0(Util.subsequence(dsts, offset, length)); + // ## Fix IOUtil.write so that we can avoid this array copy + return read0(Util.subsequence(dsts, offset, length)); } public int write(ByteBuffer buf) throws IOException { if (buf == null) throw new NullPointerException(); - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - do { - n = writeImpl(buf); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } + synchronized (writeLock) { + synchronized (stateLock) { + ensureOpen(); + if (!isConnected()) + throw new NotYetConnectedException(); + } + int n = 0; + try { + begin(); + if (!isOpen()) + return 0; + writerThread = NativeThread.current(); + do { + n = writeImpl(buf); + } while ((n == IOStatus.INTERRUPTED) && isOpen()); + return IOStatus.normalize(n); + } finally { + writerThread = 0; + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } } private long write0(ByteBuffer[] bufs) throws IOException { if (bufs == null) throw new NullPointerException(); - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - do { - n = writeImpl(bufs); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } + synchronized (writeLock) { + synchronized (stateLock) { + ensureOpen(); + if (!isConnected()) + throw new NotYetConnectedException(); + } + long n = 0; + try { + begin(); + if (!isOpen()) + return 0; + writerThread = NativeThread.current(); + do { + n = writeImpl(bufs); + } while ((n == IOStatus.INTERRUPTED) && isOpen()); + return IOStatus.normalize(n); + } finally { + writerThread = 0; + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } } public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException + throws IOException { if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) throw new IndexOutOfBoundsException(); - // ## Fix IOUtil.write so that we can avoid this array copy - return write0(Util.subsequence(srcs, offset, length)); + // ## Fix IOUtil.write so that we can avoid this array copy + return write0(Util.subsequence(srcs, offset, length)); } protected void implConfigureBlocking(boolean block) throws IOException { - IOUtil.configureBlocking(fd, block); + IOUtil.configureBlocking(fd, block); } public SocketOpts options() { - synchronized (stateLock) { - if (options == null) { - SocketOptsImpl.Dispatcher d - = new SocketOptsImpl.Dispatcher() { - int getInt(int opt) throws IOException { - return Net.getIntOption(fd, opt); - } - void setInt(int opt, int arg) - throws IOException - { - Net.setIntOption(fd, opt, arg); - } - }; - options = new SocketOptsImpl.IP(d); - } - return options; - } + synchronized (stateLock) { + if (options == null) { + SocketOptsImpl.Dispatcher d + = new SocketOptsImpl.Dispatcher() { + int getInt(int opt) throws IOException { + return Net.getIntOption(fd, opt); + } + void setInt(int opt, int arg) + throws IOException + { + Net.setIntOption(fd, opt, arg); + } + }; + options = new SocketOptsImpl.IP(d); + } + return options; + } } public boolean isBound() { @@ -381,143 +381,143 @@ class DatagramChannelImpl } public SocketAddress localAddress() { - synchronized (stateLock) { - if (isConnected() && (localAddress == null)) { - // Socket was not bound before connecting, - // so ask what the address turned out to be - localAddress = Net.localAddress(fd); - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - InetSocketAddress isa = (InetSocketAddress)localAddress; - sm.checkConnect(isa.getAddress().getHostAddress(), -1); - } - return localAddress; - } + synchronized (stateLock) { + if (isConnected() && (localAddress == null)) { + // Socket was not bound before connecting, + // so ask what the address turned out to be + localAddress = Net.localAddress(fd); + } + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + InetSocketAddress isa = (InetSocketAddress)localAddress; + sm.checkConnect(isa.getAddress().getHostAddress(), -1); + } + return localAddress; + } } public SocketAddress remoteAddress() { - synchronized (stateLock) { - return remoteAddress; - } + synchronized (stateLock) { + return remoteAddress; + } } public void bind(SocketAddress local) throws IOException { - synchronized (readLock) { - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (isBound()) - throw new AlreadyBoundException(); - InetSocketAddress isa = Net.checkAddress(local); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkListen(isa.getPort()); - Net.bind(fd, isa.getAddress(), isa.getPort()); - localAddress = Net.localAddress(fd); - } - } - } + synchronized (readLock) { + synchronized (writeLock) { + synchronized (stateLock) { + ensureOpen(); + if (isBound()) + throw new AlreadyBoundException(); + InetSocketAddress isa = Net.checkAddress(local); + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkListen(isa.getPort()); + Net.bind(fd, isa.getAddress(), isa.getPort()); + localAddress = Net.localAddress(fd); + } + } + } } public boolean isConnected() { - synchronized (stateLock) { - return (state == ST_CONNECTED); - } + synchronized (stateLock) { + return (state == ST_CONNECTED); + } } void ensureOpenAndUnconnected() throws IOException { // package-private - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (state != ST_UNCONNECTED) - throw new IllegalStateException("Connect already invoked"); - } + synchronized (stateLock) { + if (!isOpen()) + throw new ClosedChannelException(); + if (state != ST_UNCONNECTED) + throw new IllegalStateException("Connect already invoked"); + } } public DatagramChannel connect(SocketAddress sa) throws IOException { - int trafficClass = 0; - int localPort = 0; + int trafficClass = 0; + int localPort = 0; synchronized(readLock) { synchronized(writeLock) { - synchronized (stateLock) { - ensureOpenAndUnconnected(); - InetSocketAddress isa = Net.checkAddress(sa); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), - isa.getPort()); - // We simulate connectedness, so we don't call connect here, - // but if we're not yet bound, we should bind here. - if (!isBound()) - { - socket().bind(null); - } - //int n = Net.connect(fd, - // isa.getAddress(), - // isa.getPort(), - // trafficClass); - //if (n <= 0) - // throw new Error(); // Can't happen - - // Connection succeeded; disallow further invocation - state = ST_CONNECTED; - remoteAddress = sa; - sender = isa; - cachedSenderInetAddress = isa.getAddress(); - cachedSenderPort = isa.getPort(); - } + synchronized (stateLock) { + ensureOpenAndUnconnected(); + InetSocketAddress isa = Net.checkAddress(sa); + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkConnect(isa.getAddress().getHostAddress(), + isa.getPort()); + // We simulate connectedness, so we don't call connect here, + // but if we're not yet bound, we should bind here. + if (!isBound()) + { + socket().bind(null); + } + //int n = Net.connect(fd, + // isa.getAddress(), + // isa.getPort(), + // trafficClass); + //if (n <= 0) + // throw new Error(); // Can't happen + + // Connection succeeded; disallow further invocation + state = ST_CONNECTED; + remoteAddress = sa; + sender = isa; + cachedSenderInetAddress = isa.getAddress(); + cachedSenderPort = isa.getPort(); + } } } - return this; + return this; } public DatagramChannel disconnect() throws IOException { synchronized(readLock) { synchronized(writeLock) { - synchronized (stateLock) { - if (!isConnected() || !isOpen()) - return this; - InetSocketAddress isa = (InetSocketAddress)remoteAddress; - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), - isa.getPort()); - disconnect0(fd); - remoteAddress = null; - state = ST_UNCONNECTED; - } + synchronized (stateLock) { + if (!isConnected() || !isOpen()) + return this; + InetSocketAddress isa = (InetSocketAddress)remoteAddress; + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkConnect(isa.getAddress().getHostAddress(), + isa.getPort()); + disconnect0(fd); + remoteAddress = null; + state = ST_UNCONNECTED; + } } } - return this; + return this; } protected void implCloseSelectableChannel() throws IOException { - synchronized (stateLock) { - closeImpl(); - long th; - if ((th = readerThread) != 0) - NativeThread.signal(th); - if ((th = writerThread) != 0) - NativeThread.signal(th); - if (!isRegistered()) - kill(); - } + synchronized (stateLock) { + closeImpl(); + long th; + if ((th = readerThread) != 0) + NativeThread.signal(th); + if ((th = writerThread) != 0) + NativeThread.signal(th); + if (!isRegistered()) + kill(); + } } public void kill() throws IOException { - synchronized (stateLock) { - if (state == ST_KILLED) - return; - if (state == ST_UNINITIALIZED) { + synchronized (stateLock) { + if (state == ST_KILLED) + return; + if (state == ST_UNINITIALIZED) { state = ST_KILLED; - return; + return; } - assert !isOpen() && !isRegistered(); - closeImpl(); - state = ST_KILLED; - } + assert !isOpen() && !isRegistered(); + closeImpl(); + state = ST_KILLED; + } } /** @@ -530,11 +530,11 @@ class DatagramChannelImpl int newOps = initialOps; if ((ops & PollArrayWrapper.POLLNVAL) != 0) { - // This should only happen if this channel is pre-closed while a - // selection operation is in progress - // ## Throw an error if this channel has not been pre-closed - return false; - } + // This should only happen if this channel is pre-closed while a + // selection operation is in progress + // ## Throw an error if this channel has not been pre-closed + return false; + } if ((ops & (PollArrayWrapper.POLLERR | PollArrayWrapper.POLLHUP)) != 0) { @@ -583,7 +583,7 @@ class DatagramChannelImpl } public int getFDVal() { - throw new Error(); + throw new Error(); } @@ -591,190 +591,190 @@ class DatagramChannelImpl private void closeImpl() throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().Close(); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fd.getSocket().Close(); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } private static void disconnect0(FileDescriptor fd) throws IOException { - // since we simulate connectedness, we don't need to do anything here + // since we simulate connectedness, we don't need to do anything here } private int receive0(ByteBuffer bb) throws IOException { - byte[] buf = new byte[bb.remaining()]; - cli.System.Net.EndPoint[] remoteEP = new cli.System.Net.EndPoint[] + byte[] buf = new byte[bb.remaining()]; + cli.System.Net.EndPoint[] remoteEP = new cli.System.Net.EndPoint[] { new cli.System.Net.IPEndPoint(0, 0) }; - InetSocketAddress addr; - int length; - do - { - for (; ; ) - { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - length = fd.getSocket().ReceiveFrom(buf, 0, buf.length, cli.System.Net.Sockets.SocketFlags.wrap(cli.System.Net.Sockets.SocketFlags.None), remoteEP); - break; - } - catch (cli.System.Net.Sockets.SocketException x) - { - if (x.get_ErrorCode() == Net.WSAECONNRESET) - { - // A previous send failed (i.e. the remote host responded with a ICMP that the port is closed) and - // the winsock stack helpfully lets us know this, but we don't care so we just retry the receive. - continue; - } - if (x.get_ErrorCode() == Net.WSAEMSGSIZE) - { - // The buffer size was too small for the packet, ReceiveFrom receives the part of the packet - // that fits in the buffer and then throws an exception, so we have to ignore the exception in this case. - length = buf.length; - break; - } - if (x.get_ErrorCode() == Net.WSAEWOULDBLOCK) - { - return IOStatus.UNAVAILABLE; - } - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } - } - cli.System.Net.IPEndPoint ep = (cli.System.Net.IPEndPoint)remoteEP[0]; - addr = new InetSocketAddress(PlainSocketImpl.getInetAddressFromIPEndPoint(ep), ep.get_Port()); - } while (remoteAddress != null && !addr.equals(remoteAddress)); - sender = addr; - bb.put(buf, 0, length); - return length; + InetSocketAddress addr; + int length; + do + { + for (; ; ) + { + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + length = fd.getSocket().ReceiveFrom(buf, 0, buf.length, cli.System.Net.Sockets.SocketFlags.wrap(cli.System.Net.Sockets.SocketFlags.None), remoteEP); + break; + } + catch (cli.System.Net.Sockets.SocketException x) + { + if (x.get_ErrorCode() == Net.WSAECONNRESET) + { + // A previous send failed (i.e. the remote host responded with a ICMP that the port is closed) and + // the winsock stack helpfully lets us know this, but we don't care so we just retry the receive. + continue; + } + if (x.get_ErrorCode() == Net.WSAEMSGSIZE) + { + // The buffer size was too small for the packet, ReceiveFrom receives the part of the packet + // that fits in the buffer and then throws an exception, so we have to ignore the exception in this case. + length = buf.length; + break; + } + if (x.get_ErrorCode() == Net.WSAEWOULDBLOCK) + { + return IOStatus.UNAVAILABLE; + } + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } + } + cli.System.Net.IPEndPoint ep = (cli.System.Net.IPEndPoint)remoteEP[0]; + addr = new InetSocketAddress(PlainSocketImpl.getInetAddressFromIPEndPoint(ep), ep.get_Port()); + } while (remoteAddress != null && !addr.equals(remoteAddress)); + sender = addr; + bb.put(buf, 0, length); + return length; } private int sendImpl(ByteBuffer bb, InetSocketAddress addr) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - int position = bb.position(); - byte[] buf; - int offset; - int length; - if (bb.hasArray()) - { - buf = bb.array(); - offset = bb.arrayOffset() + bb.position(); - length = bb.remaining(); - } - else - { - buf = new byte[bb.remaining()]; - offset = 0; - length = buf.length; - bb.get(buf); - bb.position(position); - } - int sent = fd.getSocket().SendTo(buf, offset, length, cli.System.Net.Sockets.SocketFlags.wrap(cli.System.Net.Sockets.SocketFlags.None), new cli.System.Net.IPEndPoint(PlainSocketImpl.getAddressFromInetAddress(addr.getAddress()), addr.getPort())); - if (bb.hasArray()) - { - bb.position(position + sent); - } - else - { - bb.put(buf, 0, sent); - } - return sent; - } - catch (cli.System.Net.Sockets.SocketException x) - { - if (x.get_ErrorCode() == Net.WSAEWOULDBLOCK) - { - return IOStatus.UNAVAILABLE; - } - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + int position = bb.position(); + byte[] buf; + int offset; + int length; + if (bb.hasArray()) + { + buf = bb.array(); + offset = bb.arrayOffset() + bb.position(); + length = bb.remaining(); + } + else + { + buf = new byte[bb.remaining()]; + offset = 0; + length = buf.length; + bb.get(buf); + bb.position(position); + } + int sent = fd.getSocket().SendTo(buf, offset, length, cli.System.Net.Sockets.SocketFlags.wrap(cli.System.Net.Sockets.SocketFlags.None), new cli.System.Net.IPEndPoint(PlainSocketImpl.getAddressFromInetAddress(addr.getAddress()), addr.getPort())); + if (bb.hasArray()) + { + bb.position(position + sent); + } + else + { + bb.put(buf, 0, sent); + } + return sent; + } + catch (cli.System.Net.Sockets.SocketException x) + { + if (x.get_ErrorCode() == Net.WSAEWOULDBLOCK) + { + return IOStatus.UNAVAILABLE; + } + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } private int readImpl(ByteBuffer bb) throws IOException { - return receive0(bb); + return receive0(bb); } private long readImpl(ByteBuffer[] bb) throws IOException { - // This is a rather lame implementation. On .NET 2.0 we could make this more - // efficient by using the IList<ArraySegment<byte>> overload of Socket.Send() - long size = 0; - for (int i = 0; i < bb.length; i++) - { - size += bb[i].remaining(); - } - // UDP has a maximum packet size of 64KB - byte[] buf = new byte[(int)Math.min(65536, size)]; - int n = receive0(ByteBuffer.wrap(buf)); - if (n <= 0) - { - return n; - } - for (int i = 0, pos = 0; i < bb.length && pos < buf.length; i++) - { - int len = Math.min(bb[i].remaining(), buf.length - pos); - bb[i].put(buf, pos, len); - pos += len; - } - return n; + // This is a rather lame implementation. On .NET 2.0 we could make this more + // efficient by using the IList<ArraySegment<byte>> overload of Socket.Send() + long size = 0; + for (int i = 0; i < bb.length; i++) + { + size += bb[i].remaining(); + } + // UDP has a maximum packet size of 64KB + byte[] buf = new byte[(int)Math.min(65536, size)]; + int n = receive0(ByteBuffer.wrap(buf)); + if (n <= 0) + { + return n; + } + for (int i = 0, pos = 0; i < bb.length && pos < buf.length; i++) + { + int len = Math.min(bb[i].remaining(), buf.length - pos); + bb[i].put(buf, pos, len); + pos += len; + } + return n; } private int writeImpl(ByteBuffer bb) throws IOException { - return sendImpl(bb, (InetSocketAddress)remoteAddress); + return sendImpl(bb, (InetSocketAddress)remoteAddress); } private long writeImpl(ByteBuffer[] bb) throws IOException { - // This is a rather lame implementation. On .NET 2.0 we could make this more - // efficient by using the IList<ArraySegment<byte>> overload of Socket.Send() - long totalWritten = 0; - for (int i = 0; i < bb.length; i++) - { - try - { - int len = writeImpl(bb[i]); - if (len < 0) - { - return totalWritten > 0 ? totalWritten : len; - } - totalWritten += len; - } - catch (IOException x) - { - if (totalWritten > 0) - { - return totalWritten; - } - throw x; - } - } - return totalWritten; + // This is a rather lame implementation. On .NET 2.0 we could make this more + // efficient by using the IList<ArraySegment<byte>> overload of Socket.Send() + long totalWritten = 0; + for (int i = 0; i < bb.length; i++) + { + try + { + int len = writeImpl(bb[i]); + if (len < 0) + { + return totalWritten > 0 ? totalWritten : len; + } + totalWritten += len; + } + catch (IOException x) + { + if (totalWritten > 0) + { + return totalWritten; + } + throw x; + } + } + return totalWritten; } } diff --git a/openjdk/sun/nio/ch/DefaultSelectorProvider.java b/openjdk/sun/nio/ch/DefaultSelectorProvider.java index 5d760166..0b813081 100644 --- a/openjdk/sun/nio/ch/DefaultSelectorProvider.java +++ b/openjdk/sun/nio/ch/DefaultSelectorProvider.java @@ -45,11 +45,11 @@ public class DefaultSelectorProvider { * Returns the default SelectorProvider. */ public static SelectorProvider create() { - return new SelectorProviderImpl() { - public AbstractSelector openSelector() throws IOException { - return new DotNetSelectorImpl(this); - } - }; + return new SelectorProviderImpl() { + public AbstractSelector openSelector() throws IOException { + return new DotNetSelectorImpl(this); + } + }; } } diff --git a/openjdk/sun/nio/ch/DotNetSelectorImpl.java b/openjdk/sun/nio/ch/DotNetSelectorImpl.java index ea876e0a..ae0dfa5f 100644 --- a/openjdk/sun/nio/ch/DotNetSelectorImpl.java +++ b/openjdk/sun/nio/ch/DotNetSelectorImpl.java @@ -68,257 +68,257 @@ final class DotNetSelectorImpl extends SelectorImpl // class for fdMap entries private final static class MapEntry { - SelectionKeyImpl ski; - long updateCount = 0; - long clearedCount = 0; - MapEntry(SelectionKeyImpl ski) - { - this.ski = ski; - } + SelectionKeyImpl ski; + long updateCount = 0; + long clearedCount = 0; + MapEntry(SelectionKeyImpl ski) + { + this.ski = ski; + } } private final HashMap<Socket, MapEntry> fdMap = new HashMap<Socket, MapEntry>(); DotNetSelectorImpl(SelectorProvider sp) throws IOException { - super(sp); - wakeupPipe = Pipe.open(); - wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFD().getSocket(); + super(sp); + wakeupPipe = Pipe.open(); + wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFD().getSocket(); - // Disable the Nagle algorithm so that the wakeup is more immediate - SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink(); - (sink.sc).socket().setTcpNoDelay(true); - wakeupSinkFd = ((SelChImpl)sink).getFD().getSocket(); + // Disable the Nagle algorithm so that the wakeup is more immediate + SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink(); + (sink.sc).socket().setTcpNoDelay(true); + wakeupSinkFd = ((SelChImpl)sink).getFD().getSocket(); } protected int doSelect(long timeout) throws IOException { - if (channelArray == null) - throw new ClosedSelectorException(); - processDeregisterQueue(); - if (interruptTriggered) - { - resetWakeupSocket(); - return 0; - } + if (channelArray == null) + throw new ClosedSelectorException(); + processDeregisterQueue(); + if (interruptTriggered) + { + resetWakeupSocket(); + return 0; + } - ArrayList read = new ArrayList(); - ArrayList write = new ArrayList(); - ArrayList error = new ArrayList(); - for (int i = 0; i < channelArray.get_Count(); i++) - { - SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); - int ops = ski.interestOps(); - if (ski.channel() instanceof SocketChannelImpl) - { - // TODO there's a race condition here... - if (((SocketChannelImpl)ski.channel()).isConnected()) - { - ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE; - } - else - { - ops &= SelectionKey.OP_CONNECT; - } - } - if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) - { - read.Add(ski.getSocket()); - } - if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) - { - write.Add(ski.getSocket()); - } - if ((ops & SelectionKey.OP_CONNECT) != 0) - { - error.Add(ski.getSocket()); - } - } - read.Add(wakeupSourceFd); - try - { - begin(); - int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout); - try - { - if (false) throw new SocketException(); - // FXBUG docs say that -1 is infinite timeout, but that doesn't appear to work - Socket.Select(read, write, error, timeout < 0 ? Integer.MAX_VALUE : microSeconds); - } - catch (SocketException _) - { - read.Clear(); - write.Clear(); - error.Clear(); - } - } - finally - { - end(); - } - processDeregisterQueue(); - int updated = updateSelectedKeys(read, write, error); - // Done with poll(). Set wakeupSocket to nonsignaled for the next run. - resetWakeupSocket(); - return updated; + ArrayList read = new ArrayList(); + ArrayList write = new ArrayList(); + ArrayList error = new ArrayList(); + for (int i = 0; i < channelArray.get_Count(); i++) + { + SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); + int ops = ski.interestOps(); + if (ski.channel() instanceof SocketChannelImpl) + { + // TODO there's a race condition here... + if (((SocketChannelImpl)ski.channel()).isConnected()) + { + ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE; + } + else + { + ops &= SelectionKey.OP_CONNECT; + } + } + if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) + { + read.Add(ski.getSocket()); + } + if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) + { + write.Add(ski.getSocket()); + } + if ((ops & SelectionKey.OP_CONNECT) != 0) + { + error.Add(ski.getSocket()); + } + } + read.Add(wakeupSourceFd); + try + { + begin(); + int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout); + try + { + if (false) throw new SocketException(); + // FXBUG docs say that -1 is infinite timeout, but that doesn't appear to work + Socket.Select(read, write, error, timeout < 0 ? Integer.MAX_VALUE : microSeconds); + } + catch (SocketException _) + { + read.Clear(); + write.Clear(); + error.Clear(); + } + } + finally + { + end(); + } + processDeregisterQueue(); + int updated = updateSelectedKeys(read, write, error); + // Done with poll(). Set wakeupSocket to nonsignaled for the next run. + resetWakeupSocket(); + return updated; } private int updateSelectedKeys(ArrayList read, ArrayList write, ArrayList error) { - updateCount++; - int keys = processFDSet(updateCount, read, PollArrayWrapper.POLLIN); - keys += processFDSet(updateCount, write, PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); - keys += processFDSet(updateCount, error, PollArrayWrapper.POLLIN | PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); - return keys; + updateCount++; + int keys = processFDSet(updateCount, read, PollArrayWrapper.POLLIN); + keys += processFDSet(updateCount, write, PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); + keys += processFDSet(updateCount, error, PollArrayWrapper.POLLIN | PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); + return keys; } private int processFDSet(long updateCount, ArrayList sockets, int rOps) { - int numKeysUpdated = 0; - for (int i = 0; i < sockets.get_Count(); i++) - { - Socket desc = (Socket)sockets.get_Item(i); - if (desc == wakeupSourceFd) - { - synchronized (interruptLock) - { - interruptTriggered = true; - } - continue; - } - MapEntry me = fdMap.get(desc); - // If me is null, the key was deregistered in the previous - // processDeregisterQueue. - if (me == null) - continue; - SelectionKeyImpl sk = me.ski; - if (selectedKeys.contains(sk)) - { // Key in selected set - if (me.clearedCount != updateCount) - { - if (sk.channel.translateAndSetReadyOps(rOps, sk) && - (me.updateCount != updateCount)) - { - me.updateCount = updateCount; - numKeysUpdated++; - } - } - else - { // The readyOps have been set; now add - if (sk.channel.translateAndUpdateReadyOps(rOps, sk) && - (me.updateCount != updateCount)) - { - me.updateCount = updateCount; - numKeysUpdated++; - } - } - me.clearedCount = updateCount; - } - else - { // Key is not in selected set yet - if (me.clearedCount != updateCount) - { - sk.channel.translateAndSetReadyOps(rOps, sk); - if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) - { - selectedKeys.add(sk); - me.updateCount = updateCount; - numKeysUpdated++; - } - } - else - { // The readyOps have been set; now add - sk.channel.translateAndUpdateReadyOps(rOps, sk); - if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) - { - selectedKeys.add(sk); - me.updateCount = updateCount; - numKeysUpdated++; - } - } - me.clearedCount = updateCount; - } - } - return numKeysUpdated; + int numKeysUpdated = 0; + for (int i = 0; i < sockets.get_Count(); i++) + { + Socket desc = (Socket)sockets.get_Item(i); + if (desc == wakeupSourceFd) + { + synchronized (interruptLock) + { + interruptTriggered = true; + } + continue; + } + MapEntry me = fdMap.get(desc); + // If me is null, the key was deregistered in the previous + // processDeregisterQueue. + if (me == null) + continue; + SelectionKeyImpl sk = me.ski; + if (selectedKeys.contains(sk)) + { // Key in selected set + if (me.clearedCount != updateCount) + { + if (sk.channel.translateAndSetReadyOps(rOps, sk) && + (me.updateCount != updateCount)) + { + me.updateCount = updateCount; + numKeysUpdated++; + } + } + else + { // The readyOps have been set; now add + if (sk.channel.translateAndUpdateReadyOps(rOps, sk) && + (me.updateCount != updateCount)) + { + me.updateCount = updateCount; + numKeysUpdated++; + } + } + me.clearedCount = updateCount; + } + else + { // Key is not in selected set yet + if (me.clearedCount != updateCount) + { + sk.channel.translateAndSetReadyOps(rOps, sk); + if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) + { + selectedKeys.add(sk); + me.updateCount = updateCount; + numKeysUpdated++; + } + } + else + { // The readyOps have been set; now add + sk.channel.translateAndUpdateReadyOps(rOps, sk); + if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) + { + selectedKeys.add(sk); + me.updateCount = updateCount; + numKeysUpdated++; + } + } + me.clearedCount = updateCount; + } + } + return numKeysUpdated; } protected void implClose() throws IOException { - if (channelArray != null) - { - // prevent further wakeup - synchronized (interruptLock) { - interruptTriggered = true; - } - wakeupPipe.sink().close(); - wakeupPipe.source().close(); - for (int i = 0; i < channelArray.get_Count(); i++) - { // Deregister channels - SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); - deregister(ski); - SelectableChannel selch = ski.channel(); - if (!selch.isOpen() && !selch.isRegistered()) - ((SelChImpl)selch).kill(); - } - selectedKeys = null; - channelArray = null; - } + if (channelArray != null) + { + // prevent further wakeup + synchronized (interruptLock) { + interruptTriggered = true; + } + wakeupPipe.sink().close(); + wakeupPipe.source().close(); + for (int i = 0; i < channelArray.get_Count(); i++) + { // Deregister channels + SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); + deregister(ski); + SelectableChannel selch = ski.channel(); + if (!selch.isOpen() && !selch.isRegistered()) + ((SelChImpl)selch).kill(); + } + selectedKeys = null; + channelArray = null; + } } protected void implRegister(SelectionKeyImpl ski) { - channelArray.Add(ski); - fdMap.put(ski.getSocket(), new MapEntry(ski)); - keys.add(ski); + channelArray.Add(ski); + fdMap.put(ski.getSocket(), new MapEntry(ski)); + keys.add(ski); } protected void implDereg(SelectionKeyImpl ski) throws IOException { - channelArray.Remove(ski); - fdMap.remove(ski.getSocket()); - keys.remove(ski); - selectedKeys.remove(ski); - deregister(ski); - SelectableChannel selch = ski.channel(); - if (!selch.isOpen() && !selch.isRegistered()) - { - ((SelChImpl)selch).kill(); - } + channelArray.Remove(ski); + fdMap.remove(ski.getSocket()); + keys.remove(ski); + selectedKeys.remove(ski); + deregister(ski); + SelectableChannel selch = ski.channel(); + if (!selch.isOpen() && !selch.isRegistered()) + { + ((SelChImpl)selch).kill(); + } } public Selector wakeup() { - synchronized (interruptLock) - { - if (!interruptTriggered) - { - setWakeupSocket(); - interruptTriggered = true; - } - } - return this; + synchronized (interruptLock) + { + if (!interruptTriggered) + { + setWakeupSocket(); + interruptTriggered = true; + } + } + return this; } // Sets Windows wakeup socket to a signaled state. private void setWakeupSocket() { - wakeupSinkFd.Send(new byte[1]); + wakeupSinkFd.Send(new byte[1]); } // Sets Windows wakeup socket to a non-signaled state. private void resetWakeupSocket() { - synchronized (interruptLock) - { - if (interruptTriggered == false) - return; - resetWakeupSocket0(wakeupSourceFd); - interruptTriggered = false; - } + synchronized (interruptLock) + { + if (interruptTriggered == false) + return; + resetWakeupSocket0(wakeupSourceFd); + interruptTriggered = false; + } } private static void resetWakeupSocket0(Socket wakeupSourceFd) { - while (wakeupSourceFd.get_Available() > 0) - { - wakeupSourceFd.Receive(new byte[1]); - } + while (wakeupSourceFd.get_Available() > 0) + { + wakeupSourceFd.Receive(new byte[1]); + } } } diff --git a/openjdk/sun/nio/ch/FileChannelImpl.java b/openjdk/sun/nio/ch/FileChannelImpl.java index b63da1bd..7d5ccc9f 100644 --- a/openjdk/sun/nio/ch/FileChannelImpl.java +++ b/openjdk/sun/nio/ch/FileChannelImpl.java @@ -86,9 +86,9 @@ public class FileChannelImpl private FileChannelImpl(FileDescriptor fd, boolean readable, boolean writable, Object parent, boolean append) { - this.fd = fd; - this.readable = readable; - this.writable = writable; + this.fd = fd; + this.readable = readable; + this.writable = writable; this.parent = parent; this.appending = append; } @@ -97,22 +97,22 @@ public class FileChannelImpl // of java.io.File{Input,Output}Stream and RandomAccessFile // public static FileChannel open(FileDescriptor fd, - boolean readable, boolean writable, - Object parent) + boolean readable, boolean writable, + Object parent) { - return new FileChannelImpl(fd, readable, writable, parent, false); + return new FileChannelImpl(fd, readable, writable, parent, false); } public static FileChannel open(FileDescriptor fd, - boolean readable, boolean writable, - Object parent, boolean append) + boolean readable, boolean writable, + Object parent, boolean append) { - return new FileChannelImpl(fd, readable, writable, parent, append); + return new FileChannelImpl(fd, readable, writable, parent, append); } private void ensureOpen() throws IOException { - if (!isOpen()) - throw new ClosedChannelException(); + if (!isOpen()) + throw new ClosedChannelException(); } @@ -130,287 +130,287 @@ public class FileChannelImpl }); } - if (parent != null) { - - // Close the fd via the parent stream's close method. The parent - // will reinvoke our close method, which is defined in the - // superclass AbstractInterruptibleChannel, but the isOpen logic in - // that method will prevent this method from being reinvoked. - // - if (parent instanceof FileInputStream) - ((FileInputStream)parent).close(); - else if (parent instanceof FileOutputStream) - ((FileOutputStream)parent).close(); - else if (parent instanceof RandomAccessFile) - ((RandomAccessFile)parent).close(); - else - assert false; - - } else { - fd.close(); - } + if (parent != null) { + + // Close the fd via the parent stream's close method. The parent + // will reinvoke our close method, which is defined in the + // superclass AbstractInterruptibleChannel, but the isOpen logic in + // that method will prevent this method from being reinvoked. + // + if (parent instanceof FileInputStream) + ((FileInputStream)parent).close(); + else if (parent instanceof FileOutputStream) + ((FileOutputStream)parent).close(); + else if (parent instanceof RandomAccessFile) + ((RandomAccessFile)parent).close(); + else + assert false; + + } else { + fd.close(); + } } public int read(ByteBuffer dst) throws IOException { - ensureOpen(); - if (!readable) - throw new NonReadableChannelException(); - synchronized (positionLock) { - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; - n = readImpl(dst); - return IOStatus.normalize(n); - } finally { - end(n > 0); - assert IOStatus.check(n); - } - } + ensureOpen(); + if (!readable) + throw new NonReadableChannelException(); + synchronized (positionLock) { + int n = 0; + try { + begin(); + if (!isOpen()) + return 0; + n = readImpl(dst); + return IOStatus.normalize(n); + } finally { + end(n > 0); + assert IOStatus.check(n); + } + } } private long read0(ByteBuffer[] dsts) throws IOException { - ensureOpen(); + ensureOpen(); if (!readable) throw new NonReadableChannelException(); - synchronized (positionLock) { - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; - n = readImpl(dsts); - return IOStatus.normalize(n); - } finally { - end(n > 0); - assert IOStatus.check(n); - } - } + synchronized (positionLock) { + long n = 0; + try { + begin(); + if (!isOpen()) + return 0; + n = readImpl(dsts); + return IOStatus.normalize(n); + } finally { + end(n > 0); + assert IOStatus.check(n); + } + } } public long read(ByteBuffer[] dsts, int offset, int length) - throws IOException + throws IOException { if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) throw new IndexOutOfBoundsException(); - // ## Fix IOUtil.write so that we can avoid this array copy - return read0(Util.subsequence(dsts, offset, length)); + // ## Fix IOUtil.write so that we can avoid this array copy + return read0(Util.subsequence(dsts, offset, length)); } public int write(ByteBuffer src) throws IOException { - ensureOpen(); + ensureOpen(); if (!writable) throw new NonWritableChannelException(); - synchronized (positionLock) { - int n = 0; - try { - begin(); - if (!isOpen()) - return 0; + synchronized (positionLock) { + int n = 0; + try { + begin(); + if (!isOpen()) + return 0; if (appending) position(size()); - n = writeImpl(src); - return IOStatus.normalize(n); - } finally { - end(n > 0); - assert IOStatus.check(n); - } - } + n = writeImpl(src); + return IOStatus.normalize(n); + } finally { + end(n > 0); + assert IOStatus.check(n); + } + } } private long write0(ByteBuffer[] srcs) throws IOException { - ensureOpen(); + ensureOpen(); if (!writable) throw new NonWritableChannelException(); - synchronized (positionLock) { - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; + synchronized (positionLock) { + long n = 0; + try { + begin(); + if (!isOpen()) + return 0; if (appending) position(size()); - n = writeImpl(srcs); - return IOStatus.normalize(n); - } finally { - end(n > 0); - assert IOStatus.check(n); - } - } + n = writeImpl(srcs); + return IOStatus.normalize(n); + } finally { + end(n > 0); + assert IOStatus.check(n); + } + } } public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException + throws IOException { if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) throw new IndexOutOfBoundsException(); - // ## Fix IOUtil.write so that we can avoid this array copy - return write0(Util.subsequence(srcs, offset, length)); + // ## Fix IOUtil.write so that we can avoid this array copy + return write0(Util.subsequence(srcs, offset, length)); } // -- Other operations -- public long position() throws IOException { - ensureOpen(); - synchronized (positionLock) { - long p = -1; - try { - begin(); - if (!isOpen()) - return 0; - do { - p = position0(fd, -1); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(p); - } finally { - end(p > -1); - assert IOStatus.check(p); - } - } + ensureOpen(); + synchronized (positionLock) { + long p = -1; + try { + begin(); + if (!isOpen()) + return 0; + do { + p = position0(fd, -1); + } while ((p == IOStatus.INTERRUPTED) && isOpen()); + return IOStatus.normalize(p); + } finally { + end(p > -1); + assert IOStatus.check(p); + } + } } public FileChannel position(long newPosition) throws IOException { - ensureOpen(); + ensureOpen(); if (newPosition < 0) throw new IllegalArgumentException(); - synchronized (positionLock) { - long p = -1; - try { - begin(); - if (!isOpen()) - return null; - do { - p = position0(fd, newPosition); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - return this; - } finally { - end(p > -1); - assert IOStatus.check(p); - } - } + synchronized (positionLock) { + long p = -1; + try { + begin(); + if (!isOpen()) + return null; + do { + p = position0(fd, newPosition); + } while ((p == IOStatus.INTERRUPTED) && isOpen()); + return this; + } finally { + end(p > -1); + assert IOStatus.check(p); + } + } } public long size() throws IOException { - ensureOpen(); - synchronized (positionLock) { - long s = -1; - try { - begin(); - if (!isOpen()) - return -1; - do { - s = size0(fd); - } while ((s == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(s); - } finally { - end(s > -1); - assert IOStatus.check(s); - } - } + ensureOpen(); + synchronized (positionLock) { + long s = -1; + try { + begin(); + if (!isOpen()) + return -1; + do { + s = size0(fd); + } while ((s == IOStatus.INTERRUPTED) && isOpen()); + return IOStatus.normalize(s); + } finally { + end(s > -1); + assert IOStatus.check(s); + } + } } public FileChannel truncate(long size) throws IOException { - ensureOpen(); + ensureOpen(); if (size < 0) throw new IllegalArgumentException(); if (size > size()) return this; - if (!writable) - throw new NonWritableChannelException(); - synchronized (positionLock) { + if (!writable) + throw new NonWritableChannelException(); + synchronized (positionLock) { int rv = -1; - long p = -1; - try { - begin(); - if (!isOpen()) - return null; + long p = -1; + try { + begin(); + if (!isOpen()) + return null; // get current position - do { - p = position0(fd, -1); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - if (!isOpen()) + do { + p = position0(fd, -1); + } while ((p == IOStatus.INTERRUPTED) && isOpen()); + if (!isOpen()) return null; assert p >= 0; - // truncate file - do { - rv = truncate0(fd, size); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); + // truncate file + do { + rv = truncate0(fd, size); + } while ((rv == IOStatus.INTERRUPTED) && isOpen()); if (!isOpen()) return null; - // set position to size if greater than size + // set position to size if greater than size if (p > size) p = size; do { rv = (int)position0(fd, p); } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - return this; - } finally { - end(rv > -1); - assert IOStatus.check(rv); - } - } + return this; + } finally { + end(rv > -1); + assert IOStatus.check(rv); + } + } } public void force(boolean metaData) throws IOException { - ensureOpen(); - int rv = -1; - try { - begin(); - if (!isOpen()) - return; - do { - rv = force0(fd, metaData); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - } finally { - end(rv > -1); - assert IOStatus.check(rv); - } + ensureOpen(); + int rv = -1; + try { + begin(); + if (!isOpen()) + return; + do { + rv = force0(fd, metaData); + } while ((rv == IOStatus.INTERRUPTED) && isOpen()); + } finally { + end(rv > -1); + assert IOStatus.check(rv); + } } private long transferToArbitraryChannel(long position, int icount, - WritableByteChannel target) - throws IOException + WritableByteChannel target) + throws IOException { - // Untrusted target: Use a newly-erased buffer - int c = Math.min(icount, TRANSFER_SIZE); + // Untrusted target: Use a newly-erased buffer + int c = Math.min(icount, TRANSFER_SIZE); ByteBuffer bb = ByteBuffer.allocate(c); - long tw = 0; // Total bytes written - long pos = position; - try { - while (tw < icount) { - bb.limit(Math.min((int)(icount - tw), TRANSFER_SIZE)); - int nr = read(bb, pos); - if (nr <= 0) - break; - bb.flip(); - // ## Bug: Will block writing target if this channel - // ## is asynchronously closed - int nw = target.write(bb); - tw += nw; - if (nw != nr) - break; - pos += nw; - bb.clear(); - } - return tw; - } catch (IOException x) { - if (tw > 0) - return tw; - throw x; + long tw = 0; // Total bytes written + long pos = position; + try { + while (tw < icount) { + bb.limit(Math.min((int)(icount - tw), TRANSFER_SIZE)); + int nr = read(bb, pos); + if (nr <= 0) + break; + bb.flip(); + // ## Bug: Will block writing target if this channel + // ## is asynchronously closed + int nw = target.write(bb); + tw += nw; + if (nw != nr) + break; + pos += nw; + bb.clear(); + } + return tw; + } catch (IOException x) { + if (tw > 0) + return tw; + throw x; } } public long transferTo(long position, long count, - WritableByteChannel target) - throws IOException + WritableByteChannel target) + throws IOException { - ensureOpen(); + ensureOpen(); if (!target.isOpen()) throw new ClosedChannelException(); if (!readable) @@ -420,15 +420,15 @@ public class FileChannelImpl throw new NonWritableChannelException(); if ((position < 0) || (count < 0)) throw new IllegalArgumentException(); - long sz = size(); + long sz = size(); if (position > sz) return 0; - int icount = (int)Math.min(count, Integer.MAX_VALUE); + int icount = (int)Math.min(count, Integer.MAX_VALUE); if ((sz - position) < icount) icount = (int)(sz - position); - // Slow path for untrusted targets - return transferToArbitraryChannel(position, icount, target); + // Slow path for untrusted targets + return transferToArbitraryChannel(position, icount, target); } private static final int TRANSFER_SIZE = 8192; @@ -437,40 +437,40 @@ public class FileChannelImpl long position, long count) throws IOException { - // Untrusted target: Use a newly-erased buffer - int c = (int)Math.min(count, TRANSFER_SIZE); + // Untrusted target: Use a newly-erased buffer + int c = (int)Math.min(count, TRANSFER_SIZE); ByteBuffer bb = ByteBuffer.allocate(c); - long tw = 0; // Total bytes written - long pos = position; + long tw = 0; // Total bytes written + long pos = position; try { - while (tw < count) { + while (tw < count) { bb.limit((int)Math.min((count - tw), (long)TRANSFER_SIZE)); - // ## Bug: Will block reading src if this channel - // ## is asynchronously closed - int nr = src.read(bb); - if (nr <= 0) - break; - bb.flip(); - int nw = write(bb, pos); - tw += nw; - if (nw != nr) - break; - pos += nw; - bb.clear(); - } - return tw; - } catch (IOException x) { - if (tw > 0) - return tw; - throw x; + // ## Bug: Will block reading src if this channel + // ## is asynchronously closed + int nr = src.read(bb); + if (nr <= 0) + break; + bb.flip(); + int nw = write(bb, pos); + tw += nw; + if (nw != nr) + break; + pos += nw; + bb.clear(); + } + return tw; + } catch (IOException x) { + if (tw > 0) + return tw; + throw x; } } public long transferFrom(ReadableByteChannel src, - long position, long count) - throws IOException + long position, long count) + throws IOException { - ensureOpen(); + ensureOpen(); if (!src.isOpen()) throw new ClosedChannelException(); if (!writable) @@ -491,17 +491,17 @@ public class FileChannelImpl if (!readable) throw new NonReadableChannelException(); ensureOpen(); - int n = 0; - try { - begin(); - if (!isOpen()) - return -1; - n = readImpl(dst, position); - return IOStatus.normalize(n); - } finally { - end(n > 0); - assert IOStatus.check(n); - } + int n = 0; + try { + begin(); + if (!isOpen()) + return -1; + n = readImpl(dst, position); + return IOStatus.normalize(n); + } finally { + end(n > 0); + assert IOStatus.check(n); + } } public int write(ByteBuffer src, long position) throws IOException { @@ -512,48 +512,48 @@ public class FileChannelImpl if (!writable) throw new NonWritableChannelException(); ensureOpen(); - int n = 0; - try { - begin(); - if (!isOpen()) - return -1; - n = writeImpl(src, position); - return IOStatus.normalize(n); - } finally { - end(n > 0); - assert IOStatus.check(n); - } + int n = 0; + try { + begin(); + if (!isOpen()) + return -1; + n = writeImpl(src, position); + return IOStatus.normalize(n); + } finally { + end(n > 0); + assert IOStatus.check(n); + } } // -- Memory-mapped buffers -- private static class Unmapper - implements Runnable + implements Runnable { - private long address; - private long size; + private long address; + private long size; - private Unmapper(long address, long size) { - assert (address != 0); - this.address = address; - this.size = size; - } + private Unmapper(long address, long size) { + assert (address != 0); + this.address = address; + this.size = size; + } - public void run() { - if (address == 0) - return; - unmap0(address, size); - address = 0; - } + public void run() { + if (address == 0) + return; + unmap0(address, size); + address = 0; + } } private static void unmap(MappedByteBuffer bb) { - Cleaner cl = ((DirectBuffer)bb).cleaner(); - if (cl != null) - cl.clean(); + Cleaner cl = ((DirectBuffer)bb).cleaner(); + if (cl != null) + cl.clean(); } private static final int MAP_RO = 0; @@ -564,41 +564,41 @@ public class FileChannelImpl throws IOException { ensureOpen(); - if (position < 0L) - throw new IllegalArgumentException("Negative position"); - if (size < 0L) - throw new IllegalArgumentException("Negative size"); + if (position < 0L) + throw new IllegalArgumentException("Negative position"); + if (size < 0L) + throw new IllegalArgumentException("Negative size"); if (position + size < 0) throw new IllegalArgumentException("Position + size overflow"); - if (size > Integer.MAX_VALUE) - throw new IllegalArgumentException("Size exceeds Integer.MAX_VALUE"); - int imode = -1; + if (size > Integer.MAX_VALUE) + throw new IllegalArgumentException("Size exceeds Integer.MAX_VALUE"); + int imode = -1; if (mode == MapMode.READ_ONLY) - imode = MAP_RO; - else if (mode == MapMode.READ_WRITE) - imode = MAP_RW; - else if (mode == MapMode.PRIVATE) - imode = MAP_PV; - assert (imode >= 0); - if ((mode != MapMode.READ_ONLY) && !writable) - throw new NonWritableChannelException(); - if (!readable) - throw new NonReadableChannelException(); - - long addr = -1; - try { - begin(); - if (!isOpen()) - return null; + imode = MAP_RO; + else if (mode == MapMode.READ_WRITE) + imode = MAP_RW; + else if (mode == MapMode.PRIVATE) + imode = MAP_PV; + assert (imode >= 0); + if ((mode != MapMode.READ_ONLY) && !writable) + throw new NonWritableChannelException(); + if (!readable) + throw new NonReadableChannelException(); + + long addr = -1; + try { + begin(); + if (!isOpen()) + return null; if (size() < position + size) { // Extend file size if (!writable) { throw new IOException("Channel not open for writing " + "- cannot extend file to required size"); } - int rv; - do { - rv = truncate0(fd, position + size); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); + int rv; + do { + rv = truncate0(fd, position + size); + } while ((rv == IOStatus.INTERRUPTED) && isOpen()); } if (size == 0) { addr = 0; @@ -608,28 +608,28 @@ public class FileChannelImpl return Util.newMappedByteBuffer(0, 0, null); } - int pagePosition = (int)(position % allocationGranularity); - long mapPosition = position - pagePosition; - long mapSize = size + pagePosition; - try { - // If no exception was thrown from map0, the address is valid - addr = map0(imode, mapPosition, mapSize); - } catch (OutOfMemoryError x) { - // An OutOfMemoryError may indicate that we've exhausted memory - // so force gc and re-attempt map - System.gc(); - try { - Thread.sleep(100); - } catch (InterruptedException y) { - Thread.currentThread().interrupt(); - } - try { - addr = map0(imode, mapPosition, mapSize); - } catch (OutOfMemoryError y) { - // After a second OOME, fail - throw new IOException("Map failed", y); - } - } + int pagePosition = (int)(position % allocationGranularity); + long mapPosition = position - pagePosition; + long mapSize = size + pagePosition; + try { + // If no exception was thrown from map0, the address is valid + addr = map0(imode, mapPosition, mapSize); + } catch (OutOfMemoryError x) { + // An OutOfMemoryError may indicate that we've exhausted memory + // so force gc and re-attempt map + System.gc(); + try { + Thread.sleep(100); + } catch (InterruptedException y) { + Thread.currentThread().interrupt(); + } + try { + addr = map0(imode, mapPosition, mapSize); + } catch (OutOfMemoryError y) { + // After a second OOME, fail + throw new IOException("Map failed", y); + } + } assert (IOStatus.checkAll(addr)); assert (addr % allocationGranularity == 0); @@ -639,9 +639,9 @@ public class FileChannelImpl return Util.newMappedByteBufferR(isize, addr + pagePosition, um); else return Util.newMappedByteBuffer(isize, addr + pagePosition, um); - } finally { - end(IOStatus.checkAll(addr)); - } + } finally { + end(IOStatus.checkAll(addr)); + } } @@ -693,21 +693,21 @@ public class FileChannelImpl } public FileLock lock(long position, long size, boolean shared) - throws IOException + throws IOException { ensureOpen(); - if (shared && !readable) - throw new NonReadableChannelException(); - if (!shared && !writable) - throw new NonWritableChannelException(); + if (shared && !readable) + throw new NonReadableChannelException(); + if (!shared && !writable) + throw new NonWritableChannelException(); FileLockImpl fli = new FileLockImpl(this, position, size, shared); FileLockTable flt = fileLockTable(); flt.add(fli); boolean i = true; try { begin(); - if (!isOpen()) - return null; + if (!isOpen()) + return null; int result = lock0(fd, true, position, size, shared); if (result == RET_EX_LOCK) { assert shared; @@ -734,33 +734,33 @@ public class FileChannelImpl } public FileLock tryLock(long position, long size, boolean shared) - throws IOException + throws IOException { ensureOpen(); - if (shared && !readable) - throw new NonReadableChannelException(); - if (!shared && !writable) - throw new NonWritableChannelException(); + if (shared && !readable) + throw new NonReadableChannelException(); + if (!shared && !writable) + throw new NonWritableChannelException(); FileLockImpl fli = new FileLockImpl(this, position, size, shared); FileLockTable flt = fileLockTable(); flt.add(fli); - int result = lock0(fd, false, position, size, shared); - if (result == NO_LOCK) { - flt.remove(fli); - return null; - } - if (result == RET_EX_LOCK) { - assert shared; - FileLockImpl fli2 = new FileLockImpl(this, position, size, - false); - flt.replace(fli, fli2); - return fli2; - } + int result = lock0(fd, false, position, size, shared); + if (result == NO_LOCK) { + flt.remove(fli); + return null; + } + if (result == RET_EX_LOCK) { + assert shared; + FileLockImpl fli2 = new FileLockImpl(this, position, size, + false); + flt.replace(fli, fli2); + return fli2; + } return fli; } void release(FileLockImpl fli) throws IOException { - ensureOpen(); + ensureOpen(); release0(fd, fli.position(), fli.size()); assert fileLockTable != null; fileLockTable.remove(fli); @@ -1059,336 +1059,336 @@ public class FileChannelImpl private int readImpl(ByteBuffer dst) throws IOException { - if (dst.hasArray()) - { - byte[] buf = dst.array(); - int len = fd.readBytes(buf, dst.arrayOffset() + dst.position(), dst.remaining()); - if (len > 0) - { - dst.position(dst.position() + len); - } - return len; - } - else - { - byte[] buf = new byte[dst.remaining()]; - int len = fd.readBytes(buf, 0, buf.length); - if (len > 0) - { - dst.put(buf, 0, len); - } - return len; - } + if (dst.hasArray()) + { + byte[] buf = dst.array(); + int len = fd.readBytes(buf, dst.arrayOffset() + dst.position(), dst.remaining()); + if (len > 0) + { + dst.position(dst.position() + len); + } + return len; + } + else + { + byte[] buf = new byte[dst.remaining()]; + int len = fd.readBytes(buf, 0, buf.length); + if (len > 0) + { + dst.put(buf, 0, len); + } + return len; + } } private int readImpl(ByteBuffer dst, long position) throws IOException { - synchronized (positionLock) - { - long prev = position0(fd, -1); - try - { - position0(fd, position); - return readImpl(dst); - } - finally - { - position0(fd, prev); - } - } + synchronized (positionLock) + { + long prev = position0(fd, -1); + try + { + position0(fd, position); + return readImpl(dst); + } + finally + { + position0(fd, prev); + } + } } private long readImpl(ByteBuffer[] dsts) throws IOException { - long totalRead = 0; - try - { - for (int i = 0; i < dsts.length; i++) - { - int size = dsts[i].remaining(); - if (size > 0) - { - int read = readImpl(dsts[i]); - if (read < 0) - { - break; - } - totalRead += read; - if (read < size || fd.available() == 0) - { - break; - } - } - } - } - catch (IOException x) - { - if (totalRead == 0) - { - throw x; - } - } - return totalRead; + long totalRead = 0; + try + { + for (int i = 0; i < dsts.length; i++) + { + int size = dsts[i].remaining(); + if (size > 0) + { + int read = readImpl(dsts[i]); + if (read < 0) + { + break; + } + totalRead += read; + if (read < size || fd.available() == 0) + { + break; + } + } + } + } + catch (IOException x) + { + if (totalRead == 0) + { + throw x; + } + } + return totalRead; } private int writeImpl(ByteBuffer src) throws IOException { - if (src.hasArray()) - { - byte[] buf = src.array(); - int len = src.remaining(); - fd.writeBytes(buf, src.arrayOffset() + src.position(), len); - src.position(src.position() + len); - return len; - } - else - { - int pos = src.position(); - byte[] buf = new byte[src.remaining()]; - src.get(buf); - fd.writeBytes(buf, 0, buf.length); - src.position(pos + buf.length); - return buf.length; - } + if (src.hasArray()) + { + byte[] buf = src.array(); + int len = src.remaining(); + fd.writeBytes(buf, src.arrayOffset() + src.position(), len); + src.position(src.position() + len); + return len; + } + else + { + int pos = src.position(); + byte[] buf = new byte[src.remaining()]; + src.get(buf); + fd.writeBytes(buf, 0, buf.length); + src.position(pos + buf.length); + return buf.length; + } } private int writeImpl(ByteBuffer src, long position) throws IOException { - synchronized (positionLock) - { - long prev = position0(fd, -1); - try - { - position0(fd, position); - return writeImpl(src); - } - finally - { - position0(fd, prev); - } - } + synchronized (positionLock) + { + long prev = position0(fd, -1); + try + { + position0(fd, position); + return writeImpl(src); + } + finally + { + position0(fd, prev); + } + } } private long writeImpl(ByteBuffer[] srcs) throws IOException { - long totalWritten = 0; - try - { - for (int i = 0; i < srcs.length; i++) - { - int size = srcs[i].remaining(); - if (size > 0) - { - int written = writeImpl(srcs[i]); - totalWritten += written; - if (written < size) - { - break; - } - } - } - } - catch (IOException x) - { - if (totalWritten == 0) - { - throw x; - } - } - return totalWritten; + long totalWritten = 0; + try + { + for (int i = 0; i < srcs.length; i++) + { + int size = srcs[i].remaining(); + if (size > 0) + { + int written = writeImpl(srcs[i]); + totalWritten += written; + if (written < size) + { + break; + } + } + } + } + catch (IOException x) + { + if (totalWritten == 0) + { + throw x; + } + } + return totalWritten; } @StructLayoutAttribute.Annotation(LayoutKind.__Enum.Sequential) private static final class OVERLAPPED extends cli.System.Object { - IntPtr Internal; - IntPtr InternalHigh; - int OffsetLow; - int OffsetHigh; - IntPtr hEvent; + IntPtr Internal; + IntPtr InternalHigh; + int OffsetLow; + int OffsetHigh; + IntPtr hEvent; } // Grabs a file lock static int lock0(FileDescriptor fd, boolean blocking, long pos, long size, boolean shared) throws IOException { - FileStream fs = (FileStream)fd.getStream(); - if (winNT) - { - int LOCKFILE_FAIL_IMMEDIATELY = 1; - int LOCKFILE_EXCLUSIVE_LOCK = 2; - int ERROR_LOCK_VIOLATION = 33; - int flags = 0; - OVERLAPPED o = new OVERLAPPED(); - o.OffsetLow = (int)pos; - o.OffsetHigh = (int)(pos >> 32); - if (!blocking) - { - flags |= LOCKFILE_FAIL_IMMEDIATELY; - } - if (!shared) - { - flags |= LOCKFILE_EXCLUSIVE_LOCK; - } - int result = LockFileEx(fs.get_SafeFileHandle(), flags, 0, (int)size, (int)(size >> 32), o); - if (result == 0) - { - int error = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); - if (!blocking && error == ERROR_LOCK_VIOLATION) - { - return NO_LOCK; - } - throw new IOException("Lock failed"); - } - return LOCKED; - } - else - { - try - { - if (false) throw new cli.System.ArgumentOutOfRangeException(); - for (;;) - { - try - { - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fs.Lock(pos, size); - return shared ? RET_EX_LOCK : LOCKED; - } - catch (cli.System.IO.IOException x) - { - if (!blocking) - { - return NO_LOCK; - } - cli.System.Threading.Thread.Sleep(100); - } - catch (cli.System.ObjectDisposedException x) - { - throw new IOException(x.getMessage()); - } - } - } - catch (cli.System.ArgumentOutOfRangeException x) - { - throw new IOException(x.getMessage()); - } - } + FileStream fs = (FileStream)fd.getStream(); + if (winNT) + { + int LOCKFILE_FAIL_IMMEDIATELY = 1; + int LOCKFILE_EXCLUSIVE_LOCK = 2; + int ERROR_LOCK_VIOLATION = 33; + int flags = 0; + OVERLAPPED o = new OVERLAPPED(); + o.OffsetLow = (int)pos; + o.OffsetHigh = (int)(pos >> 32); + if (!blocking) + { + flags |= LOCKFILE_FAIL_IMMEDIATELY; + } + if (!shared) + { + flags |= LOCKFILE_EXCLUSIVE_LOCK; + } + int result = LockFileEx(fs.get_SafeFileHandle(), flags, 0, (int)size, (int)(size >> 32), o); + if (result == 0) + { + int error = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); + if (!blocking && error == ERROR_LOCK_VIOLATION) + { + return NO_LOCK; + } + throw new IOException("Lock failed"); + } + return LOCKED; + } + else + { + try + { + if (false) throw new cli.System.ArgumentOutOfRangeException(); + for (;;) + { + try + { + if (false) throw new cli.System.IO.IOException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fs.Lock(pos, size); + return shared ? RET_EX_LOCK : LOCKED; + } + catch (cli.System.IO.IOException x) + { + if (!blocking) + { + return NO_LOCK; + } + cli.System.Threading.Thread.Sleep(100); + } + catch (cli.System.ObjectDisposedException x) + { + throw new IOException(x.getMessage()); + } + } + } + catch (cli.System.ArgumentOutOfRangeException x) + { + throw new IOException(x.getMessage()); + } + } } // Releases a file lock static void release0(FileDescriptor fd, long pos, long size) throws IOException { - FileStream fs = (FileStream)fd.getStream(); - if (winNT) - { - OVERLAPPED o = new OVERLAPPED(); - o.OffsetLow = (int)pos; - o.OffsetHigh = (int)(pos >> 32); - int result = UnlockFileEx(fs.get_SafeFileHandle(), 0, (int)size, (int)(size >> 32), o); - if (result == 0) - { - throw new IOException("Release failed"); - } - } - else - { - try - { - if (false) throw new cli.System.ArgumentOutOfRangeException(); - if (false) throw new cli.System.IO.IOException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fs.Unlock(pos, size); - } - catch (cli.System.ArgumentOutOfRangeException x) - { - throw new IOException(x.getMessage()); - } - catch (cli.System.IO.IOException x) - { - throw new IOException(x.getMessage()); - } - catch (cli.System.ObjectDisposedException x) - { - throw new IOException(x.getMessage()); - } - } + FileStream fs = (FileStream)fd.getStream(); + if (winNT) + { + OVERLAPPED o = new OVERLAPPED(); + o.OffsetLow = (int)pos; + o.OffsetHigh = (int)(pos >> 32); + int result = UnlockFileEx(fs.get_SafeFileHandle(), 0, (int)size, (int)(size >> 32), o); + if (result == 0) + { + throw new IOException("Release failed"); + } + } + else + { + try + { + if (false) throw new cli.System.ArgumentOutOfRangeException(); + if (false) throw new cli.System.IO.IOException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fs.Unlock(pos, size); + } + catch (cli.System.ArgumentOutOfRangeException x) + { + throw new IOException(x.getMessage()); + } + catch (cli.System.IO.IOException x) + { + throw new IOException(x.getMessage()); + } + catch (cli.System.ObjectDisposedException x) + { + throw new IOException(x.getMessage()); + } + } } // Creates a new mapping private long map0(int prot, long position, long length) throws IOException { - FileStream fs = (FileStream)fd.getStream(); - if (win32) - return mapViewOfFileWin32(fs, prot, position, length); - else - return mapViewOfFilePosix(fs, prot, position, length); + FileStream fs = (FileStream)fd.getStream(); + if (win32) + return mapViewOfFileWin32(fs, prot, position, length); + else + return mapViewOfFilePosix(fs, prot, position, length); } private static long mapViewOfFileWin32(FileStream fs, int prot, long position, long length) throws IOException { - try - { - int PAGE_READONLY = 2; - int PAGE_READWRITE = 4; - int PAGE_WRITECOPY = 8; - - int FILE_MAP_WRITE = 2; - int FILE_MAP_READ = 4; - int FILE_MAP_COPY = 1; - - int fileProtect; - int mapAccess; - - switch (prot) - { - case MAP_RO: - fileProtect = PAGE_READONLY; - mapAccess = FILE_MAP_READ; - break; - case MAP_RW: - fileProtect = PAGE_READWRITE; - mapAccess = FILE_MAP_WRITE; - break; - case MAP_PV: - fileProtect = PAGE_WRITECOPY; - mapAccess = FILE_MAP_COPY; - break; - default: - throw new Error(); - } - - long maxSize = length + position; - SafeFileHandle hFileMapping = CreateFileMapping(fs.get_SafeFileHandle(), IntPtr.Zero, fileProtect, (int)(maxSize >> 32), (int)maxSize, null); - int err = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); - if (hFileMapping.get_IsInvalid()) - { - throw new IOException("Win32 error " + err); - } - IntPtr p = MapViewOfFile(hFileMapping, mapAccess, (int)(position >> 32), (int)position, IntPtr.op_Explicit(length)); - err = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); - hFileMapping.Close(); - if (p.Equals(IntPtr.Zero)) - { - if (err == 8 /*ERROR_NOT_ENOUGH_MEMORY*/) - { - throw new OutOfMemoryError("Map failed"); - } - throw new IOException("Win32 error " + err); - } - cli.System.GC.AddMemoryPressure(length); - return p.ToInt64(); - } - finally - { - cli.System.GC.KeepAlive(fs); - } + try + { + int PAGE_READONLY = 2; + int PAGE_READWRITE = 4; + int PAGE_WRITECOPY = 8; + + int FILE_MAP_WRITE = 2; + int FILE_MAP_READ = 4; + int FILE_MAP_COPY = 1; + + int fileProtect; + int mapAccess; + + switch (prot) + { + case MAP_RO: + fileProtect = PAGE_READONLY; + mapAccess = FILE_MAP_READ; + break; + case MAP_RW: + fileProtect = PAGE_READWRITE; + mapAccess = FILE_MAP_WRITE; + break; + case MAP_PV: + fileProtect = PAGE_WRITECOPY; + mapAccess = FILE_MAP_COPY; + break; + default: + throw new Error(); + } + + long maxSize = length + position; + SafeFileHandle hFileMapping = CreateFileMapping(fs.get_SafeFileHandle(), IntPtr.Zero, fileProtect, (int)(maxSize >> 32), (int)maxSize, null); + int err = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); + if (hFileMapping.get_IsInvalid()) + { + throw new IOException("Win32 error " + err); + } + IntPtr p = MapViewOfFile(hFileMapping, mapAccess, (int)(position >> 32), (int)position, IntPtr.op_Explicit(length)); + err = cli.System.Runtime.InteropServices.Marshal.GetLastWin32Error(); + hFileMapping.Close(); + if (p.Equals(IntPtr.Zero)) + { + if (err == 8 /*ERROR_NOT_ENOUGH_MEMORY*/) + { + throw new OutOfMemoryError("Map failed"); + } + throw new IOException("Win32 error " + err); + } + cli.System.GC.AddMemoryPressure(length); + return p.ToInt64(); + } + finally + { + cli.System.GC.KeepAlive(fs); + } } private static long mapViewOfFilePosix(FileStream fs, int prot, long position, long length) throws IOException { - byte writeable = prot != MAP_RO ? (byte)1 : (byte)0; - byte copy_on_write = prot == MAP_PV ? (byte)1 : (byte)0; + byte writeable = prot != MAP_RO ? (byte)1 : (byte)0; + byte copy_on_write = prot == MAP_PV ? (byte)1 : (byte)0; IntPtr p = ikvm_mmap(fs.get_SafeFileHandle(), writeable, copy_on_write, position, (int)length); cli.System.GC.KeepAlive(fs); // HACK ikvm_mmap should really be changed to return a null pointer on failure, @@ -1398,7 +1398,7 @@ public class FileChannelImpl { throw new IOException("file mapping failed"); } - cli.System.GC.AddMemoryPressure(length); + cli.System.GC.AddMemoryPressure(length); return p.ToInt64(); } @@ -1457,26 +1457,26 @@ public class FileChannelImpl else ikvm_munmap(IntPtr.op_Explicit(address), (int)length); cli.System.GC.RemoveMemoryPressure(length); - return 0; + return 0; } // Forces output to device private static int force0(FileDescriptor fd, boolean metaData) throws IOException { - FileStream fs = (FileStream)fd.getStream(); - boolean rc = win32 ? flushWin32(fs) : flushPosix(fs); - if (!rc) - { - throw new IOException("Force failed"); - } - return 0; + FileStream fs = (FileStream)fd.getStream(); + boolean rc = win32 ? flushWin32(fs) : flushPosix(fs); + if (!rc) + { + throw new IOException("Force failed"); + } + return 0; } // Truncates a file private static int truncate0(FileDescriptor fd, long size) throws IOException { - fd.setLength(size); - return 0; + fd.setLength(size); + return 0; } // Sets or reports this file's position @@ -1484,18 +1484,18 @@ public class FileChannelImpl // otherwise the position is set to offset private static long position0(FileDescriptor fd, long offset) throws IOException { - if (offset == -1) - { - return fd.getFilePointer(); - } - fd.seek(offset); - return offset; + if (offset == -1) + { + return fd.getFilePointer(); + } + fd.seek(offset); + return offset; } // Reports this file's size private static long size0(FileDescriptor fd) throws IOException { - return fd.length(); + return fd.length(); } static { diff --git a/openjdk/sun/nio/ch/FileKey.java b/openjdk/sun/nio/ch/FileKey.java index af98346a..4feec5d3 100644 --- a/openjdk/sun/nio/ch/FileKey.java +++ b/openjdk/sun/nio/ch/FileKey.java @@ -33,25 +33,25 @@ public class FileKey public static FileKey create(FileDescriptor fd) { - FileKey fk = new FileKey(); - fk.path = ((cli.System.IO.FileStream)fd.getStream()).get_Name(); - try - { - fk.path = new File(fk.path).getCanonicalPath(); - } - catch (IOException x) - { - } - return fk; + FileKey fk = new FileKey(); + fk.path = ((cli.System.IO.FileStream)fd.getStream()).get_Name(); + try + { + fk.path = new File(fk.path).getCanonicalPath(); + } + catch (IOException x) + { + } + return fk; } public int hashCode() { - return path.hashCode(); + return path.hashCode(); } public boolean equals(Object obj) { - return obj == this || (obj instanceof FileKey && ((FileKey)obj).path.equals(path)); + return obj == this || (obj instanceof FileKey && ((FileKey)obj).path.equals(path)); } } diff --git a/openjdk/sun/nio/ch/IOUtil.java b/openjdk/sun/nio/ch/IOUtil.java index 836c4c3a..fd89aabe 100644 --- a/openjdk/sun/nio/ch/IOUtil.java +++ b/openjdk/sun/nio/ch/IOUtil.java @@ -39,26 +39,26 @@ import java.nio.channels.spi.*; class IOUtil { - private IOUtil() { } // No instantiation + private IOUtil() { } // No instantiation static boolean randomBytes(byte[] someBytes) { - try - { - if (false) throw new cli.System.Security.Cryptography.CryptographicException(); - cli.System.Security.Cryptography.RNGCryptoServiceProvider csp = new cli.System.Security.Cryptography.RNGCryptoServiceProvider(); - csp.GetBytes(someBytes); - return true; - } - catch (cli.System.Security.Cryptography.CryptographicException _) - { - return false; - } + try + { + if (false) throw new cli.System.Security.Cryptography.CryptographicException(); + cli.System.Security.Cryptography.RNGCryptoServiceProvider csp = new cli.System.Security.Cryptography.RNGCryptoServiceProvider(); + csp.GetBytes(someBytes); + return true; + } + catch (cli.System.Security.Cryptography.CryptographicException _) + { + return false; + } } static void configureBlocking(FileDescriptor fd, boolean blocking) throws IOException { - Net.configureBlocking(fd, blocking); + Net.configureBlocking(fd, blocking); } } diff --git a/openjdk/sun/nio/ch/Net.java b/openjdk/sun/nio/ch/Net.java index 835d6f9e..af9c957c 100644 --- a/openjdk/sun/nio/ch/Net.java +++ b/openjdk/sun/nio/ch/Net.java @@ -44,7 +44,7 @@ import java.nio.ByteBuffer; import java.nio.channels.*; -class Net { // package-private +class Net { // package-private private Net() { } @@ -63,442 +63,442 @@ class Net { // package-private static FileDescriptor serverSocket(boolean stream) throws IOException { - return socket(stream); + return socket(stream); } static FileDescriptor socket(boolean stream) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - FileDescriptor fd = new FileDescriptor(); - if (stream) - { - fd.setSocket(new cli.System.Net.Sockets.Socket(AddressFamily.wrap(AddressFamily.InterNetwork), SocketType.wrap(SocketType.Stream), ProtocolType.wrap(ProtocolType.Tcp))); - } - else - { - fd.setSocket(new cli.System.Net.Sockets.Socket(AddressFamily.wrap(AddressFamily.InterNetwork), SocketType.wrap(SocketType.Dgram), ProtocolType.wrap(ProtocolType.Udp))); - } - return fd; - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + FileDescriptor fd = new FileDescriptor(); + if (stream) + { + fd.setSocket(new cli.System.Net.Sockets.Socket(AddressFamily.wrap(AddressFamily.InterNetwork), SocketType.wrap(SocketType.Stream), ProtocolType.wrap(ProtocolType.Tcp))); + } + else + { + fd.setSocket(new cli.System.Net.Sockets.Socket(AddressFamily.wrap(AddressFamily.InterNetwork), SocketType.wrap(SocketType.Dgram), ProtocolType.wrap(ProtocolType.Udp))); + } + return fd; + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } } static void bind(FileDescriptor fd, InetAddress addr, int port) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().Bind(new IPEndPoint(PlainSocketImpl.getAddressFromInetAddress(addr), port)); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fd.getSocket().Bind(new IPEndPoint(PlainSocketImpl.getAddressFromInetAddress(addr), port)); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } static void configureBlocking(FileDescriptor fd, boolean blocking) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().set_Blocking(blocking); - } - catch (cli.System.Net.Sockets.SocketException x) - { - if (x.get_ErrorCode() == WSAEINVAL) - { - // Work around for winsock issue. You can't set a socket to blocking if a connection request is pending, - // so we'll have to set the blocking again in SocketChannelImpl.checkConnect(). - return; - } - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException _) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fd.getSocket().set_Blocking(blocking); + } + catch (cli.System.Net.Sockets.SocketException x) + { + if (x.get_ErrorCode() == WSAEINVAL) + { + // Work around for winsock issue. You can't set a socket to blocking if a connection request is pending, + // so we'll have to set the blocking again in SocketChannelImpl.checkConnect(). + return; + } + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException _) + { + throw new SocketException("Socket is closed"); + } } static InetSocketAddress localAddress(FileDescriptor fd) { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - IPEndPoint ep = (IPEndPoint)fd.getSocket().get_LocalEndPoint(); - return new InetSocketAddress(PlainSocketImpl.getInetAddressFromIPEndPoint(ep), ep.get_Port()); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw new Error(x); - } - catch (cli.System.ObjectDisposedException x) - { - throw new Error(x); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + IPEndPoint ep = (IPEndPoint)fd.getSocket().get_LocalEndPoint(); + return new InetSocketAddress(PlainSocketImpl.getInetAddressFromIPEndPoint(ep), ep.get_Port()); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw new Error(x); + } + catch (cli.System.ObjectDisposedException x) + { + throw new Error(x); + } } static int localPortNumber(FileDescriptor fd) { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - IPEndPoint ep = (IPEndPoint)fd.getSocket().get_LocalEndPoint(); - return ep == null ? 0 : ep.get_Port(); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw new Error(x); - } - catch (cli.System.ObjectDisposedException x) - { - throw new Error(x); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + IPEndPoint ep = (IPEndPoint)fd.getSocket().get_LocalEndPoint(); + return ep == null ? 0 : ep.get_Port(); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw new Error(x); + } + catch (cli.System.ObjectDisposedException x) + { + throw new Error(x); + } } private static int mapSocketOptionLevel(int opt) throws IOException { - switch (opt) - { - case SocketOptions.SO_BROADCAST: - case SocketOptions.SO_KEEPALIVE: - case SocketOptions.SO_LINGER: - case SocketOptions.SO_OOBINLINE: - case SocketOptions.SO_RCVBUF: - case SocketOptions.SO_SNDBUF: - case SocketOptions.SO_REUSEADDR: - return SocketOptionLevel.Socket; - case SocketOptions.IP_MULTICAST_LOOP: - case SocketOptions.IP_TOS: - return SocketOptionLevel.IP; - case SocketOptions.TCP_NODELAY: - return SocketOptionLevel.Tcp; - default: - throw new SocketException("unsupported socket option: " + opt); - } + switch (opt) + { + case SocketOptions.SO_BROADCAST: + case SocketOptions.SO_KEEPALIVE: + case SocketOptions.SO_LINGER: + case SocketOptions.SO_OOBINLINE: + case SocketOptions.SO_RCVBUF: + case SocketOptions.SO_SNDBUF: + case SocketOptions.SO_REUSEADDR: + return SocketOptionLevel.Socket; + case SocketOptions.IP_MULTICAST_LOOP: + case SocketOptions.IP_TOS: + return SocketOptionLevel.IP; + case SocketOptions.TCP_NODELAY: + return SocketOptionLevel.Tcp; + default: + throw new SocketException("unsupported socket option: " + opt); + } } private static int mapSocketOptionName(int opt) throws IOException { - switch (opt) - { - case SocketOptions.SO_BROADCAST: - return SocketOptionName.Broadcast; - case SocketOptions.SO_KEEPALIVE: - return SocketOptionName.KeepAlive; - case SocketOptions.SO_LINGER: - return SocketOptionName.Linger; - case SocketOptions.SO_OOBINLINE: - return SocketOptionName.OutOfBandInline; - case SocketOptions.SO_RCVBUF: - return SocketOptionName.ReceiveBuffer; - case SocketOptions.SO_SNDBUF: - return SocketOptionName.SendBuffer; - case SocketOptions.SO_REUSEADDR: - return SocketOptionName.ReuseAddress; - case SocketOptions.IP_MULTICAST_LOOP: - return SocketOptionName.MulticastLoopback; - case SocketOptions.IP_TOS: - return SocketOptionName.TypeOfService; - case SocketOptions.TCP_NODELAY: - return SocketOptionName.NoDelay; - default: - throw new SocketException("unsupported socket option: " + opt); - } + switch (opt) + { + case SocketOptions.SO_BROADCAST: + return SocketOptionName.Broadcast; + case SocketOptions.SO_KEEPALIVE: + return SocketOptionName.KeepAlive; + case SocketOptions.SO_LINGER: + return SocketOptionName.Linger; + case SocketOptions.SO_OOBINLINE: + return SocketOptionName.OutOfBandInline; + case SocketOptions.SO_RCVBUF: + return SocketOptionName.ReceiveBuffer; + case SocketOptions.SO_SNDBUF: + return SocketOptionName.SendBuffer; + case SocketOptions.SO_REUSEADDR: + return SocketOptionName.ReuseAddress; + case SocketOptions.IP_MULTICAST_LOOP: + return SocketOptionName.MulticastLoopback; + case SocketOptions.IP_TOS: + return SocketOptionName.TypeOfService; + case SocketOptions.TCP_NODELAY: + return SocketOptionName.NoDelay; + default: + throw new SocketException("unsupported socket option: " + opt); + } } static void setIntOption(FileDescriptor fd, int opt, int arg) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - int level = mapSocketOptionLevel(opt); - int name = mapSocketOptionName(opt); - fd.getSocket().SetSocketOption(SocketOptionLevel.wrap(level), SocketOptionName.wrap(name), arg); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + int level = mapSocketOptionLevel(opt); + int name = mapSocketOptionName(opt); + fd.getSocket().SetSocketOption(SocketOptionLevel.wrap(level), SocketOptionName.wrap(name), arg); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } static int getIntOption(FileDescriptor fd, int opt) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - int level = mapSocketOptionLevel(opt); - int name = mapSocketOptionName(opt); - Object obj = fd.getSocket().GetSocketOption(SocketOptionLevel.wrap(level), SocketOptionName.wrap(name)); - if (obj instanceof LingerOption) - { - LingerOption lo = (LingerOption)obj; - return lo.get_Enabled() ? lo.get_LingerTime() : -1; - } - return CIL.unbox_int(obj); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + int level = mapSocketOptionLevel(opt); + int name = mapSocketOptionName(opt); + Object obj = fd.getSocket().GetSocketOption(SocketOptionLevel.wrap(level), SocketOptionName.wrap(name)); + if (obj instanceof LingerOption) + { + LingerOption lo = (LingerOption)obj; + return lo.get_Enabled() ? lo.get_LingerTime() : -1; + } + return CIL.unbox_int(obj); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } private static int readImpl(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException { - if (length == 0) - { - return 0; - } - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - int read = fd.getSocket().Receive(buf, offset, length, SocketFlags.wrap(SocketFlags.None)); - return read == 0 ? IOStatus.EOF : read; - } - catch (cli.System.Net.Sockets.SocketException x) - { - if (x.get_ErrorCode() == PlainSocketImpl.WSAESHUTDOWN) - { - // the socket was shutdown, so we have to return EOF - return IOStatus.EOF; - } - else if (x.get_ErrorCode() == PlainSocketImpl.WSAEWOULDBLOCK) - { - // nothing to read and would block - return IOStatus.UNAVAILABLE; - } - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + if (length == 0) + { + return 0; + } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + int read = fd.getSocket().Receive(buf, offset, length, SocketFlags.wrap(SocketFlags.None)); + return read == 0 ? IOStatus.EOF : read; + } + catch (cli.System.Net.Sockets.SocketException x) + { + if (x.get_ErrorCode() == PlainSocketImpl.WSAESHUTDOWN) + { + // the socket was shutdown, so we have to return EOF + return IOStatus.EOF; + } + else if (x.get_ErrorCode() == PlainSocketImpl.WSAEWOULDBLOCK) + { + // nothing to read and would block + return IOStatus.UNAVAILABLE; + } + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } static int read(FileDescriptor fd, ByteBuffer dst) throws IOException { - if (dst.hasArray()) - { - byte[] buf = dst.array(); - int len = readImpl(fd, buf, dst.arrayOffset() + dst.position(), dst.remaining()); - if (len > 0) - { - dst.position(dst.position() + len); - } - return len; - } - else - { - byte[] buf = new byte[dst.remaining()]; - int len = readImpl(fd, buf, 0, buf.length); - if (len > 0) - { - dst.put(buf, 0, len); - } - return len; - } + if (dst.hasArray()) + { + byte[] buf = dst.array(); + int len = readImpl(fd, buf, dst.arrayOffset() + dst.position(), dst.remaining()); + if (len > 0) + { + dst.position(dst.position() + len); + } + return len; + } + else + { + byte[] buf = new byte[dst.remaining()]; + int len = readImpl(fd, buf, 0, buf.length); + if (len > 0) + { + dst.put(buf, 0, len); + } + return len; + } } static long read(FileDescriptor fd, ByteBuffer[] dsts) throws IOException { - long totalRead = 0; - for (int i = 0; i < dsts.length; i++) - { - int size = dsts[i].remaining(); - if (size > 0) - { - int read = read(fd, dsts[i]); - if (read < 0) - { - break; - } - totalRead += read; - if (read < size || safeGetAvailable(fd) == 0) - { - break; - } - } - } - return totalRead; + long totalRead = 0; + for (int i = 0; i < dsts.length; i++) + { + int size = dsts[i].remaining(); + if (size > 0) + { + int read = read(fd, dsts[i]); + if (read < 0) + { + break; + } + totalRead += read; + if (read < size || safeGetAvailable(fd) == 0) + { + break; + } + } + } + return totalRead; } private static int safeGetAvailable(FileDescriptor fd) { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - return fd.getSocket().get_Available(); - } - catch (cli.System.Net.Sockets.SocketException x) - { - } - catch (cli.System.ObjectDisposedException x1) - { - } - return 0; + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + return fd.getSocket().get_Available(); + } + catch (cli.System.Net.Sockets.SocketException x) + { + } + catch (cli.System.ObjectDisposedException x1) + { + } + return 0; } private static int writeImpl(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - return fd.getSocket().Send(buf, offset, length, SocketFlags.wrap(SocketFlags.None)); - } - catch (cli.System.Net.Sockets.SocketException x) - { - if (x.get_ErrorCode() == PlainSocketImpl.WSAEWOULDBLOCK) - { - return IOStatus.UNAVAILABLE; - } - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + return fd.getSocket().Send(buf, offset, length, SocketFlags.wrap(SocketFlags.None)); + } + catch (cli.System.Net.Sockets.SocketException x) + { + if (x.get_ErrorCode() == PlainSocketImpl.WSAEWOULDBLOCK) + { + return IOStatus.UNAVAILABLE; + } + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } static int write(FileDescriptor fd, ByteBuffer src) throws IOException { - if (src.hasArray()) - { - byte[] buf = src.array(); - int len = writeImpl(fd, buf, src.arrayOffset() + src.position(), src.remaining()); - if (len > 0) - { - src.position(src.position() + len); - } - return len; - } - else - { - int pos = src.position(); - byte[] buf = new byte[src.remaining()]; - src.get(buf); - int len = writeImpl(fd, buf, 0, buf.length); - if (len > 0) - { - src.position(pos + len); - } - return len; - } + if (src.hasArray()) + { + byte[] buf = src.array(); + int len = writeImpl(fd, buf, src.arrayOffset() + src.position(), src.remaining()); + if (len > 0) + { + src.position(src.position() + len); + } + return len; + } + else + { + int pos = src.position(); + byte[] buf = new byte[src.remaining()]; + src.get(buf); + int len = writeImpl(fd, buf, 0, buf.length); + if (len > 0) + { + src.position(pos + len); + } + return len; + } } static long write(FileDescriptor fd, ByteBuffer[] srcs) throws IOException { - long totalWritten = 0; - for (int i = 0; i < srcs.length; i++) - { - int size = srcs[i].remaining(); - if (size > 0) - { - int written = write(fd, srcs[i]); - if (written < 0) - { - break; - } - totalWritten += written; - if (written < size) - { - break; - } - } - } - return totalWritten; + long totalWritten = 0; + for (int i = 0; i < srcs.length; i++) + { + int size = srcs[i].remaining(); + if (size > 0) + { + int written = write(fd, srcs[i]); + if (written < 0) + { + break; + } + totalWritten += written; + if (written < size) + { + break; + } + } + } + return totalWritten; } // -- Miscellaneous utilities -- static InetSocketAddress checkAddress(SocketAddress sa) { - if (sa == null) - throw new IllegalArgumentException(); - if (!(sa instanceof InetSocketAddress)) - throw new UnsupportedAddressTypeException(); // ## needs arg - InetSocketAddress isa = (InetSocketAddress)sa; - if (isa.isUnresolved()) - throw new UnresolvedAddressException(); // ## needs arg - return isa; + if (sa == null) + throw new IllegalArgumentException(); + if (!(sa instanceof InetSocketAddress)) + throw new UnsupportedAddressTypeException(); // ## needs arg + InetSocketAddress isa = (InetSocketAddress)sa; + if (isa.isUnresolved()) + throw new UnresolvedAddressException(); // ## needs arg + return isa; } static InetSocketAddress asInetSocketAddress(SocketAddress sa) { - if (!(sa instanceof InetSocketAddress)) - throw new UnsupportedAddressTypeException(); - return (InetSocketAddress)sa; + if (!(sa instanceof InetSocketAddress)) + throw new UnsupportedAddressTypeException(); + return (InetSocketAddress)sa; } static void translateToSocketException(Exception x) - throws SocketException + throws SocketException { - if (x instanceof SocketException) - throw (SocketException)x; - Exception nx = x; - if (x instanceof ClosedChannelException) - nx = new SocketException("Socket is closed"); - else if (x instanceof AlreadyBoundException) - nx = new SocketException("Already bound"); - else if (x instanceof NotYetBoundException) - nx = new SocketException("Socket is not bound yet"); - else if (x instanceof UnsupportedAddressTypeException) - nx = new SocketException("Unsupported address type"); - else if (x instanceof UnresolvedAddressException) { - nx = new SocketException("Unresolved address"); - } - if (nx != x) - nx.initCause(x); + if (x instanceof SocketException) + throw (SocketException)x; + Exception nx = x; + if (x instanceof ClosedChannelException) + nx = new SocketException("Socket is closed"); + else if (x instanceof AlreadyBoundException) + nx = new SocketException("Already bound"); + else if (x instanceof NotYetBoundException) + nx = new SocketException("Socket is not bound yet"); + else if (x instanceof UnsupportedAddressTypeException) + nx = new SocketException("Unsupported address type"); + else if (x instanceof UnresolvedAddressException) { + nx = new SocketException("Unresolved address"); + } + if (nx != x) + nx.initCause(x); - if (nx instanceof SocketException) - throw (SocketException)nx; + if (nx instanceof SocketException) + throw (SocketException)nx; else if (nx instanceof RuntimeException) - throw (RuntimeException)nx; - else - throw new Error("Untranslated exception", nx); + throw (RuntimeException)nx; + else + throw new Error("Untranslated exception", nx); } static void translateException(Exception x, - boolean unknownHostForUnresolved) - throws IOException + boolean unknownHostForUnresolved) + throws IOException { - if (x instanceof IOException) - throw (IOException)x; + if (x instanceof IOException) + throw (IOException)x; // Throw UnknownHostException from here since it cannot // be thrown as a SocketException - if (unknownHostForUnresolved && + if (unknownHostForUnresolved && (x instanceof UnresolvedAddressException)) { throw new UnknownHostException(); } - translateToSocketException(x); + translateToSocketException(x); } static void translateException(Exception x) - throws IOException + throws IOException { - translateException(x, false); + translateException(x, false); } } diff --git a/openjdk/sun/nio/ch/SelectionKeyImpl.java b/openjdk/sun/nio/ch/SelectionKeyImpl.java index f67d23db..5edc3005 100644 --- a/openjdk/sun/nio/ch/SelectionKeyImpl.java +++ b/openjdk/sun/nio/ch/SelectionKeyImpl.java @@ -41,12 +41,12 @@ final class SelectionKeyImpl extends AbstractSelectionKey { this.channel = ch; this.selector = sel; - socket = ch.getFD().getSocket(); + socket = ch.getFD().getSocket(); } public SelectableChannel channel() { - return (SelectableChannel)channel; + return (SelectableChannel)channel; } public int readyOps() @@ -94,25 +94,25 @@ final class SelectionKeyImpl extends AbstractSelectionKey void nioReadyOps(int ops) { - readyOps = ops; + readyOps = ops; } int nioReadyOps() { - return readyOps; + return readyOps; } int nioInterestOps() { - return interestOps; + return interestOps; } SelectionKey nioInterestOps(int ops) { - if ((ops & ~channel().validOps()) != 0) - throw new IllegalArgumentException(); - channel.translateAndSetInterestOps(ops, this); - interestOps = ops; - return this; + if ((ops & ~channel().validOps()) != 0) + throw new IllegalArgumentException(); + channel.translateAndSetInterestOps(ops, this); + interestOps = ops; + return this; } } diff --git a/openjdk/sun/nio/ch/ServerSocketChannelImpl.java b/openjdk/sun/nio/ch/ServerSocketChannelImpl.java index 5c7555f0..7e94f03a 100644 --- a/openjdk/sun/nio/ch/ServerSocketChannelImpl.java +++ b/openjdk/sun/nio/ch/ServerSocketChannelImpl.java @@ -79,153 +79,153 @@ class ServerSocketChannelImpl public ServerSocketChannelImpl(SelectorProvider sp) throws IOException { - super(sp); - this.fd = Net.serverSocket(true); - this.state = ST_INUSE; + super(sp); + this.fd = Net.serverSocket(true); + this.state = ST_INUSE; } public ServerSocketChannelImpl(SelectorProvider sp, FileDescriptor fd) - throws IOException + throws IOException { - super(sp); - this.fd = fd; - this.state = ST_INUSE; - localAddress = Net.localAddress(fd); + super(sp); + this.fd = fd; + this.state = ST_INUSE; + localAddress = Net.localAddress(fd); } public ServerSocket socket() { - synchronized (stateLock) { - if (socket == null) - socket = ServerSocketAdaptor.create(this); - return socket; - } + synchronized (stateLock) { + if (socket == null) + socket = ServerSocketAdaptor.create(this); + return socket; + } } public boolean isBound() { - synchronized (stateLock) { - return localAddress != null; - } + synchronized (stateLock) { + return localAddress != null; + } } public SocketAddress localAddress() { - synchronized (stateLock) { - return localAddress; - } + synchronized (stateLock) { + return localAddress; + } } public void bind(SocketAddress local, int backlog) throws IOException { - synchronized (lock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (isBound()) - throw new AlreadyBoundException(); - InetSocketAddress isa = Net.checkAddress(local); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkListen(isa.getPort()); - Net.bind(fd, isa.getAddress(), isa.getPort()); - listen(fd, backlog < 1 ? 50 : backlog); - synchronized (stateLock) { - localAddress = Net.localAddress(fd); - } - } + synchronized (lock) { + if (!isOpen()) + throw new ClosedChannelException(); + if (isBound()) + throw new AlreadyBoundException(); + InetSocketAddress isa = Net.checkAddress(local); + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkListen(isa.getPort()); + Net.bind(fd, isa.getAddress(), isa.getPort()); + listen(fd, backlog < 1 ? 50 : backlog); + synchronized (stateLock) { + localAddress = Net.localAddress(fd); + } + } } public SocketChannel accept() throws IOException { - synchronized (lock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (!isBound()) - throw new NotYetBoundException(); - SocketChannel sc = null; - - int n = 0; - FileDescriptor newfd = new FileDescriptor(); - InetSocketAddress[] isaa = new InetSocketAddress[1]; - - try { - begin(); - if (!isOpen()) - return null; - thread = NativeThread.current(); - for (;;) { - n = accept0(this.fd, newfd, isaa); - if ((n == IOStatus.INTERRUPTED) && isOpen()) - continue; - break; - } - } finally { - thread = 0; - end(n > 0); - assert IOStatus.check(n); - } - - if (n < 1) - return null; - - IOUtil.configureBlocking(newfd, true); - InetSocketAddress isa = isaa[0]; - sc = new SocketChannelImpl(provider(), newfd, isa); - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - try { - sm.checkAccept(isa.getAddress().getHostAddress(), - isa.getPort()); - } catch (SecurityException x) { - sc.close(); - throw x; - } - } - return sc; - - } + synchronized (lock) { + if (!isOpen()) + throw new ClosedChannelException(); + if (!isBound()) + throw new NotYetBoundException(); + SocketChannel sc = null; + + int n = 0; + FileDescriptor newfd = new FileDescriptor(); + InetSocketAddress[] isaa = new InetSocketAddress[1]; + + try { + begin(); + if (!isOpen()) + return null; + thread = NativeThread.current(); + for (;;) { + n = accept0(this.fd, newfd, isaa); + if ((n == IOStatus.INTERRUPTED) && isOpen()) + continue; + break; + } + } finally { + thread = 0; + end(n > 0); + assert IOStatus.check(n); + } + + if (n < 1) + return null; + + IOUtil.configureBlocking(newfd, true); + InetSocketAddress isa = isaa[0]; + sc = new SocketChannelImpl(provider(), newfd, isa); + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + try { + sm.checkAccept(isa.getAddress().getHostAddress(), + isa.getPort()); + } catch (SecurityException x) { + sc.close(); + throw x; + } + } + return sc; + + } } protected void implConfigureBlocking(boolean block) throws IOException { - IOUtil.configureBlocking(fd, block); + IOUtil.configureBlocking(fd, block); } public SocketOpts options() { - synchronized (stateLock) { - if (options == null) { - SocketOptsImpl.Dispatcher d - = new SocketOptsImpl.Dispatcher() { - int getInt(int opt) throws IOException { - return Net.getIntOption(fd, opt); - } - void setInt(int opt, int arg) throws IOException { - Net.setIntOption(fd, opt, arg); - } - }; - options = new SocketOptsImpl.IP.TCP(d); - } - return options; - } + synchronized (stateLock) { + if (options == null) { + SocketOptsImpl.Dispatcher d + = new SocketOptsImpl.Dispatcher() { + int getInt(int opt) throws IOException { + return Net.getIntOption(fd, opt); + } + void setInt(int opt, int arg) throws IOException { + Net.setIntOption(fd, opt, arg); + } + }; + options = new SocketOptsImpl.IP.TCP(d); + } + return options; + } } protected void implCloseSelectableChannel() throws IOException { - synchronized (stateLock) { - closeImpl(); - long th = thread; - if (th != 0) - NativeThread.signal(th); - if (!isRegistered()) - kill(); - } + synchronized (stateLock) { + closeImpl(); + long th = thread; + if (th != 0) + NativeThread.signal(th); + if (!isRegistered()) + kill(); + } } public void kill() throws IOException { - synchronized (stateLock) { - if (state == ST_KILLED) - return; - if (state == ST_UNINITIALIZED) { + synchronized (stateLock) { + if (state == ST_KILLED) + return; + if (state == ST_UNINITIALIZED) { state = ST_KILLED; - return; + return; } - assert !isOpen() && !isRegistered(); - closeImpl(); - state = ST_KILLED; - } + assert !isOpen() && !isRegistered(); + closeImpl(); + state = ST_KILLED; + } } /** @@ -238,11 +238,11 @@ class ServerSocketChannelImpl int newOps = initialOps; if ((ops & PollArrayWrapper.POLLNVAL) != 0) { - // This should only happen if this channel is pre-closed while a - // selection operation is in progress - // ## Throw an error if this channel has not been pre-closed - return false; - } + // This should only happen if this channel is pre-closed while a + // selection operation is in progress + // ## Throw an error if this channel has not been pre-closed + return false; + } if ((ops & (PollArrayWrapper.POLLERR | PollArrayWrapper.POLLHUP)) != 0) { @@ -281,50 +281,50 @@ class ServerSocketChannelImpl } public FileDescriptor getFD() { - return fd; + return fd; } public int getFDVal() { - throw new Error(); + throw new Error(); } public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append(this.getClass().getName()); - sb.append('['); - if (!isOpen()) - sb.append("closed"); - else { - synchronized (stateLock) { - if (localAddress() == null) { - sb.append("unbound"); - } else { - sb.append(localAddress().toString()); - } - } - } - sb.append(']'); - return sb.toString(); + StringBuffer sb = new StringBuffer(); + sb.append(this.getClass().getName()); + sb.append('['); + if (!isOpen()) + sb.append("closed"); + else { + synchronized (stateLock) { + if (localAddress() == null) { + sb.append("unbound"); + } else { + sb.append(localAddress().toString()); + } + } + } + sb.append(']'); + return sb.toString(); } // -- Native methods -- private static void listen(FileDescriptor fd, int backlog) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().Listen(backlog); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException _) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fd.getSocket().Listen(backlog); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException _) + { + throw new SocketException("Socket is closed"); + } } // Accepts a new connection, setting the given file descriptor to refer to @@ -334,49 +334,49 @@ class ServerSocketChannelImpl // private static int accept0(FileDescriptor ssfd, FileDescriptor newfd, InetSocketAddress[] isaa) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - cli.System.Net.Sockets.Socket netSocket = ssfd.getSocket(); - if (netSocket.get_Blocking() || netSocket.Poll(0, cli.System.Net.Sockets.SelectMode.wrap(cli.System.Net.Sockets.SelectMode.SelectRead))) - { - cli.System.Net.Sockets.Socket accsock = netSocket.Accept(); - newfd.setSocket(accsock); - cli.System.Net.IPEndPoint ep = (cli.System.Net.IPEndPoint)accsock.get_RemoteEndPoint(); - isaa[0] = new InetSocketAddress(PlainSocketImpl.getInetAddressFromIPEndPoint(ep), ep.get_Port()); - return 1; - } - else - { - return IOStatus.UNAVAILABLE; - } - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException _) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + cli.System.Net.Sockets.Socket netSocket = ssfd.getSocket(); + if (netSocket.get_Blocking() || netSocket.Poll(0, cli.System.Net.Sockets.SelectMode.wrap(cli.System.Net.Sockets.SelectMode.SelectRead))) + { + cli.System.Net.Sockets.Socket accsock = netSocket.Accept(); + newfd.setSocket(accsock); + cli.System.Net.IPEndPoint ep = (cli.System.Net.IPEndPoint)accsock.get_RemoteEndPoint(); + isaa[0] = new InetSocketAddress(PlainSocketImpl.getInetAddressFromIPEndPoint(ep), ep.get_Port()); + return 1; + } + else + { + return IOStatus.UNAVAILABLE; + } + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException _) + { + throw new SocketException("Socket is closed"); + } } private void closeImpl() throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().Close(); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fd.getSocket().Close(); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } } diff --git a/openjdk/sun/nio/ch/SocketChannelImpl.java b/openjdk/sun/nio/ch/SocketChannelImpl.java index 2140150b..baa6b902 100644 --- a/openjdk/sun/nio/ch/SocketChannelImpl.java +++ b/openjdk/sun/nio/ch/SocketChannelImpl.java @@ -91,138 +91,138 @@ class SocketChannelImpl // Constructor for normal connecting sockets // SocketChannelImpl(SelectorProvider sp) throws IOException { - super(sp); - this.fd = Net.socket(true); - this.state = ST_UNCONNECTED; + super(sp); + this.fd = Net.socket(true); + this.state = ST_UNCONNECTED; } // Constructor for sockets obtained from server sockets // SocketChannelImpl(SelectorProvider sp, - FileDescriptor fd, InetSocketAddress remote) - throws IOException + FileDescriptor fd, InetSocketAddress remote) + throws IOException { - super(sp); - this.fd = fd; - this.state = ST_CONNECTED; - this.remoteAddress = remote; + super(sp); + this.fd = fd; + this.state = ST_CONNECTED; + this.remoteAddress = remote; } public Socket socket() { - synchronized (stateLock) { - if (socket == null) - socket = SocketAdaptor.create(this); - return socket; - } + synchronized (stateLock) { + if (socket == null) + socket = SocketAdaptor.create(this); + return socket; + } } private boolean ensureReadOpen() throws ClosedChannelException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (!isConnected()) - throw new NotYetConnectedException(); - if (!isInputOpen) - return false; - else - return true; - } + synchronized (stateLock) { + if (!isOpen()) + throw new ClosedChannelException(); + if (!isConnected()) + throw new NotYetConnectedException(); + if (!isInputOpen) + return false; + else + return true; + } } private void ensureWriteOpen() throws ClosedChannelException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (!isOutputOpen) - throw new ClosedChannelException(); - if (!isConnected()) - throw new NotYetConnectedException(); - } + synchronized (stateLock) { + if (!isOpen()) + throw new ClosedChannelException(); + if (!isOutputOpen) + throw new ClosedChannelException(); + if (!isConnected()) + throw new NotYetConnectedException(); + } } private void readerCleanup() throws IOException { - synchronized (stateLock) { + synchronized (stateLock) { readerThread = 0; - if (state == ST_KILLPENDING) + if (state == ST_KILLPENDING) kill(); - } + } } private void writerCleanup() throws IOException { - synchronized (stateLock) { + synchronized (stateLock) { writerThread = 0; - if (state == ST_KILLPENDING) + if (state == ST_KILLPENDING) kill(); - } + } } public int read(ByteBuffer buf) throws IOException { - if (buf == null) - throw new NullPointerException(); + if (buf == null) + throw new NullPointerException(); - synchronized (readLock) { + synchronized (readLock) { if (!ensureReadOpen()) return -1; - int n = 0; - try { + int n = 0; + try { - // Set up the interruption machinery; see - // AbstractInterruptibleChannel for details - // - begin(); + // Set up the interruption machinery; see + // AbstractInterruptibleChannel for details + // + begin(); - synchronized (stateLock) { + synchronized (stateLock) { if (!isOpen()) { - // Either the current thread is already interrupted, so - // begin() closed the channel, or another thread closed the - // channel since we checked it a few bytecodes ago. In - // either case the value returned here is irrelevant since - // the invocation of end() in the finally block will throw - // an appropriate exception. - // - return 0; - - } - - // Save this thread so that it can be signalled on those - // platforms that require it - // - readerThread = NativeThread.current(); - } - - // Between the previous test of isOpen() and the return of the - // IOUtil.read invocation below, this channel might be closed - // or this thread might be interrupted. We rely upon the - // implicit synchronization point in the kernel read() call to - // make sure that the right thing happens. In either case the - // implCloseSelectableChannel method is ultimately invoked in - // some other thread, so there are three possibilities: - // - // - implCloseSelectableChannel() invokes nd.preClose() - // before this thread invokes read(), in which case the - // read returns immediately with either EOF or an error, - // the latter of which will cause an IOException to be - // thrown. - // - // - implCloseSelectableChannel() invokes nd.preClose() after - // this thread is blocked in read(). On some operating - // systems (e.g., Solaris and Windows) this causes the read - // to return immediately with either EOF or an error - // indication. - // - // - implCloseSelectableChannel() invokes nd.preClose() after - // this thread is blocked in read() but the operating - // system (e.g., Linux) doesn't support preemptive close, - // so implCloseSelectableChannel() proceeds to signal this - // thread, thereby causing the read to return immediately - // with IOStatus.INTERRUPTED. - // - // In all three cases the invocation of end() in the finally - // clause will notice that the channel has been closed and - // throw an appropriate exception (AsynchronousCloseException - // or ClosedByInterruptException) if necessary. - // + // Either the current thread is already interrupted, so + // begin() closed the channel, or another thread closed the + // channel since we checked it a few bytecodes ago. In + // either case the value returned here is irrelevant since + // the invocation of end() in the finally block will throw + // an appropriate exception. + // + return 0; + + } + + // Save this thread so that it can be signalled on those + // platforms that require it + // + readerThread = NativeThread.current(); + } + + // Between the previous test of isOpen() and the return of the + // IOUtil.read invocation below, this channel might be closed + // or this thread might be interrupted. We rely upon the + // implicit synchronization point in the kernel read() call to + // make sure that the right thing happens. In either case the + // implCloseSelectableChannel method is ultimately invoked in + // some other thread, so there are three possibilities: + // + // - implCloseSelectableChannel() invokes nd.preClose() + // before this thread invokes read(), in which case the + // read returns immediately with either EOF or an error, + // the latter of which will cause an IOException to be + // thrown. + // + // - implCloseSelectableChannel() invokes nd.preClose() after + // this thread is blocked in read(). On some operating + // systems (e.g., Solaris and Windows) this causes the read + // to return immediately with either EOF or an error + // indication. + // + // - implCloseSelectableChannel() invokes nd.preClose() after + // this thread is blocked in read() but the operating + // system (e.g., Linux) doesn't support preemptive close, + // so implCloseSelectableChannel() proceeds to signal this + // thread, thereby causing the read to return immediately + // with IOStatus.INTERRUPTED. + // + // In all three cases the invocation of end() in the finally + // clause will notice that the channel has been closed and + // throw an appropriate exception (AsynchronousCloseException + // or ClosedByInterruptException) if necessary. + // // *There is A fourth possibility. implCloseSelectableChannel() // invokes nd.preClose(), signals reader/writer thred and quickly // moves on to nd.close() in kill(), which does a real close. @@ -234,261 +234,261 @@ class SocketChannelImpl // writer thread(s) over there "waiting", leave the cleanup/kill // to the reader or writer thread. (the preClose() still happens // so the connection gets cut off as usual). - // - // For socket channels there is the additional wrinkle that - // asynchronous shutdown works much like asynchronous close, - // except that the channel is shutdown rather than completely - // closed. This is analogous to the first two cases above, - // except that the shutdown operation plays the role of - // nd.preClose(). - for (;;) { - n = Net.read(fd, buf); - if ((n == IOStatus.INTERRUPTED) && isOpen()) { - // The system call was interrupted but the channel - // is still open, so retry - continue; - } - return IOStatus.normalize(n); - } - - } finally { - readerCleanup(); // Clear reader thread - // The end method, which is defined in our superclass - // AbstractInterruptibleChannel, resets the interruption - // machinery. If its argument is true then it returns - // normally; otherwise it checks the interrupt and open state - // of this channel and throws an appropriate exception if - // necessary. - // - // So, if we actually managed to do any I/O in the above try - // block then we pass true to the end method. We also pass - // true if the channel was in non-blocking mode when the I/O - // operation was initiated but no data could be transferred; - // this prevents spurious exceptions from being thrown in the - // rare event that a channel is closed or a thread is - // interrupted at the exact moment that a non-blocking I/O - // request is made. - // - end(n > 0 || (n == IOStatus.UNAVAILABLE)); - - // Extra case for socket channels: Asynchronous shutdown - // - synchronized (stateLock) { - if ((n <= 0) && (!isInputOpen)) - return IOStatus.EOF; - } - - assert IOStatus.check(n); - - } - } + // + // For socket channels there is the additional wrinkle that + // asynchronous shutdown works much like asynchronous close, + // except that the channel is shutdown rather than completely + // closed. This is analogous to the first two cases above, + // except that the shutdown operation plays the role of + // nd.preClose(). + for (;;) { + n = Net.read(fd, buf); + if ((n == IOStatus.INTERRUPTED) && isOpen()) { + // The system call was interrupted but the channel + // is still open, so retry + continue; + } + return IOStatus.normalize(n); + } + + } finally { + readerCleanup(); // Clear reader thread + // The end method, which is defined in our superclass + // AbstractInterruptibleChannel, resets the interruption + // machinery. If its argument is true then it returns + // normally; otherwise it checks the interrupt and open state + // of this channel and throws an appropriate exception if + // necessary. + // + // So, if we actually managed to do any I/O in the above try + // block then we pass true to the end method. We also pass + // true if the channel was in non-blocking mode when the I/O + // operation was initiated but no data could be transferred; + // this prevents spurious exceptions from being thrown in the + // rare event that a channel is closed or a thread is + // interrupted at the exact moment that a non-blocking I/O + // request is made. + // + end(n > 0 || (n == IOStatus.UNAVAILABLE)); + + // Extra case for socket channels: Asynchronous shutdown + // + synchronized (stateLock) { + if ((n <= 0) && (!isInputOpen)) + return IOStatus.EOF; + } + + assert IOStatus.check(n); + + } + } } private long read0(ByteBuffer[] bufs) throws IOException { if (bufs == null) throw new NullPointerException(); - synchronized (readLock) { + synchronized (readLock) { if (!ensureReadOpen()) return -1; - long n = 0; - try { - begin(); - synchronized (stateLock) { - if (!isOpen()) - return 0; - readerThread = NativeThread.current(); + long n = 0; + try { + begin(); + synchronized (stateLock) { + if (!isOpen()) + return 0; + readerThread = NativeThread.current(); } - for (;;) { - n = Net.read(fd, bufs); - if ((n == IOStatus.INTERRUPTED) && isOpen()) - continue; - return IOStatus.normalize(n); - } - } finally { + for (;;) { + n = Net.read(fd, bufs); + if ((n == IOStatus.INTERRUPTED) && isOpen()) + continue; + return IOStatus.normalize(n); + } + } finally { readerCleanup(); - end(n > 0 || (n == IOStatus.UNAVAILABLE)); - synchronized (stateLock) { - if ((n <= 0) && (!isInputOpen)) - return IOStatus.EOF; - } - assert IOStatus.check(n); - } - } + end(n > 0 || (n == IOStatus.UNAVAILABLE)); + synchronized (stateLock) { + if ((n <= 0) && (!isInputOpen)) + return IOStatus.EOF; + } + assert IOStatus.check(n); + } + } } public long read(ByteBuffer[] dsts, int offset, int length) - throws IOException + throws IOException { if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) throw new IndexOutOfBoundsException(); - // ## Fix IOUtil.write so that we can avoid this array copy - return read0(Util.subsequence(dsts, offset, length)); + // ## Fix IOUtil.write so that we can avoid this array copy + return read0(Util.subsequence(dsts, offset, length)); } public int write(ByteBuffer buf) throws IOException { if (buf == null) throw new NullPointerException(); - synchronized (writeLock) { + synchronized (writeLock) { ensureWriteOpen(); - int n = 0; - try { - begin(); - synchronized (stateLock) { - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - } - for (;;) { - n = Net.write(fd, buf); - if ((n == IOStatus.INTERRUPTED) && isOpen()) - continue; - return IOStatus.normalize(n); - } - } finally { - writerCleanup(); - end(n > 0 || (n == IOStatus.UNAVAILABLE)); - synchronized (stateLock) { - if ((n <= 0) && (!isOutputOpen)) - throw new AsynchronousCloseException(); - } - assert IOStatus.check(n); - } - } + int n = 0; + try { + begin(); + synchronized (stateLock) { + if (!isOpen()) + return 0; + writerThread = NativeThread.current(); + } + for (;;) { + n = Net.write(fd, buf); + if ((n == IOStatus.INTERRUPTED) && isOpen()) + continue; + return IOStatus.normalize(n); + } + } finally { + writerCleanup(); + end(n > 0 || (n == IOStatus.UNAVAILABLE)); + synchronized (stateLock) { + if ((n <= 0) && (!isOutputOpen)) + throw new AsynchronousCloseException(); + } + assert IOStatus.check(n); + } + } } public long write0(ByteBuffer[] bufs) throws IOException { if (bufs == null) throw new NullPointerException(); - synchronized (writeLock) { + synchronized (writeLock) { ensureWriteOpen(); - long n = 0; - try { - begin(); - synchronized (stateLock) { - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - } - for (;;) { - n = Net.write(fd, bufs); - if ((n == IOStatus.INTERRUPTED) && isOpen()) - continue; - return IOStatus.normalize(n); - } - } finally { - writerCleanup(); - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - synchronized (stateLock) { - if ((n <= 0) && (!isOutputOpen)) - throw new AsynchronousCloseException(); - } - assert IOStatus.check(n); - } - } + long n = 0; + try { + begin(); + synchronized (stateLock) { + if (!isOpen()) + return 0; + writerThread = NativeThread.current(); + } + for (;;) { + n = Net.write(fd, bufs); + if ((n == IOStatus.INTERRUPTED) && isOpen()) + continue; + return IOStatus.normalize(n); + } + } finally { + writerCleanup(); + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + synchronized (stateLock) { + if ((n <= 0) && (!isOutputOpen)) + throw new AsynchronousCloseException(); + } + assert IOStatus.check(n); + } + } } public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException + throws IOException { if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) throw new IndexOutOfBoundsException(); - // ## Fix IOUtil.write so that we can avoid this array copy - return write0(Util.subsequence(srcs, offset, length)); + // ## Fix IOUtil.write so that we can avoid this array copy + return write0(Util.subsequence(srcs, offset, length)); } protected void implConfigureBlocking(boolean block) throws IOException { - IOUtil.configureBlocking(fd, block); + IOUtil.configureBlocking(fd, block); } public SocketOpts options() { - synchronized (stateLock) { - if (options == null) { - SocketOptsImpl.Dispatcher d - = new SocketOptsImpl.Dispatcher() { - int getInt(int opt) throws IOException { - return Net.getIntOption(fd, opt); - } - void setInt(int opt, int arg) - throws IOException - { - Net.setIntOption(fd, opt, arg); - } - }; - options = new SocketOptsImpl.IP.TCP(d); - } - return options; - } + synchronized (stateLock) { + if (options == null) { + SocketOptsImpl.Dispatcher d + = new SocketOptsImpl.Dispatcher() { + int getInt(int opt) throws IOException { + return Net.getIntOption(fd, opt); + } + void setInt(int opt, int arg) + throws IOException + { + Net.setIntOption(fd, opt, arg); + } + }; + options = new SocketOptsImpl.IP.TCP(d); + } + return options; + } } public boolean isBound() { - synchronized (stateLock) { + synchronized (stateLock) { if (state == ST_CONNECTED) return true; - return localAddress != null; - } + return localAddress != null; + } } public SocketAddress localAddress() { - synchronized (stateLock) { - if (state == ST_CONNECTED && - (localAddress == null || - ((InetSocketAddress)localAddress).getAddress().isAnyLocalAddress())) { - // Socket was not bound before connecting or - // Socket was bound with an "anyLocalAddress" - localAddress = Net.localAddress(fd); - } - return localAddress; - } + synchronized (stateLock) { + if (state == ST_CONNECTED && + (localAddress == null || + ((InetSocketAddress)localAddress).getAddress().isAnyLocalAddress())) { + // Socket was not bound before connecting or + // Socket was bound with an "anyLocalAddress" + localAddress = Net.localAddress(fd); + } + return localAddress; + } } public SocketAddress remoteAddress() { - synchronized (stateLock) { - return remoteAddress; - } + synchronized (stateLock) { + return remoteAddress; + } } public void bind(SocketAddress local) throws IOException { - synchronized (readLock) { - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpenAndUnconnected(); - if (localAddress != null) - throw new AlreadyBoundException(); - InetSocketAddress isa = Net.checkAddress(local); - Net.bind(fd, isa.getAddress(), isa.getPort()); - localAddress = Net.localAddress(fd); - } - } - } + synchronized (readLock) { + synchronized (writeLock) { + synchronized (stateLock) { + ensureOpenAndUnconnected(); + if (localAddress != null) + throw new AlreadyBoundException(); + InetSocketAddress isa = Net.checkAddress(local); + Net.bind(fd, isa.getAddress(), isa.getPort()); + localAddress = Net.localAddress(fd); + } + } + } } public boolean isConnected() { - synchronized (stateLock) { - return (state == ST_CONNECTED); - } + synchronized (stateLock) { + return (state == ST_CONNECTED); + } } public boolean isConnectionPending() { - synchronized (stateLock) { - return (state == ST_PENDING); - } + synchronized (stateLock) { + return (state == ST_PENDING); + } } void ensureOpenAndUnconnected() throws IOException { // package-private - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (state == ST_CONNECTED) - throw new AlreadyConnectedException(); - if (state == ST_PENDING) - throw new ConnectionPendingException(); - } + synchronized (stateLock) { + if (!isOpen()) + throw new ClosedChannelException(); + if (state == ST_CONNECTED) + throw new AlreadyConnectedException(); + if (state == ST_PENDING) + throw new ConnectionPendingException(); + } } public boolean connect(SocketAddress sa) throws IOException { - int trafficClass = 0; // ## Pick up from options - int localPort = 0; + int trafficClass = 0; // ## Pick up from options + int localPort = 0; synchronized (readLock) { synchronized (writeLock) { @@ -499,56 +499,56 @@ class SocketChannelImpl sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); synchronized (blockingLock()) { - int n = 0; - try { - try { - begin(); - synchronized (stateLock) { - if (!isOpen()) { - return false; - } - readerThread = NativeThread.current(); - } - for (;;) { - InetAddress ia = isa.getAddress(); - if (ia.isAnyLocalAddress()) - ia = InetAddress.getLocalHost(); - n = connectImpl(ia, - isa.getPort(), - trafficClass); - if ( (n == IOStatus.INTERRUPTED) - && isOpen()) - continue; - break; - } - } finally { + int n = 0; + try { + try { + begin(); + synchronized (stateLock) { + if (!isOpen()) { + return false; + } + readerThread = NativeThread.current(); + } + for (;;) { + InetAddress ia = isa.getAddress(); + if (ia.isAnyLocalAddress()) + ia = InetAddress.getLocalHost(); + n = connectImpl(ia, + isa.getPort(), + trafficClass); + if ( (n == IOStatus.INTERRUPTED) + && isOpen()) + continue; + break; + } + } finally { readerCleanup(); - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } catch (IOException x) { - // If an exception was thrown, close the channel after - // invoking end() so as to avoid bogus - // AsynchronousCloseExceptions - close(); - throw x; - } - synchronized (stateLock) { - remoteAddress = isa; - if (n > 0) { - - // Connection succeeded; disallow further - // invocation + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } catch (IOException x) { + // If an exception was thrown, close the channel after + // invoking end() so as to avoid bogus + // AsynchronousCloseExceptions + close(); + throw x; + } + synchronized (stateLock) { + remoteAddress = isa; + if (n > 0) { + + // Connection succeeded; disallow further + // invocation state = ST_CONNECTED; - return true; - } - // If nonblocking and no exception then connection - // pending; disallow another invocation - if (!isBlocking()) - state = ST_PENDING; - else - assert false; - } + return true; + } + // If nonblocking and no exception then connection + // pending; disallow another invocation + if (!isBlocking()) + state = ST_PENDING; + else + assert false; + } } return false; } @@ -558,54 +558,54 @@ class SocketChannelImpl public boolean finishConnect() throws IOException { synchronized (readLock) { synchronized (writeLock) { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - if (state == ST_CONNECTED) - return true; - if (state != ST_PENDING) - throw new NoConnectionPendingException(); - } - int n = 0; - try { - try { - begin(); - synchronized (blockingLock()) { - synchronized (stateLock) { - if (!isOpen()) { - return false; - } - readerThread = NativeThread.current(); - } - if (!isBlocking()) { - for (;;) { - n = checkConnect(fd, false, - readyToConnect); - if ( (n == IOStatus.INTERRUPTED) - && isOpen()) - continue; - break; - } - } else { - for (;;) { - n = checkConnect(fd, true, - readyToConnect); - if (n == 0) { - // Loop in case of - // spurious notifications - continue; - } - if ( (n == IOStatus.INTERRUPTED) - && isOpen()) - continue; - break; - } - } - } - } finally { - synchronized (stateLock) { - readerThread = 0; - if (state == ST_KILLPENDING) { + synchronized (stateLock) { + if (!isOpen()) + throw new ClosedChannelException(); + if (state == ST_CONNECTED) + return true; + if (state != ST_PENDING) + throw new NoConnectionPendingException(); + } + int n = 0; + try { + try { + begin(); + synchronized (blockingLock()) { + synchronized (stateLock) { + if (!isOpen()) { + return false; + } + readerThread = NativeThread.current(); + } + if (!isBlocking()) { + for (;;) { + n = checkConnect(fd, false, + readyToConnect); + if ( (n == IOStatus.INTERRUPTED) + && isOpen()) + continue; + break; + } + } else { + for (;;) { + n = checkConnect(fd, true, + readyToConnect); + if (n == 0) { + // Loop in case of + // spurious notifications + continue; + } + if ( (n == IOStatus.INTERRUPTED) + && isOpen()) + continue; + break; + } + } + } + } finally { + synchronized (stateLock) { + readerThread = 0; + if (state == ST_KILLPENDING) { kill(); // poll()/getsockopt() does not report // error (throws exception, with n = 0) @@ -614,21 +614,21 @@ class SocketChannelImpl // end() can throw appropriate exception n = 0; } - } - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } catch (IOException x) { - // If an exception was thrown, close the channel after - // invoking end() so as to avoid bogus - // AsynchronousCloseExceptions + } + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + assert IOStatus.check(n); + } + } catch (IOException x) { + // If an exception was thrown, close the channel after + // invoking end() so as to avoid bogus + // AsynchronousCloseExceptions close(); throw x; - } + } if (n > 0) { - synchronized (stateLock) { - state = ST_CONNECTED; - } + synchronized (stateLock) { + state = ST_CONNECTED; + } return true; } return false; @@ -641,37 +641,37 @@ class SocketChannelImpl public final static int SHUT_RDWR = 2; public void shutdownInput() throws IOException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - isInputOpen = false; - shutdown(fd, SHUT_RD); - if (readerThread != 0) - NativeThread.signal(readerThread); - } + synchronized (stateLock) { + if (!isOpen()) + throw new ClosedChannelException(); + isInputOpen = false; + shutdown(fd, SHUT_RD); + if (readerThread != 0) + NativeThread.signal(readerThread); + } } public void shutdownOutput() throws IOException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - isOutputOpen = false; - shutdown(fd, SHUT_WR); - if (writerThread != 0) - NativeThread.signal(writerThread); - } + synchronized (stateLock) { + if (!isOpen()) + throw new ClosedChannelException(); + isOutputOpen = false; + shutdown(fd, SHUT_WR); + if (writerThread != 0) + NativeThread.signal(writerThread); + } } public boolean isInputOpen() { - synchronized (stateLock) { - return isInputOpen; - } + synchronized (stateLock) { + return isInputOpen; + } } public boolean isOutputOpen() { - synchronized (stateLock) { - return isOutputOpen; - } + synchronized (stateLock) { + return isOutputOpen; + } } // AbstractInterruptibleChannel synchronizes invocations of this method @@ -680,57 +680,57 @@ class SocketChannelImpl // (which is volatile) will have been set to false. // protected void implCloseSelectableChannel() throws IOException { - synchronized (stateLock) { - isInputOpen = false; - isOutputOpen = false; - - closeImpl(); - - // Signal native threads, if needed. If a target thread is not - // currently blocked in an I/O operation then no harm is done since - // the signal handler doesn't actually do anything. - // - if (readerThread != 0) - NativeThread.signal(readerThread); - - if (writerThread != 0) - NativeThread.signal(writerThread); - - // If this channel is not registered then it's safe to close the fd - // immediately since we know at this point that no thread is - // blocked in an I/O operation upon the channel and, since the - // channel is marked closed, no thread will start another such - // operation. If this channel is registered then we don't close - // the fd since it might be in use by a selector. In that case - // closing this channel caused its keys to be cancelled, so the - // last selector to deregister a key for this channel will invoke - // kill() to close the fd. - // - if (!isRegistered()) - kill(); - } + synchronized (stateLock) { + isInputOpen = false; + isOutputOpen = false; + + closeImpl(); + + // Signal native threads, if needed. If a target thread is not + // currently blocked in an I/O operation then no harm is done since + // the signal handler doesn't actually do anything. + // + if (readerThread != 0) + NativeThread.signal(readerThread); + + if (writerThread != 0) + NativeThread.signal(writerThread); + + // If this channel is not registered then it's safe to close the fd + // immediately since we know at this point that no thread is + // blocked in an I/O operation upon the channel and, since the + // channel is marked closed, no thread will start another such + // operation. If this channel is registered then we don't close + // the fd since it might be in use by a selector. In that case + // closing this channel caused its keys to be cancelled, so the + // last selector to deregister a key for this channel will invoke + // kill() to close the fd. + // + if (!isRegistered()) + kill(); + } } public void kill() throws IOException { - synchronized (stateLock) { - if (state == ST_KILLED) - return; - if (state == ST_UNINITIALIZED) { + synchronized (stateLock) { + if (state == ST_KILLED) + return; + if (state == ST_UNINITIALIZED) { state = ST_KILLED; - return; + return; } - assert !isOpen() && !isRegistered(); + assert !isOpen() && !isRegistered(); // Postpone the kill if there is a waiting reader // or writer thread. See the comments in read() for // more detailed explanation. - if (readerThread == 0 && writerThread == 0) { + if (readerThread == 0 && writerThread == 0) { closeImpl(); - state = ST_KILLED; + state = ST_KILLED; } else { - state = ST_KILLPENDING; + state = ST_KILLPENDING; } - } + } } /** @@ -743,11 +743,11 @@ class SocketChannelImpl int newOps = initialOps; if ((ops & PollArrayWrapper.POLLNVAL) != 0) { - // This should only happen if this channel is pre-closed while a - // selection operation is in progress - // ## Throw an error if this channel has not been pre-closed - return false; - } + // This should only happen if this channel is pre-closed while a + // selection operation is in progress + // ## Throw an error if this channel has not been pre-closed + return false; + } if ((ops & (PollArrayWrapper.POLLERR | PollArrayWrapper.POLLHUP)) != 0) { @@ -803,48 +803,48 @@ class SocketChannelImpl } public FileDescriptor getFD() { - return fd; + return fd; } public int getFDVal() { - throw new Error(); + throw new Error(); } public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append(this.getClass().getSuperclass().getName()); - sb.append('['); - if (!isOpen()) - sb.append("closed"); - else { - synchronized (stateLock) { - switch (state) { - case ST_UNCONNECTED: - sb.append("unconnected"); - break; - case ST_PENDING: - sb.append("connection-pending"); - break; - case ST_CONNECTED: - sb.append("connected"); - if (!isInputOpen) - sb.append(" ishut"); - if (!isOutputOpen) - sb.append(" oshut"); - break; - } - if (localAddress() != null) { - sb.append(" local="); - sb.append(localAddress().toString()); - } - if (remoteAddress() != null) { - sb.append(" remote="); - sb.append(remoteAddress().toString()); - } - } - } - sb.append(']'); - return sb.toString(); + StringBuffer sb = new StringBuffer(); + sb.append(this.getClass().getSuperclass().getName()); + sb.append('['); + if (!isOpen()) + sb.append("closed"); + else { + synchronized (stateLock) { + switch (state) { + case ST_UNCONNECTED: + sb.append("unconnected"); + break; + case ST_PENDING: + sb.append("connection-pending"); + break; + case ST_CONNECTED: + sb.append("connected"); + if (!isInputOpen) + sb.append(" ishut"); + if (!isOutputOpen) + sb.append(" oshut"); + break; + } + if (localAddress() != null) { + sb.append(" local="); + sb.append(localAddress().toString()); + } + if (remoteAddress() != null) { + sb.append(" remote="); + sb.append(remoteAddress().toString()); + } + } + } + sb.append(']'); + return sb.toString(); } @@ -852,96 +852,96 @@ class SocketChannelImpl private int connectImpl(InetAddress remote, int remotePort, int trafficClass) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - cli.System.Net.IPEndPoint ep = new cli.System.Net.IPEndPoint(PlainSocketImpl.getAddressFromInetAddress(remote), remotePort); - if (isBlocking()) - { - fd.getSocket().Connect(ep); - return 1; - } - else - { - asyncConnect = fd.getSocket().BeginConnect(ep, null, null); - return IOStatus.UNAVAILABLE; - } - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw new ConnectException(x.getMessage()); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + cli.System.Net.IPEndPoint ep = new cli.System.Net.IPEndPoint(PlainSocketImpl.getAddressFromInetAddress(remote), remotePort); + if (isBlocking()) + { + fd.getSocket().Connect(ep); + return 1; + } + else + { + asyncConnect = fd.getSocket().BeginConnect(ep, null, null); + return IOStatus.UNAVAILABLE; + } + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw new ConnectException(x.getMessage()); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } private int checkConnect(FileDescriptor fd, boolean block, boolean ready) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - if (block || ready || asyncConnect.get_IsCompleted()) - { - cli.System.IAsyncResult res = asyncConnect; - asyncConnect = null; - fd.getSocket().EndConnect(res); - // work around for blocking issue - fd.getSocket().set_Blocking(isBlocking()); - return 1; - } - else - { - return IOStatus.UNAVAILABLE; - } - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw new ConnectException(x.getMessage()); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + if (block || ready || asyncConnect.get_IsCompleted()) + { + cli.System.IAsyncResult res = asyncConnect; + asyncConnect = null; + fd.getSocket().EndConnect(res); + // work around for blocking issue + fd.getSocket().set_Blocking(isBlocking()); + return 1; + } + else + { + return IOStatus.UNAVAILABLE; + } + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw new ConnectException(x.getMessage()); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } private static void shutdown(FileDescriptor fd, int how) throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().Shutdown(cli.System.Net.Sockets.SocketShutdown.wrap(how == SHUT_RD ? cli.System.Net.Sockets.SocketShutdown.Receive : cli.System.Net.Sockets.SocketShutdown.Send)); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fd.getSocket().Shutdown(cli.System.Net.Sockets.SocketShutdown.wrap(how == SHUT_RD ? cli.System.Net.Sockets.SocketShutdown.Receive : cli.System.Net.Sockets.SocketShutdown.Send)); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } private void closeImpl() throws IOException { - try - { - if (false) throw new cli.System.Net.Sockets.SocketException(); - if (false) throw new cli.System.ObjectDisposedException(""); - fd.getSocket().Close(); - } - catch (cli.System.Net.Sockets.SocketException x) - { - throw PlainSocketImpl.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } + try + { + if (false) throw new cli.System.Net.Sockets.SocketException(); + if (false) throw new cli.System.ObjectDisposedException(""); + fd.getSocket().Close(); + } + catch (cli.System.Net.Sockets.SocketException x) + { + throw PlainSocketImpl.convertSocketExceptionToIOException(x); + } + catch (cli.System.ObjectDisposedException x1) + { + throw new SocketException("Socket is closed"); + } } } diff --git a/openjdk/sun/nio/ch/Util.java b/openjdk/sun/nio/ch/Util.java index a3830e7e..71771abb 100644 --- a/openjdk/sun/nio/ch/Util.java +++ b/openjdk/sun/nio/ch/Util.java @@ -53,13 +53,13 @@ class Util { private Closer (Selector sel) { this.sel = sel; } - public void run () { + public void run () { try { - sel.close(); - } catch (Throwable th) { - throw new Error(th); - } - } + sel.close(); + } catch (Throwable th) { + throw new Error(th); + } + } } public Selector get() { return sel;} } @@ -74,109 +74,109 @@ class Util { // by cancelling any related keys and explicitly releasing // the selector by invoking releaseTemporarySelector() static Selector getTemporarySelector(SelectableChannel sc) - throws IOException + throws IOException { SoftReference ref = (SoftReference)localSelector.get(); - SelectorWrapper selWrapper = null; - Selector sel = null; - if (ref == null - || ((selWrapper = (SelectorWrapper) ref.get()) == null) - || ((sel = selWrapper.get()) == null) - || (sel.provider() != sc.provider())) { - sel = sc.provider().openSelector(); - localSelector.set(new SoftReference(new SelectorWrapper(sel))); - } else { + SelectorWrapper selWrapper = null; + Selector sel = null; + if (ref == null + || ((selWrapper = (SelectorWrapper) ref.get()) == null) + || ((sel = selWrapper.get()) == null) + || (sel.provider() != sc.provider())) { + sel = sc.provider().openSelector(); + localSelector.set(new SoftReference(new SelectorWrapper(sel))); + } else { localSelectorWrapper.set(selWrapper); - } - return sel; + } + return sel; } static void releaseTemporarySelector(Selector sel) throws IOException { - // Selector should be empty - sel.selectNow(); // Flush cancelled keys - assert sel.keys().isEmpty() : "Temporary selector not empty"; - localSelectorWrapper.set(null); + // Selector should be empty + sel.selectNow(); // Flush cancelled keys + assert sel.keys().isEmpty() : "Temporary selector not empty"; + localSelectorWrapper.set(null); } // -- Random stuff -- static ByteBuffer[] subsequence(ByteBuffer[] bs, int offset, int length) { - if ((offset == 0) && (length == bs.length)) - return bs; - int n = length; - ByteBuffer[] bs2 = new ByteBuffer[n]; - for (int i = 0; i < n; i++) - bs2[i] = bs[offset + i]; - return bs2; + if ((offset == 0) && (length == bs.length)) + return bs; + int n = length; + ByteBuffer[] bs2 = new ByteBuffer[n]; + for (int i = 0; i < n; i++) + bs2[i] = bs[offset + i]; + return bs2; } static <E> Set<E> ungrowableSet(final Set<E> s) { - return new Set<E>() { + return new Set<E>() { - public int size() { return s.size(); } - public boolean isEmpty() { return s.isEmpty(); } - public boolean contains(Object o) { return s.contains(o); } - public Object[] toArray() { return s.toArray(); } - public <T> T[] toArray(T[] a) { return s.toArray(a); } - public String toString() { return s.toString(); } - public Iterator<E> iterator() { return s.iterator(); } - public boolean equals(Object o) { return s.equals(o); } - public int hashCode() { return s.hashCode(); } - public void clear() { s.clear(); } - public boolean remove(Object o) { return s.remove(o); } + public int size() { return s.size(); } + public boolean isEmpty() { return s.isEmpty(); } + public boolean contains(Object o) { return s.contains(o); } + public Object[] toArray() { return s.toArray(); } + public <T> T[] toArray(T[] a) { return s.toArray(a); } + public String toString() { return s.toString(); } + public Iterator<E> iterator() { return s.iterator(); } + public boolean equals(Object o) { return s.equals(o); } + public int hashCode() { return s.hashCode(); } + public void clear() { s.clear(); } + public boolean remove(Object o) { return s.remove(o); } - public boolean containsAll(Collection<?> coll) { - return s.containsAll(coll); - } - public boolean removeAll(Collection<?> coll) { - return s.removeAll(coll); - } - public boolean retainAll(Collection<?> coll) { - return s.retainAll(coll); - } + public boolean containsAll(Collection<?> coll) { + return s.containsAll(coll); + } + public boolean removeAll(Collection<?> coll) { + return s.removeAll(coll); + } + public boolean retainAll(Collection<?> coll) { + return s.retainAll(coll); + } - public boolean add(E o){ - throw new UnsupportedOperationException(); - } - public boolean addAll(Collection<? extends E> coll) { - throw new UnsupportedOperationException(); - } + public boolean add(E o){ + throw new UnsupportedOperationException(); + } + public boolean addAll(Collection<? extends E> coll) { + throw new UnsupportedOperationException(); + } - }; + }; } private static volatile Constructor directByteBufferConstructor = null; private static void initDBBConstructor() { - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - try { - Class cl = Class.forName("java.nio.DirectByteBuffer"); + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + try { + Class cl = Class.forName("java.nio.DirectByteBuffer"); Constructor ctor = cl.getDeclaredConstructor( - new Class[] { int.class, + new Class[] { int.class, long.class, - Runnable.class }); + Runnable.class }); ctor.setAccessible(true); - directByteBufferConstructor = ctor; - } catch (ClassNotFoundException x) { - throw new InternalError(); - } catch (NoSuchMethodException x) { - throw new InternalError(); - } catch (IllegalArgumentException x) { - throw new InternalError(); - } catch (ClassCastException x) { - throw new InternalError(); - } + directByteBufferConstructor = ctor; + } catch (ClassNotFoundException x) { + throw new InternalError(); + } catch (NoSuchMethodException x) { + throw new InternalError(); + } catch (IllegalArgumentException x) { + throw new InternalError(); + } catch (ClassCastException x) { + throw new InternalError(); + } return null; - }}); + }}); } static MappedByteBuffer newMappedByteBuffer(int size, long addr, - Runnable unmapper) + Runnable unmapper) { MappedByteBuffer dbb; if (directByteBufferConstructor == null) @@ -185,7 +185,7 @@ class Util { dbb = (MappedByteBuffer)directByteBufferConstructor.newInstance( new Object[] { new Integer(size), new Long(addr), - unmapper }); + unmapper }); } catch (InstantiationException e) { throw new InternalError(); } catch (IllegalAccessException e) { @@ -199,31 +199,31 @@ class Util { private static volatile Constructor directByteBufferRConstructor = null; private static void initDBBRConstructor() { - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - try { - Class cl = Class.forName("java.nio.DirectByteBufferR"); - Constructor ctor = cl.getDeclaredConstructor( - new Class[] { int.class, + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + try { + Class cl = Class.forName("java.nio.DirectByteBufferR"); + Constructor ctor = cl.getDeclaredConstructor( + new Class[] { int.class, long.class, - Runnable.class }); - ctor.setAccessible(true); - directByteBufferRConstructor = ctor; - } catch (ClassNotFoundException x) { - throw new InternalError(); - } catch (NoSuchMethodException x) { - throw new InternalError(); - } catch (IllegalArgumentException x) { - throw new InternalError(); - } catch (ClassCastException x) { - throw new InternalError(); - } + Runnable.class }); + ctor.setAccessible(true); + directByteBufferRConstructor = ctor; + } catch (ClassNotFoundException x) { + throw new InternalError(); + } catch (NoSuchMethodException x) { + throw new InternalError(); + } catch (IllegalArgumentException x) { + throw new InternalError(); + } catch (ClassCastException x) { + throw new InternalError(); + } return null; - }}); + }}); } static MappedByteBuffer newMappedByteBufferR(int size, long addr, - Runnable unmapper) + Runnable unmapper) { MappedByteBuffer dbb; if (directByteBufferRConstructor == null) @@ -232,7 +232,7 @@ class Util { dbb = (MappedByteBuffer)directByteBufferRConstructor.newInstance( new Object[] { new Integer(size), new Long(addr), - unmapper }); + unmapper }); } catch (InstantiationException e) { throw new InternalError(); } catch (IllegalAccessException e) { @@ -248,16 +248,16 @@ class Util { private static volatile String bugLevel = null; - static boolean atBugLevel(String bl) { // package-private - if (bugLevel == null) { - if (!sun.misc.VM.isBooted()) - return false; - java.security.PrivilegedAction pa = - new GetPropertyAction("sun.nio.ch.bugLevel"); - String value = (String)AccessController.doPrivileged(pa); - bugLevel = (value != null) ? value : ""; - } - return bugLevel.equals(bl); + static boolean atBugLevel(String bl) { // package-private + if (bugLevel == null) { + if (!sun.misc.VM.isBooted()) + return false; + java.security.PrivilegedAction pa = + new GetPropertyAction("sun.nio.ch.bugLevel"); + String value = (String)AccessController.doPrivileged(pa); + bugLevel = (value != null) ? value : ""; + } + return bugLevel.equals(bl); } |