diff options
author | Miguel de Icaza <miguel@gnome.org> | 2016-02-27 23:38:24 +0300 |
---|---|---|
committer | Miguel de Icaza <miguel@gnome.org> | 2016-02-27 23:38:24 +0300 |
commit | 94d4a298ad560f8674d746dea2d51e26e0a97f2a (patch) | |
tree | ae303637d83843abf98938b07eb9808880cea9fa /openjdk/sun/nio/ch | |
parent | c9edfe788667d5777e97e3f2fd195080d06dd32c (diff) |
Remove unused filesmaster-signed
Diffstat (limited to 'openjdk/sun/nio/ch')
-rw-r--r-- | openjdk/sun/nio/ch/DatagramChannelImpl.java | 1113 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/DefaultSelectorProvider.java | 55 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/DotNetSelectorImpl.java | 324 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/FileChannelImpl.java | 1104 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/FileDispatcherImpl.java | 301 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/FileKey.java | 57 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/IOUtil.java | 179 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/Iocp.java | 140 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/NativeDispatcher.java | 56 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/Net.java | 609 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/PollArrayWrapper.java | 37 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/SelectionKeyImpl.java | 118 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/SocketDispatcher.java | 121 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/SocketOptionRegistry.java | 86 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/Util.java | 278 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java | 689 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java | 320 | ||||
-rw-r--r-- | openjdk/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java | 817 |
18 files changed, 0 insertions, 6404 deletions
diff --git a/openjdk/sun/nio/ch/DatagramChannelImpl.java b/openjdk/sun/nio/ch/DatagramChannelImpl.java deleted file mode 100644 index 08cc5c95..00000000 --- a/openjdk/sun/nio/ch/DatagramChannelImpl.java +++ /dev/null @@ -1,1113 +0,0 @@ -/* - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.net.*; -import java.nio.ByteBuffer; -import java.nio.channels.*; -import java.nio.channels.spi.*; -import java.util.*; -import sun.net.ResourceManager; - - -/** - * An implementation of DatagramChannels. - */ - -class DatagramChannelImpl - extends DatagramChannel - implements SelChImpl -{ - - // Used to make native read and write calls - private static NativeDispatcher nd = new SocketDispatcher(); - - // Our file descriptor - private final FileDescriptor fd; - - // fd value needed for dev/poll. This value will remain valid - // even after the value in the file descriptor object has been set to -1 - private final int fdVal; - - // The protocol family of the socket - private final ProtocolFamily family; - - // IDs of native threads doing reads and writes, for signalling - private volatile long readerThread = 0; - private volatile long writerThread = 0; - - // Cached InetAddress and port for unconnected DatagramChannels - // used by receive0 - private InetAddress cachedSenderInetAddress; - private int cachedSenderPort; - - // Lock held by current reading or connecting thread - private final Object readLock = new Object(); - - // Lock held by current writing or connecting thread - private final Object writeLock = new Object(); - - // Lock held by any thread that modifies the state fields declared below - // DO NOT invoke a blocking I/O operation while holding this lock! - private final Object stateLock = new Object(); - - // -- The following fields are protected by stateLock - - // State (does not necessarily increase monotonically) - private static final int ST_UNINITIALIZED = -1; - private static final int ST_UNCONNECTED = 0; - private static final int ST_CONNECTED = 1; - private static final int ST_KILLED = 2; - private int state = ST_UNINITIALIZED; - - // Binding - private InetSocketAddress localAddress; - private InetSocketAddress remoteAddress; - - // Our socket adaptor, if any - private DatagramSocket socket; - - // Multicast support - private MembershipRegistry registry; - - // set true when socket is bound and SO_REUSEADDRESS is emulated - private boolean reuseAddressEmulated; - - // set true/false when socket is already bound and SO_REUSEADDR is emulated - private boolean isReuseAddress; - - // -- End of fields protected by stateLock - - - public DatagramChannelImpl(SelectorProvider sp) - throws IOException - { - super(sp); - ResourceManager.beforeUdpCreate(); - try { - this.family = Net.isIPv6Available() ? - StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; - this.fd = Net.socket(family, false); - this.fdVal = IOUtil.fdVal(fd); - this.state = ST_UNCONNECTED; - } catch (IOException ioe) { - ResourceManager.afterUdpClose(); - throw ioe; - } - } - - public DatagramChannelImpl(SelectorProvider sp, ProtocolFamily family) - throws IOException - { - super(sp); - if ((family != StandardProtocolFamily.INET) && - (family != StandardProtocolFamily.INET6)) - { - if (family == null) - throw new NullPointerException("'family' is null"); - else - throw new UnsupportedOperationException("Protocol family not supported"); - } - if (family == StandardProtocolFamily.INET6) { - if (!Net.isIPv6Available()) { - throw new UnsupportedOperationException("IPv6 not available"); - } - } - this.family = family; - this.fd = Net.socket(family, false); - this.fdVal = IOUtil.fdVal(fd); - this.state = ST_UNCONNECTED; - } - - public DatagramChannelImpl(SelectorProvider sp, FileDescriptor fd) - throws IOException - { - super(sp); - this.family = Net.isIPv6Available() ? - StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; - this.fd = fd; - this.fdVal = IOUtil.fdVal(fd); - this.state = ST_UNCONNECTED; - this.localAddress = Net.localAddress(fd); - } - - public DatagramSocket socket() { - synchronized (stateLock) { - if (socket == null) - socket = DatagramSocketAdaptor.create(this); - return socket; - } - } - - @Override - public SocketAddress getLocalAddress() throws IOException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - return Net.getRevealedLocalAddress(localAddress); - } - } - - @Override - public SocketAddress getRemoteAddress() throws IOException { - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - return remoteAddress; - } - } - - @Override - public <T> DatagramChannel setOption(SocketOption<T> name, T value) - throws IOException - { - if (name == null) - throw new NullPointerException(); - if (!supportedOptions().contains(name)) - throw new UnsupportedOperationException("'" + name + "' not supported"); - - synchronized (stateLock) { - ensureOpen(); - - if (name == StandardSocketOptions.IP_TOS) { - // IPv4 only; no-op for IPv6 - if (family == StandardProtocolFamily.INET) { - Net.setSocketOption(fd, family, name, value); - } - return this; - } - - if (name == StandardSocketOptions.IP_MULTICAST_TTL || - name == StandardSocketOptions.IP_MULTICAST_LOOP) - { - // options are protocol dependent - Net.setSocketOption(fd, family, name, value); - return this; - } - - if (name == StandardSocketOptions.IP_MULTICAST_IF) { - if (value == null) - throw new IllegalArgumentException("Cannot set IP_MULTICAST_IF to 'null'"); - NetworkInterface interf = (NetworkInterface)value; - if (family == StandardProtocolFamily.INET6) { - int index = interf.getIndex(); - if (index == -1) - throw new IOException("Network interface cannot be identified"); - Net.setInterface6(fd, index); - } else { - // need IPv4 address to identify interface - Inet4Address target = Net.anyInet4Address(interf); - if (target == null) - throw new IOException("Network interface not configured for IPv4"); - int targetAddress = Net.inet4AsInt(target); - Net.setInterface4(fd, targetAddress); - } - return this; - } - if (name == StandardSocketOptions.SO_REUSEADDR && - Net.useExclusiveBind() && localAddress != null) - { - reuseAddressEmulated = true; - this.isReuseAddress = (Boolean)value; - } - - // remaining options don't need any special handling - Net.setSocketOption(fd, Net.UNSPEC, name, value); - return this; - } - } - - @Override - @SuppressWarnings("unchecked") - public <T> T getOption(SocketOption<T> name) - throws IOException - { - if (name == null) - throw new NullPointerException(); - if (!supportedOptions().contains(name)) - throw new UnsupportedOperationException("'" + name + "' not supported"); - - synchronized (stateLock) { - ensureOpen(); - - if (name == StandardSocketOptions.IP_TOS) { - // IPv4 only; always return 0 on IPv6 - if (family == StandardProtocolFamily.INET) { - return (T) Net.getSocketOption(fd, family, name); - } else { - return (T) Integer.valueOf(0); - } - } - - if (name == StandardSocketOptions.IP_MULTICAST_TTL || - name == StandardSocketOptions.IP_MULTICAST_LOOP) - { - return (T) Net.getSocketOption(fd, family, name); - } - - if (name == StandardSocketOptions.IP_MULTICAST_IF) { - if (family == StandardProtocolFamily.INET) { - int address = Net.getInterface4(fd); - if (address == 0) - return null; // default interface - - InetAddress ia = Net.inet4FromInt(address); - NetworkInterface ni = NetworkInterface.getByInetAddress(ia); - if (ni == null) - throw new IOException("Unable to map address to interface"); - return (T) ni; - } else { - int index = Net.getInterface6(fd); - if (index == 0) - return null; // default interface - - NetworkInterface ni = NetworkInterface.getByIndex(index); - if (ni == null) - throw new IOException("Unable to map index to interface"); - return (T) ni; - } - } - - if (name == StandardSocketOptions.SO_REUSEADDR && - reuseAddressEmulated) - { - return (T)Boolean.valueOf(isReuseAddress); - } - - // no special handling - return (T) Net.getSocketOption(fd, Net.UNSPEC, name); - } - } - - private static class DefaultOptionsHolder { - static final Set<SocketOption<?>> defaultOptions = defaultOptions(); - - private static Set<SocketOption<?>> defaultOptions() { - HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(8); - set.add(StandardSocketOptions.SO_SNDBUF); - set.add(StandardSocketOptions.SO_RCVBUF); - set.add(StandardSocketOptions.SO_REUSEADDR); - set.add(StandardSocketOptions.SO_BROADCAST); - set.add(StandardSocketOptions.IP_TOS); - set.add(StandardSocketOptions.IP_MULTICAST_IF); - set.add(StandardSocketOptions.IP_MULTICAST_TTL); - set.add(StandardSocketOptions.IP_MULTICAST_LOOP); - return Collections.unmodifiableSet(set); - } - } - - @Override - public final Set<SocketOption<?>> supportedOptions() { - return DefaultOptionsHolder.defaultOptions; - } - - private void ensureOpen() throws ClosedChannelException { - if (!isOpen()) - throw new ClosedChannelException(); - } - - 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) { - ensureOpen(); - // Socket was not bound before attempting receive - if (localAddress() == null) - bind(null); - int n = 0; - ByteBuffer bb = null; - try { - begin(); - if (!isOpen()) - return null; - SecurityManager security = System.getSecurityManager(); - readerThread = NativeThread.current(); - if (isConnected() || (security == null)) { - do { - n = receive(fd, dst); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - if (n == IOStatus.UNAVAILABLE) - return null; - } else { - bb = ByteBuffer.allocate(dst.remaining()); - for (;;) { - do { - n = receive(fd, bb); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - if (n == IOStatus.UNAVAILABLE) - return null; - InetSocketAddress isa = (InetSocketAddress)sender; - try { - security.checkAccept( - isa.getAddress().getHostAddress(), - isa.getPort()); - } catch (SecurityException se) { - // Ignore packet - bb.clear(); - n = 0; - continue; - } - bb.flip(); - dst.put(bb); - break; - } - } - return sender; - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - private int receive(FileDescriptor fd, ByteBuffer dst) - throws IOException - { - int pos = dst.position(); - int lim = dst.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - if (dst.hasArray() && rem > 0) - return receiveIntoManagedBuffer(fd, dst, rem, pos); - - // Substitute a managed buffer. If the supplied buffer is empty - // we must instead use a nonempty buffer, otherwise the call - // will not block waiting for a datagram on some platforms. - int newSize = Math.max(rem, 1); - ByteBuffer bb = ByteBuffer.allocate(newSize); - try { - int n = receiveIntoManagedBuffer(fd, bb, newSize, 0); - bb.flip(); - if (n > 0 && rem > 0) - dst.put(bb); - return n; - } finally { - } - } - - private int receiveIntoManagedBuffer(FileDescriptor fd, ByteBuffer bb, - int rem, int pos) - throws IOException - { - int n = receive0(fd, bb.array(), bb.arrayOffset() + pos, rem, - isConnected()); - if (n > 0) - bb.position(pos + n); - return n; - } - - public int send(ByteBuffer src, SocketAddress target) - throws IOException - { - if (src == null) - throw new NullPointerException(); - - synchronized (writeLock) { - ensureOpen(); - InetSocketAddress isa = Net.checkAddress(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(ia); - } else { - sm.checkConnect(ia.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 = send(fd, src, isa); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - - synchronized (stateLock) { - if (isOpen() && (localAddress == null)) { - localAddress = Net.localAddress(fd); - } - } - return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - private int send(FileDescriptor fd, ByteBuffer src, InetSocketAddress target) - throws IOException - { - if (src.hasArray()) - return sendFromManagedBuffer(fd, src, target); - - // Substitute a managed buffer - int pos = src.position(); - int lim = src.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - ByteBuffer bb = ByteBuffer.allocate(rem); - try { - bb.put(src); - bb.flip(); - // Do not update src until we see how many bytes were written - src.position(pos); - - int n = sendFromManagedBuffer(fd, bb, target); - if (n > 0) { - // now update src - src.position(pos + n); - } - return n; - } finally { - } - } - - private int sendFromManagedBuffer(FileDescriptor fd, ByteBuffer bb, - InetSocketAddress target) - throws IOException - { - int pos = bb.position(); - int lim = bb.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - boolean preferIPv6 = (family != StandardProtocolFamily.INET); - int written; - try { - written = send0(preferIPv6, fd, bb.array(), bb.arrayOffset() + pos, - rem, target.getAddress(), target.getPort()); - } catch (PortUnreachableException pue) { - if (isConnected()) - throw pue; - written = rem; - } - if (written > 0) - bb.position(pos + written); - return written; - } - - 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 = IOUtil.read(fd, buf, -1, nd, readLock); - } 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 - { - if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) - throw new IndexOutOfBoundsException(); - synchronized (readLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; - readerThread = NativeThread.current(); - do { - n = IOUtil.read(fd, dsts, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - readerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - 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 = IOUtil.write(fd, buf, -1, nd, writeLock); - } 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 - { - if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) - throw new IndexOutOfBoundsException(); - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (!isConnected()) - throw new NotYetConnectedException(); - } - long n = 0; - try { - begin(); - if (!isOpen()) - return 0; - writerThread = NativeThread.current(); - do { - n = IOUtil.write(fd, srcs, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - writerThread = 0; - end((n > 0) || (n == IOStatus.UNAVAILABLE)); - assert IOStatus.check(n); - } - } - } - - protected void implConfigureBlocking(boolean block) throws IOException { - IOUtil.configureBlocking(fd, block); - } - - public SocketAddress localAddress() { - synchronized (stateLock) { - return localAddress; - } - } - - public SocketAddress remoteAddress() { - synchronized (stateLock) { - return remoteAddress; - } - } - - @Override - public DatagramChannel bind(SocketAddress local) throws IOException { - synchronized (readLock) { - synchronized (writeLock) { - synchronized (stateLock) { - ensureOpen(); - if (localAddress != null) - throw new AlreadyBoundException(); - InetSocketAddress isa; - if (local == null) { - // only Inet4Address allowed with IPv4 socket - if (family == StandardProtocolFamily.INET) { - isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0); - } else { - isa = new InetSocketAddress(0); - } - } else { - isa = Net.checkAddress(local); - - // only Inet4Address allowed with IPv4 socket - if (family == StandardProtocolFamily.INET) { - InetAddress addr = isa.getAddress(); - if (!(addr instanceof Inet4Address)) - throw new UnsupportedAddressTypeException(); - } - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkListen(isa.getPort()); - } - Net.bind(family, fd, isa.getAddress(), isa.getPort()); - localAddress = Net.localAddress(fd); - } - } - } - return this; - } - - public boolean isConnected() { - 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"); - } - } - - @Override - public DatagramChannel connect(SocketAddress sa) throws IOException { - 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()); - int n = Net.connect(family, - fd, - isa.getAddress(), - isa.getPort()); - if (n <= 0) - throw new Error(); // Can't happen - - // Connection succeeded; disallow further invocation - state = ST_CONNECTED; - remoteAddress = isa; - sender = isa; - cachedSenderInetAddress = isa.getAddress(); - cachedSenderPort = isa.getPort(); - - // set or refresh local address - localAddress = Net.localAddress(fd); - } - } - } - return this; - } - - public DatagramChannel disconnect() throws IOException { - synchronized(readLock) { - synchronized(writeLock) { - synchronized (stateLock) { - if (!isConnected() || !isOpen()) - return this; - InetSocketAddress isa = remoteAddress; - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), - isa.getPort()); - boolean isIPv6 = (family == StandardProtocolFamily.INET6); - disconnect0(fd, isIPv6); - remoteAddress = null; - state = ST_UNCONNECTED; - - // refresh local address - localAddress = Net.localAddress(fd); - } - } - } - return this; - } - - /** - * Joins channel's socket to the given group/interface and - * optional source address. - */ - private MembershipKey innerJoin(InetAddress group, - NetworkInterface interf, - InetAddress source) - throws IOException - { - if (!group.isMulticastAddress()) - throw new IllegalArgumentException("Group not a multicast address"); - - // check multicast address is compatible with this socket - if (group instanceof Inet4Address) { - if (family == StandardProtocolFamily.INET6 && !Net.canIPv6SocketJoinIPv4Group()) - throw new IllegalArgumentException("IPv6 socket cannot join IPv4 multicast group"); - } else if (group instanceof Inet6Address) { - if (family != StandardProtocolFamily.INET6) - throw new IllegalArgumentException("Only IPv6 sockets can join IPv6 multicast group"); - } else { - throw new IllegalArgumentException("Address type not supported"); - } - - // check source address - if (source != null) { - if (source.isAnyLocalAddress()) - throw new IllegalArgumentException("Source address is a wildcard address"); - if (source.isMulticastAddress()) - throw new IllegalArgumentException("Source address is multicast address"); - if (source.getClass() != group.getClass()) - throw new IllegalArgumentException("Source address is different type to group"); - } - - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkMulticast(group); - - synchronized (stateLock) { - if (!isOpen()) - throw new ClosedChannelException(); - - // check the registry to see if we are already a member of the group - if (registry == null) { - registry = new MembershipRegistry(); - } else { - // return existing membership key - MembershipKey key = registry.checkMembership(group, interf, source); - if (key != null) - return key; - } - - MembershipKeyImpl key; - if ((family == StandardProtocolFamily.INET6) && - ((group instanceof Inet6Address) || Net.canJoin6WithIPv4Group())) - { - int index = interf.getIndex(); - if (index == -1) - throw new IOException("Network interface cannot be identified"); - - // need multicast and source address as byte arrays - byte[] groupAddress = Net.inet6AsByteArray(group); - byte[] sourceAddress = (source == null) ? null : - Net.inet6AsByteArray(source); - - // join the group - int n = Net.join6(fd, groupAddress, index, sourceAddress); - if (n == IOStatus.UNAVAILABLE) - throw new UnsupportedOperationException(); - - key = new MembershipKeyImpl.Type6(this, group, interf, source, - groupAddress, index, sourceAddress); - - } else { - // need IPv4 address to identify interface - Inet4Address target = Net.anyInet4Address(interf); - if (target == null) - throw new IOException("Network interface not configured for IPv4"); - - int groupAddress = Net.inet4AsInt(group); - int targetAddress = Net.inet4AsInt(target); - int sourceAddress = (source == null) ? 0 : Net.inet4AsInt(source); - - // join the group - int n = Net.join4(fd, groupAddress, targetAddress, sourceAddress); - if (n == IOStatus.UNAVAILABLE) - throw new UnsupportedOperationException(); - - key = new MembershipKeyImpl.Type4(this, group, interf, source, - groupAddress, targetAddress, sourceAddress); - } - - registry.add(key); - return key; - } - } - - @Override - public MembershipKey join(InetAddress group, - NetworkInterface interf) - throws IOException - { - return innerJoin(group, interf, null); - } - - @Override - public MembershipKey join(InetAddress group, - NetworkInterface interf, - InetAddress source) - throws IOException - { - if (source == null) - throw new NullPointerException("source address is null"); - return innerJoin(group, interf, source); - } - - // package-private - void drop(MembershipKeyImpl key) { - assert key.channel() == this; - - synchronized (stateLock) { - if (!key.isValid()) - return; - - try { - if (key instanceof MembershipKeyImpl.Type6) { - MembershipKeyImpl.Type6 key6 = - (MembershipKeyImpl.Type6)key; - Net.drop6(fd, key6.groupAddress(), key6.index(), key6.source()); - } else { - MembershipKeyImpl.Type4 key4 = (MembershipKeyImpl.Type4)key; - Net.drop4(fd, key4.groupAddress(), key4.interfaceAddress(), - key4.source()); - } - } catch (IOException ioe) { - // should not happen - throw new AssertionError(ioe); - } - - key.invalidate(); - registry.remove(key); - } - } - - /** - * Block datagrams from given source if a memory to receive all - * datagrams. - */ - void block(MembershipKeyImpl key, InetAddress source) - throws IOException - { - assert key.channel() == this; - assert key.sourceAddress() == null; - - synchronized (stateLock) { - if (!key.isValid()) - throw new IllegalStateException("key is no longer valid"); - if (source.isAnyLocalAddress()) - throw new IllegalArgumentException("Source address is a wildcard address"); - if (source.isMulticastAddress()) - throw new IllegalArgumentException("Source address is multicast address"); - if (source.getClass() != key.group().getClass()) - throw new IllegalArgumentException("Source address is different type to group"); - - int n; - if (key instanceof MembershipKeyImpl.Type6) { - MembershipKeyImpl.Type6 key6 = - (MembershipKeyImpl.Type6)key; - n = Net.block6(fd, key6.groupAddress(), key6.index(), - Net.inet6AsByteArray(source)); - } else { - MembershipKeyImpl.Type4 key4 = - (MembershipKeyImpl.Type4)key; - n = Net.block4(fd, key4.groupAddress(), key4.interfaceAddress(), - Net.inet4AsInt(source)); - } - if (n == IOStatus.UNAVAILABLE) { - // ancient kernel - throw new UnsupportedOperationException(); - } - } - } - - /** - * Unblock given source. - */ - void unblock(MembershipKeyImpl key, InetAddress source) { - assert key.channel() == this; - assert key.sourceAddress() == null; - - synchronized (stateLock) { - if (!key.isValid()) - throw new IllegalStateException("key is no longer valid"); - - try { - if (key instanceof MembershipKeyImpl.Type6) { - MembershipKeyImpl.Type6 key6 = - (MembershipKeyImpl.Type6)key; - Net.unblock6(fd, key6.groupAddress(), key6.index(), - Net.inet6AsByteArray(source)); - } else { - MembershipKeyImpl.Type4 key4 = - (MembershipKeyImpl.Type4)key; - Net.unblock4(fd, key4.groupAddress(), key4.interfaceAddress(), - Net.inet4AsInt(source)); - } - } catch (IOException ioe) { - // should not happen - throw new AssertionError(ioe); - } - } - } - - protected void implCloseSelectableChannel() throws IOException { - synchronized (stateLock) { - if (state != ST_KILLED) - nd.preClose(fd); - ResourceManager.afterUdpClose(); - - // if member of mulitcast group then invalidate all keys - if (registry != null) - registry.invalidateAll(); - - 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) { - state = ST_KILLED; - return; - } - assert !isOpen() && !isRegistered(); - nd.close(fd); - state = ST_KILLED; - } - } - - /** - * Translates native poll revent set into a ready operation set - */ - public boolean translateReadyOps(int ops, int initialOps, - SelectionKeyImpl sk) { - int intOps = sk.nioInterestOps(); // Do this just once, it synchronizes - int oldOps = sk.nioReadyOps(); - 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; - } - - if ((ops & (PollArrayWrapper.POLLERR - | PollArrayWrapper.POLLHUP)) != 0) { - newOps = intOps; - sk.nioReadyOps(newOps); - return (newOps & ~oldOps) != 0; - } - - if (((ops & PollArrayWrapper.POLLIN) != 0) && - ((intOps & SelectionKey.OP_READ) != 0)) - newOps |= SelectionKey.OP_READ; - - if (((ops & PollArrayWrapper.POLLOUT) != 0) && - ((intOps & SelectionKey.OP_WRITE) != 0)) - newOps |= SelectionKey.OP_WRITE; - - sk.nioReadyOps(newOps); - return (newOps & ~oldOps) != 0; - } - - public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk) { - return translateReadyOps(ops, sk.nioReadyOps(), sk); - } - - public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk) { - return translateReadyOps(ops, 0, sk); - } - - /** - * Translates an interest operation set into a native poll event set - */ - public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) { - int newOps = 0; - - if ((ops & SelectionKey.OP_READ) != 0) - newOps |= PollArrayWrapper.POLLIN; - if ((ops & SelectionKey.OP_WRITE) != 0) - newOps |= PollArrayWrapper.POLLOUT; - if ((ops & SelectionKey.OP_CONNECT) != 0) - newOps |= PollArrayWrapper.POLLIN; - sk.selector.putEventOps(sk, newOps); - } - - public FileDescriptor getFD() { - return fd; - } - - public int getFDVal() { - return fdVal; - } - - - // -- Native methods -- - - private static native void initIDs(); - - private static native void disconnect0(FileDescriptor fd, boolean isIPv6) - throws IOException; - - private native int receive0(FileDescriptor fd, byte[] buf, int pos, int len, - boolean connected) - throws IOException; - - private native int send0(boolean preferIPv6, FileDescriptor fd, byte[] buf, int pos, - int len, InetAddress addr, int port) - throws IOException; - - static { - Util.load(); - initIDs(); - } - -} diff --git a/openjdk/sun/nio/ch/DefaultSelectorProvider.java b/openjdk/sun/nio/ch/DefaultSelectorProvider.java deleted file mode 100644 index 8c5cf037..00000000 --- a/openjdk/sun/nio/ch/DefaultSelectorProvider.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.IOException; -import java.nio.channels.spi.AbstractSelector; -import java.nio.channels.spi.SelectorProvider; - - -/** - * Creates this platform's default SelectorProvider - */ - -public class DefaultSelectorProvider { - - /** - * Prevent instantiation. - */ - private DefaultSelectorProvider() { } - - /** - * Returns the default SelectorProvider. - */ - public static SelectorProvider create() { - 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 deleted file mode 100644 index 897cf9a1..00000000 --- a/openjdk/sun/nio/ch/DotNetSelectorImpl.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// Parts Copyright (C) 2002-2007 Jeroen Frijters - -package sun.nio.ch; - -import cli.System.Net.Sockets.Socket; -import cli.System.Net.Sockets.SocketException; -import cli.System.Net.Sockets.AddressFamily; -import cli.System.Net.Sockets.SocketType; -import cli.System.Net.Sockets.ProtocolType; -import cli.System.Net.Sockets.SelectMode; -import cli.System.Collections.ArrayList; -import java.io.IOException; -import java.nio.channels.ClosedSelectorException; -import java.nio.channels.Pipe; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.AbstractSelectableChannel; -import java.nio.channels.spi.AbstractSelector; -import java.nio.channels.spi.SelectorProvider; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -final class DotNetSelectorImpl extends SelectorImpl -{ - private ArrayList channelArray = new ArrayList(); - private long updateCount = 0; - - //Pipe used as a wakeup object. - private final Pipe wakeupPipe; - - // File descriptors corresponding to source and sink - private final Socket wakeupSourceFd, wakeupSinkFd; - - // Lock for interrupt triggering and clearing - private final Object interruptLock = new Object(); - private volatile boolean interruptTriggered = false; - - // class for fdMap entries - private final static class MapEntry - { - 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(); - - // 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; - } - - 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; - } - - 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; - } - - 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; - } - } - - protected void implRegister(SelectionKeyImpl 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(); - } - } - - public Selector wakeup() - { - 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]); - } - - // Sets Windows wakeup socket to a non-signaled state. - private void resetWakeupSocket() { - 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]); - } - } -} diff --git a/openjdk/sun/nio/ch/FileChannelImpl.java b/openjdk/sun/nio/ch/FileChannelImpl.java deleted file mode 100644 index 902509bd..00000000 --- a/openjdk/sun/nio/ch/FileChannelImpl.java +++ /dev/null @@ -1,1104 +0,0 @@ -/* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import cli.Microsoft.Win32.SafeHandles.SafeFileHandle; -import cli.System.IntPtr; -import cli.System.IO.FileStream; -import cli.System.Runtime.InteropServices.DllImportAttribute; -import java.io.FileDescriptor; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.*; -import java.util.ArrayList; -import java.util.List; -import java.security.AccessController; -import sun.misc.Cleaner; -import sun.misc.IoTrace; -import sun.security.action.GetPropertyAction; - -public class FileChannelImpl - extends FileChannel -{ - private static final boolean win32 = ikvm.internal.Util.WINDOWS; - - // Memory allocation size for mapping buffers - private static final long allocationGranularity = 64 * 1024; // HACK we're using a hard coded value here that works on all mainstream platforms - - // Used to make native read and write calls - private final FileDispatcher nd; - - // File descriptor - private final FileDescriptor fd; - - // File access mode (immutable) - private final boolean writable; - private final boolean readable; - private final boolean append; - - // Required to prevent finalization of creating stream (immutable) - private final Object parent; - - // The path of the referenced file (null if the parent stream is created with a file descriptor) - private final String path; - - // Thread-safe set of IDs of native threads, for signalling - private final NativeThreadSet threads = new NativeThreadSet(2); - - // Lock for operations involving position and size - private final Object positionLock = new Object(); - - private FileChannelImpl(FileDescriptor fd, String path, boolean readable, - boolean writable, boolean append, Object parent) - { - this.fd = fd; - this.readable = readable; - this.writable = writable; - this.append = append; - this.parent = parent; - this.path = path; - this.nd = new FileDispatcherImpl(append); - } - - // Used by FileInputStream.getChannel() and RandomAccessFile.getChannel() - public static FileChannel open(FileDescriptor fd, String path, - boolean readable, boolean writable, - Object parent) - { - return new FileChannelImpl(fd, path, readable, writable, false, parent); - } - - // Used by FileOutputStream.getChannel - public static FileChannel open(FileDescriptor fd, String path, - boolean readable, boolean writable, - boolean append, Object parent) - { - return new FileChannelImpl(fd, path, readable, writable, append, parent); - } - - private void ensureOpen() throws IOException { - if (!isOpen()) - throw new ClosedChannelException(); - } - - - // -- Standard channel operations -- - - protected void implCloseChannel() throws IOException { - // Release and invalidate any locks that we still hold - if (fileLockTable != null) { - for (FileLock fl: fileLockTable.removeAll()) { - synchronized (fl) { - if (fl.isValid()) { - nd.release(fd, fl.position(), fl.size()); - ((FileLockImpl)fl).invalidate(); - } - } - } - } - - nd.preClose(fd); - threads.signalAndWait(); - - 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. - // - ((java.io.Closeable)parent).close(); - } else { - nd.close(fd); - } - - } - - public int read(ByteBuffer dst) throws IOException { - ensureOpen(); - if (!readable) - throw new NonReadableChannelException(); - synchronized (positionLock) { - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileReadBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.read(fd, dst, -1, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - } - - public long read(ByteBuffer[] dsts, int offset, int length) - throws IOException - { - if ((offset < 0) || (length < 0) || (offset > dsts.length - length)) - throw new IndexOutOfBoundsException(); - ensureOpen(); - if (!readable) - throw new NonReadableChannelException(); - synchronized (positionLock) { - long n = 0; - int ti = -1; - Object traceContext = IoTrace.fileReadBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.read(fd, dsts, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - } - - public int write(ByteBuffer src) throws IOException { - ensureOpen(); - if (!writable) - throw new NonWritableChannelException(); - synchronized (positionLock) { - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileWriteBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.write(fd, src, -1, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - end(n > 0); - IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0); - assert IOStatus.check(n); - } - } - } - - public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException - { - if ((offset < 0) || (length < 0) || (offset > srcs.length - length)) - throw new IndexOutOfBoundsException(); - ensureOpen(); - if (!writable) - throw new NonWritableChannelException(); - synchronized (positionLock) { - long n = 0; - int ti = -1; - Object traceContext = IoTrace.fileWriteBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - n = IOUtil.write(fd, srcs, offset, length, nd); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - } - - // -- Other operations -- - - public long position() throws IOException { - ensureOpen(); - synchronized (positionLock) { - long p = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return 0; - do { - // in append-mode then position is advanced to end before writing - p = (append) ? nd.size(fd) : position0(fd, -1); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(p); - } finally { - threads.remove(ti); - end(p > -1); - assert IOStatus.check(p); - } - } - } - - public FileChannel position(long newPosition) throws IOException { - ensureOpen(); - if (newPosition < 0) - throw new IllegalArgumentException(); - synchronized (positionLock) { - long p = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return null; - do { - p = position0(fd, newPosition); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - return this; - } finally { - threads.remove(ti); - end(p > -1); - assert IOStatus.check(p); - } - } - } - - public long size() throws IOException { - ensureOpen(); - synchronized (positionLock) { - long s = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return -1; - do { - s = nd.size(fd); - } while ((s == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(s); - } finally { - threads.remove(ti); - end(s > -1); - assert IOStatus.check(s); - } - } - } - - public FileChannel truncate(long size) throws IOException { - ensureOpen(); - if (size < 0) - throw new IllegalArgumentException(); - if (size > size()) - return this; - if (!writable) - throw new NonWritableChannelException(); - synchronized (positionLock) { - int rv = -1; - long p = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return null; - - // get current position - do { - p = position0(fd, -1); - } while ((p == IOStatus.INTERRUPTED) && isOpen()); - if (!isOpen()) - return null; - assert p >= 0; - - // truncate file - do { - rv = nd.truncate(fd, size); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - if (!isOpen()) - return null; - - // [IKVM] in append mode we're not allowed to seek backwards, but the atomic append will honor the new file size - if (append) - return this; - - // 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 { - threads.remove(ti); - end(rv > -1); - assert IOStatus.check(rv); - } - } - } - - public void force(boolean metaData) throws IOException { - ensureOpen(); - int rv = -1; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return; - do { - rv = nd.force(fd, metaData); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - } finally { - threads.remove(ti); - end(rv > -1); - assert IOStatus.check(rv); - } - } - - private long transferToArbitraryChannel(long position, int icount, - WritableByteChannel target) - throws IOException - { - // 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; - } - } - - public long transferTo(long position, long count, - WritableByteChannel target) - throws IOException - { - ensureOpen(); - if (!target.isOpen()) - throw new ClosedChannelException(); - if (!readable) - throw new NonReadableChannelException(); - if (target instanceof FileChannelImpl && - !((FileChannelImpl)target).writable) - throw new NonWritableChannelException(); - if ((position < 0) || (count < 0)) - throw new IllegalArgumentException(); - long sz = size(); - if (position > sz) - return 0; - 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); - } - - private long transferFromFileChannel(FileChannelImpl src, - long position, long count) - throws IOException - { - if (!src.readable) - throw new NonReadableChannelException(); - return transferFromArbitraryChannel(src, position, count); - } - - private static final int TRANSFER_SIZE = 8192; - - private long transferFromArbitraryChannel(ReadableByteChannel src, - long position, long count) - throws IOException - { - // 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; - try { - 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; - } - } - - public long transferFrom(ReadableByteChannel src, - long position, long count) - throws IOException - { - ensureOpen(); - if (!src.isOpen()) - throw new ClosedChannelException(); - if (!writable) - throw new NonWritableChannelException(); - if ((position < 0) || (count < 0)) - throw new IllegalArgumentException(); - if (position > size()) - return 0; - if (src instanceof FileChannelImpl) - return transferFromFileChannel((FileChannelImpl)src, - position, count); - - return transferFromArbitraryChannel(src, position, count); - } - - public int read(ByteBuffer dst, long position) throws IOException { - if (dst == null) - throw new NullPointerException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (!readable) - throw new NonReadableChannelException(); - ensureOpen(); - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileReadBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return -1; - do { - n = IOUtil.read(fd, dst, position, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0); - end(n > 0); - assert IOStatus.check(n); - } - } - - public int write(ByteBuffer src, long position) throws IOException { - if (src == null) - throw new NullPointerException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (!writable) - throw new NonWritableChannelException(); - ensureOpen(); - int n = 0; - int ti = -1; - Object traceContext = IoTrace.fileWriteBegin(path); - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return -1; - do { - n = IOUtil.write(fd, src, position, nd, positionLock); - } while ((n == IOStatus.INTERRUPTED) && isOpen()); - return IOStatus.normalize(n); - } finally { - threads.remove(ti); - end(n > 0); - IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0); - assert IOStatus.check(n); - } - } - - - // -- Memory-mapped buffers -- - - private static class Unmapper - implements Runnable - { - // may be required to close file - private static final NativeDispatcher nd = new FileDispatcherImpl(); - - // keep track of mapped buffer usage - static volatile int count; - static volatile long totalSize; - static volatile long totalCapacity; - - private volatile long address; - private final long size; - private final int cap; - private final FileDescriptor fd; - - private Unmapper(long address, long size, int cap, - FileDescriptor fd) - { - assert (address != 0); - this.address = address; - this.size = size; - this.cap = cap; - this.fd = fd; - - synchronized (Unmapper.class) { - count++; - totalSize += size; - totalCapacity += cap; - } - } - - public void run() { - if (address == 0) - return; - unmap0(address, size); - address = 0; - - // if this mapping has a valid file descriptor then we close it - if (fd.valid()) { - try { - nd.close(fd); - } catch (IOException ignore) { - // nothing we can do - } - } - - synchronized (Unmapper.class) { - count--; - totalSize -= size; - totalCapacity -= cap; - } - } - } - - private static void unmap(MappedByteBuffer bb) { - Cleaner cl = ((DirectBuffer)bb).cleaner(); - if (cl != null) - cl.clean(); - } - - private static final int MAP_RO = 0; - private static final int MAP_RW = 1; - private static final int MAP_PV = 2; - - public MappedByteBuffer map(MapMode mode, long position, long size) - throws IOException - { - ensureOpen(); - 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 (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; - int ti = -1; - try { - begin(); - ti = threads.add(); - 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 = nd.truncate(fd, position + size); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); - } - if (size == 0) { - addr = 0; - // a valid file descriptor is not required - FileDescriptor dummy = new FileDescriptor(); - if ((!writable) || (imode == MAP_RO)) - return Util.newMappedByteBufferR(0, 0, dummy, null); - else - return Util.newMappedByteBuffer(0, 0, dummy, 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); - } - } - - // On Windows, and potentially other platforms, we need an open - // file descriptor for some mapping operations. - FileDescriptor mfd; - try { - mfd = nd.duplicateForMapping(fd); - } catch (IOException ioe) { - unmap0(addr, mapSize); - throw ioe; - } - - assert (IOStatus.checkAll(addr)); - assert (addr % allocationGranularity == 0); - int isize = (int)size; - Unmapper um = new Unmapper(addr, mapSize, isize, mfd); - if ((!writable) || (imode == MAP_RO)) { - return Util.newMappedByteBufferR(isize, - addr + pagePosition, - mfd, - um); - } else { - return Util.newMappedByteBuffer(isize, - addr + pagePosition, - mfd, - um); - } - } finally { - threads.remove(ti); - end(IOStatus.checkAll(addr)); - } - } - - /** - * Invoked by sun.management.ManagementFactoryHelper to create the management - * interface for mapped buffers. - */ - public static sun.misc.JavaNioAccess.BufferPool getMappedBufferPool() { - return new sun.misc.JavaNioAccess.BufferPool() { - @Override - public String getName() { - return "mapped"; - } - @Override - public long getCount() { - return Unmapper.count; - } - @Override - public long getTotalCapacity() { - return Unmapper.totalCapacity; - } - @Override - public long getMemoryUsed() { - return Unmapper.totalSize; - } - }; - } - - // -- Locks -- - - - - // keeps track of locks on this file - private volatile FileLockTable fileLockTable; - - // indicates if file locks are maintained system-wide (as per spec) - private static boolean isSharedFileLockTable; - - // indicates if the disableSystemWideOverlappingFileLockCheck property - // has been checked - private static volatile boolean propertyChecked; - - // The lock list in J2SE 1.4/5.0 was local to each FileChannel instance so - // the overlap check wasn't system wide when there were multiple channels to - // the same file. This property is used to get 1.4/5.0 behavior if desired. - private static boolean isSharedFileLockTable() { - if (!propertyChecked) { - synchronized (FileChannelImpl.class) { - if (!propertyChecked) { - String value = AccessController.doPrivileged( - new GetPropertyAction( - "sun.nio.ch.disableSystemWideOverlappingFileLockCheck")); - isSharedFileLockTable = ((value == null) || value.equals("false")); - propertyChecked = true; - } - } - } - return isSharedFileLockTable; - } - - private FileLockTable fileLockTable() throws IOException { - if (fileLockTable == null) { - synchronized (this) { - if (fileLockTable == null) { - if (isSharedFileLockTable()) { - int ti = threads.add(); - try { - ensureOpen(); - fileLockTable = FileLockTable.newSharedFileLockTable(this, fd); - } finally { - threads.remove(ti); - } - } else { - fileLockTable = new SimpleFileLockTable(); - } - } - } - } - return fileLockTable; - } - - public FileLock lock(long position, long size, boolean shared) - throws IOException - { - ensureOpen(); - 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 completed = false; - int ti = -1; - try { - begin(); - ti = threads.add(); - if (!isOpen()) - return null; - int n; - do { - n = nd.lock(fd, true, position, size, shared); - } while ((n == FileDispatcher.INTERRUPTED) && isOpen()); - if (isOpen()) { - if (n == FileDispatcher.RET_EX_LOCK) { - assert shared; - FileLockImpl fli2 = new FileLockImpl(this, position, size, - false); - flt.replace(fli, fli2); - fli = fli2; - } - completed = true; - } - } finally { - if (!completed) - flt.remove(fli); - threads.remove(ti); - try { - end(completed); - } catch (ClosedByInterruptException e) { - throw new FileLockInterruptionException(); - } - } - return fli; - } - - public FileLock tryLock(long position, long size, boolean shared) - throws IOException - { - ensureOpen(); - 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; - - int ti = threads.add(); - try { - try { - ensureOpen(); - result = nd.lock(fd, false, position, size, shared); - } catch (IOException e) { - flt.remove(fli); - throw e; - } - if (result == FileDispatcher.NO_LOCK) { - flt.remove(fli); - return null; - } - if (result == FileDispatcher.RET_EX_LOCK) { - assert shared; - FileLockImpl fli2 = new FileLockImpl(this, position, size, - false); - flt.replace(fli, fli2); - return fli2; - } - return fli; - } finally { - threads.remove(ti); - } - } - - void release(FileLockImpl fli) throws IOException { - int ti = threads.add(); - try { - ensureOpen(); - nd.release(fd, fli.position(), fli.size()); - } finally { - threads.remove(ti); - } - assert fileLockTable != null; - fileLockTable.remove(fli); - } - - // -- File lock support -- - - /** - * A simple file lock table that maintains a list of FileLocks obtained by a - * FileChannel. Use to get 1.4/5.0 behaviour. - */ - private static class SimpleFileLockTable extends FileLockTable { - // synchronize on list for access - private final List<FileLock> lockList = new ArrayList<FileLock>(2); - - public SimpleFileLockTable() { - } - - private void checkList(long position, long size) - throws OverlappingFileLockException - { - assert Thread.holdsLock(lockList); - for (FileLock fl: lockList) { - if (fl.overlaps(position, size)) { - throw new OverlappingFileLockException(); - } - } - } - - public void add(FileLock fl) throws OverlappingFileLockException { - synchronized (lockList) { - checkList(fl.position(), fl.size()); - lockList.add(fl); - } - } - - public void remove(FileLock fl) { - synchronized (lockList) { - lockList.remove(fl); - } - } - - public List<FileLock> removeAll() { - synchronized(lockList) { - List<FileLock> result = new ArrayList<FileLock>(lockList); - lockList.clear(); - return result; - } - } - - public void replace(FileLock fl1, FileLock fl2) { - synchronized (lockList) { - lockList.remove(fl1); - lockList.add(fl2); - } - } - } - - // -- Native methods -- - - // 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); - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - 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); - } - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - 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; - 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, - // instead of whatever MAP_FAILED is defined to on the particular system we're running on, - // common values for MAP_FAILED are 0 and -1, so we test for these. - if (p.Equals(IntPtr.Zero) || p.Equals(new IntPtr(-1))) - { - throw new IOException("file mapping failed"); - } - cli.System.GC.AddMemoryPressure(length); - return p.ToInt64(); - } - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native SafeFileHandle CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, int flProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, String lpName); - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native IntPtr MapViewOfFile(SafeFileHandle hFileMapping, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, IntPtr dwNumberOfBytesToMap); - - @DllImportAttribute.Annotation("kernel32") - private static native int UnmapViewOfFile(IntPtr lpBaseAddress); - - @DllImportAttribute.Annotation("ikvm-native") - private static native int ikvm_munmap(IntPtr address, int size); - - @DllImportAttribute.Annotation("ikvm-native") - private static native IntPtr ikvm_mmap(SafeFileHandle handle, byte writeable, byte copy_on_write, long position, int size); - - // Removes an existing mapping - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - static int unmap0(long address, long length) - { - if (win32) - UnmapViewOfFile(IntPtr.op_Explicit(address)); - else - ikvm_munmap(IntPtr.op_Explicit(address), (int)length); - cli.System.GC.RemoveMemoryPressure(length); - return 0; - } - - // Sets or reports this file's position - // If offset is -1, the current position is returned - // 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; - } -} diff --git a/openjdk/sun/nio/ch/FileDispatcherImpl.java b/openjdk/sun/nio/ch/FileDispatcherImpl.java deleted file mode 100644 index 971df81b..00000000 --- a/openjdk/sun/nio/ch/FileDispatcherImpl.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.nio.ByteBuffer; -import cli.Microsoft.Win32.SafeHandles.SafeFileHandle; -import cli.System.IntPtr; -import cli.System.IO.FileStream; -import cli.System.Runtime.InteropServices.DllImportAttribute; -import cli.System.Runtime.InteropServices.StructLayoutAttribute; -import cli.System.Runtime.InteropServices.LayoutKind; -import cli.System.Runtime.InteropServices.Marshal; -import static ikvm.internal.Util.WINDOWS; - -class FileDispatcherImpl extends FileDispatcher -{ - /** - * Indicates if the dispatcher should first advance the file position - * to the end of file when writing. - */ - private final boolean append; - - FileDispatcherImpl(boolean append) { - this.append = append; - } - - FileDispatcherImpl() { - this(false); - } - - int read(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException { - return fd.readBytes(buf, offset, length); - } - - int write(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException { - fd.writeBytes(buf, offset, length); - return length; - } - - long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException { - long totalRead = 0; - try - { - for (int i = offset; i < offset + length; i++) - { - int size = bufs[i].remaining(); - if (size > 0) - { - int read = IOUtil.read(fd, bufs[i], -1, this, this); - if (read < 0) - { - break; - } - totalRead += read; - if (read < size || fd.available() == 0) - { - break; - } - } - } - } - catch (IOException x) - { - if (totalRead == 0) - { - throw x; - } - } - return totalRead; - } - - long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException { - long totalWritten = 0; - try - { - for (int i = offset; i < offset + length; i++) - { - int size = bufs[i].remaining(); - if (size > 0) - { - int written = IOUtil.write(fd, bufs[i], -1, this, this); - totalWritten += written; - if (written < size) - { - break; - } - } - } - } - catch (IOException x) - { - if (totalWritten == 0) - { - throw x; - } - } - return totalWritten; - } - - int force(FileDescriptor fd, boolean metaData) throws IOException { - fd.sync(); - return 0; - } - - int truncate(FileDescriptor fd, long size) throws IOException { - if (append) { - // HACK in append mode we're not allowed to truncate, so we try to reopen the file and truncate that - try (FileOutputStream fos = new FileOutputStream(((FileStream)fd.getStream()).get_Name())) { - fos.getFD().setLength(size); - } - } else { - fd.setLength(size); - } - return 0; - } - - long size(FileDescriptor fd) throws IOException { - return fd.length(); - } - - @StructLayoutAttribute.Annotation(LayoutKind.__Enum.Sequential) - private static final class OVERLAPPED extends cli.System.Object - { - IntPtr Internal; - IntPtr InternalHigh; - int OffsetLow; - int OffsetHigh; - IntPtr hEvent; - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - int lock(FileDescriptor fd, boolean blocking, long pos, long size, - boolean shared) throws IOException - { - FileStream fs = (FileStream)fd.getStream(); - if (WINDOWS) - { - 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 = 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()); - } - } - } - - @cli.System.Security.SecuritySafeCriticalAttribute.Annotation - void release(FileDescriptor fd, long pos, long size) throws IOException { - FileStream fs = (FileStream)fd.getStream(); - if (WINDOWS) - { - int ERROR_NOT_LOCKED = 158; - 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 && Marshal.GetLastWin32Error() != ERROR_NOT_LOCKED) - { - 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.IO.IOException x) - { - if (!NotLockedHack.isErrorNotLocked(x)) - { - throw new IOException(x.getMessage()); - } - } - catch (cli.System.ArgumentOutOfRangeException - | cli.System.ObjectDisposedException x) - { - throw new IOException(x.getMessage()); - } - } - } - - static class NotLockedHack { - private static String msg; - static { - try { - File tmp = File.createTempFile("lock", null); - try (FileStream fs = new FileStream(tmp.getPath(), cli.System.IO.FileMode.wrap(cli.System.IO.FileMode.Create))) { - try { - if (false) throw new cli.System.IO.IOException(); - fs.Unlock(0, 1); - } catch (cli.System.IO.IOException x) { - msg = x.get_Message(); - } - } - tmp.delete(); - } catch (Throwable _) { - } - } - static boolean isErrorNotLocked(cli.System.IO.IOException x) { - return x.get_Message().equals(msg); - } - } - - - void close(FileDescriptor fd) throws IOException { - fd.close(); - } - - FileDescriptor duplicateForMapping(FileDescriptor fd) throws IOException { - // we return a dummy FileDescriptor, because we don't need it for mapping operations - // and we don't want the original to be closed - return new FileDescriptor(); - } - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native int LockFileEx(SafeFileHandle hFile, int dwFlags, int dwReserved, int nNumberOfBytesToLockLow, int nNumberOfBytesToLockHigh, OVERLAPPED lpOverlapped); - - @DllImportAttribute.Annotation(value="kernel32", SetLastError=true) - private static native int UnlockFileEx(SafeFileHandle hFile, int dwReserved, int nNumberOfBytesToUnlockLow, int nNumberOfBytesToUnlockHigh, OVERLAPPED lpOverlapped); -} diff --git a/openjdk/sun/nio/ch/FileKey.java b/openjdk/sun/nio/ch/FileKey.java deleted file mode 100644 index 4feec5d3..00000000 --- a/openjdk/sun/nio/ch/FileKey.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (C) 2007 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ -package sun.nio.ch; - -import java.io.File; -import java.io.FileDescriptor; -import java.io.IOException; - -public class FileKey -{ - private String path; - - 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; - } - - public int hashCode() - { - return path.hashCode(); - } - - public boolean equals(Object obj) - { - 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 deleted file mode 100644 index 38325371..00000000 --- a/openjdk/sun/nio/ch/IOUtil.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.net.*; -import java.nio.ByteBuffer; -import java.nio.channels.*; -import java.nio.channels.spi.*; - - -/** - * File-descriptor based I/O utilities that are shared by NIO classes. - */ - -class IOUtil { - - 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; - } - } - - static void configureBlocking(FileDescriptor fd, boolean blocking) throws IOException - { - fd.setSocketBlocking(blocking); - } - - // this is a dummy method to allow us to use unmodified socket channel impls - static int fdVal(FileDescriptor fd) - { - return 0xbadc0de; - } - - static int read(FileDescriptor fd, ByteBuffer dst, long position, - NativeDispatcher nd, Object lock) - throws IOException - { - if (dst.isReadOnly()) - throw new IllegalArgumentException("Read-only buffer"); - - if (position != -1) - { - synchronized (lock) - { - long prevpos = fd.getFilePointer(); - try - { - fd.seek(position); - return read(fd, dst, -1, nd, null); - } - finally - { - fd.seek(prevpos); - } - } - } - - if (dst.hasArray()) - { - byte[] buf = dst.array(); - int len = nd.read(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 = nd.read(fd, buf, 0, buf.length); - if (len > 0) - { - dst.put(buf, 0, len); - } - return len; - } - } - - static long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length, NativeDispatcher nd) - throws IOException - { - return nd.read(fd, bufs, offset, length); - } - - static int write(FileDescriptor fd, ByteBuffer src, long position, - NativeDispatcher nd, Object lock) - throws IOException - { - if (position != -1) - { - synchronized (lock) - { - long prevpos = fd.getFilePointer(); - try - { - fd.seek(position); - return write(fd, src, -1, nd, null); - } - finally - { - fd.seek(prevpos); - } - } - } - - if (src.hasArray()) - { - byte[] buf = src.array(); - int len = nd.write(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); - src.position(pos); - int len = nd.write(fd, buf, 0, buf.length); - if (len > 0) - { - src.position(pos + len); - } - return len; - } - } - - static long write(FileDescriptor fd, ByteBuffer[] bufs, NativeDispatcher nd) - throws IOException - { - return nd.write(fd, bufs, 0, bufs.length); - } - - static long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length, NativeDispatcher nd) - throws IOException - { - return nd.write(fd, bufs, offset, length); - } -} diff --git a/openjdk/sun/nio/ch/Iocp.java b/openjdk/sun/nio/ch/Iocp.java deleted file mode 100644 index b74b0a8f..00000000 --- a/openjdk/sun/nio/ch/Iocp.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.nio.channels.spi.AsynchronousChannelProvider; -import java.io.Closeable; -import java.io.IOException; -import java.io.FileDescriptor; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import ikvm.internal.NotYetImplementedError; - -/** - * Windows implementation of AsynchronousChannelGroup encapsulating an I/O - * completion port. - */ - -class Iocp extends AsynchronousChannelGroupImpl { - private static final boolean supportsThreadAgnosticIo; - - // true if port has been closed - private boolean closed; - - // the set of "stale" OVERLAPPED structures. These OVERLAPPED structures - // relate to I/O operations where the completion notification was not - // received in a timely manner after the channel is closed. - private final Set<Long> staleIoSet = new HashSet<Long>(); - - Iocp(AsynchronousChannelProvider provider, ThreadPool pool) - throws IOException - { - super(provider, pool); - } - - Iocp start() { - return this; - } - - /* - * Channels implements this interface support overlapped I/O and can be - * associated with a completion port. - */ - static interface OverlappedChannel extends Closeable { - /** - * Returns a reference to the pending I/O result. - */ - <V,A> PendingFuture<V,A> getByOverlapped(long overlapped); - } - - /** - * Indicates if this operating system supports thread agnostic I/O. - */ - static boolean supportsThreadAgnosticIo() { - return supportsThreadAgnosticIo; - } - - // release all resources - void implClose() { - synchronized (this) { - if (closed) - return; - closed = true; - } - } - - @Override - boolean isEmpty() { - return true; - } - - @Override - final Object attachForeignChannel(final Channel channel, FileDescriptor fdObj) - throws IOException - { - throw new NotYetImplementedError(); - } - - @Override - final void detachForeignChannel(Object key) { - throw new NotYetImplementedError(); - } - - @Override - void closeAllChannels() { - } - - @Override - void executeOnHandlerTask(Runnable task) { - throw new NotYetImplementedError(); - } - - @Override - void shutdownHandlerTasks() { - } - - /** - * The handler for consuming the result of an asynchronous I/O operation. - */ - static interface ResultHandler { - /** - * Invoked if the I/O operation completes successfully. - */ - public void completed(int bytesTransferred, boolean canInvokeDirect); - - /** - * Invoked if the I/O operation fails. - */ - public void failed(int error, IOException ioe); - } - - static { - supportsThreadAgnosticIo = true; - } -} diff --git a/openjdk/sun/nio/ch/NativeDispatcher.java b/openjdk/sun/nio/ch/NativeDispatcher.java deleted file mode 100644 index 7f523265..00000000 --- a/openjdk/sun/nio/ch/NativeDispatcher.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.nio.ByteBuffer; - -/** - * Allows different platforms to call different native methods - * for read and write operations. - */ - -abstract class NativeDispatcher -{ - abstract int read(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException; - - abstract int write(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException; - - abstract long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - abstract long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - abstract void close(FileDescriptor fd) throws IOException; - - // Prepare the given fd for closing by duping it to a known internal fd - // that's already closed. This is necessary on some operating systems - // (Solaris and Linux) to prevent fd recycling. - // - void preClose(FileDescriptor fd) throws IOException { - // Do nothing by default; this is only needed on Unix - } - -} diff --git a/openjdk/sun/nio/ch/Net.java b/openjdk/sun/nio/ch/Net.java deleted file mode 100644 index d9ab0f0f..00000000 --- a/openjdk/sun/nio/ch/Net.java +++ /dev/null @@ -1,609 +0,0 @@ -/* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.net.*; -import java.nio.channels.*; -import java.util.*; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; - - -class Net { // package-private - - private Net() { } - - // unspecified protocol family - static final ProtocolFamily UNSPEC = new ProtocolFamily() { - public String name() { - return "UNSPEC"; - } - }; - - // Value of jdk.net.revealLocalAddress - private static boolean revealLocalAddress; - - // True if jdk.net.revealLocalAddress had been read - private static volatile boolean propRevealLocalAddress; - - // set to true if exclusive binding is on for Windows - private static final boolean exclusiveBind; - - static { - int availLevel = isExclusiveBindAvailable(); - if (availLevel >= 0) { - String exclBindProp = - java.security.AccessController.doPrivileged( - new PrivilegedAction<String>() { - @Override - public String run() { - return System.getProperty( - "sun.net.useExclusiveBind"); - } - }); - if (exclBindProp != null) { - exclusiveBind = exclBindProp.length() == 0 ? - true : Boolean.parseBoolean(exclBindProp); - } else if (availLevel == 1) { - exclusiveBind = true; - } else { - exclusiveBind = false; - } - } else { - exclusiveBind = false; - } - } - - // -- Miscellaneous utilities -- - - private static volatile boolean checkedIPv6 = false; - private static volatile boolean isIPv6Available; - - /** - * Tells whether dual-IPv4/IPv6 sockets should be used. - */ - static boolean isIPv6Available() { - if (!checkedIPv6) { - isIPv6Available = isIPv6Available0(); - checkedIPv6 = true; - } - return isIPv6Available; - } - - /** - * Returns true if exclusive binding is on - */ - static boolean useExclusiveBind() { - return exclusiveBind; - } - - /** - * Tells whether IPv6 sockets can join IPv4 multicast groups - */ - static boolean canIPv6SocketJoinIPv4Group() { - return canIPv6SocketJoinIPv4Group0(); - } - - /** - * Tells whether {@link #join6} can be used to join an IPv4 - * multicast group (IPv4 group as IPv4-mapped IPv6 address) - */ - static boolean canJoin6WithIPv4Group() { - return canJoin6WithIPv4Group0(); - } - - static InetSocketAddress checkAddress(SocketAddress sa) { - if (sa == null) - throw new NullPointerException(); - if (!(sa instanceof InetSocketAddress)) - throw new UnsupportedAddressTypeException(); // ## needs arg - InetSocketAddress isa = (InetSocketAddress)sa; - if (isa.isUnresolved()) - throw new UnresolvedAddressException(); // ## needs arg - InetAddress addr = isa.getAddress(); - if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) - throw new IllegalArgumentException("Invalid address type"); - return isa; - } - - static InetSocketAddress asInetSocketAddress(SocketAddress sa) { - if (!(sa instanceof InetSocketAddress)) - throw new UnsupportedAddressTypeException(); - return (InetSocketAddress)sa; - } - - static void translateToSocketException(Exception x) - 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 NotYetConnectedException) - nx = new SocketException("Socket is not connected"); - 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; - else if (nx instanceof RuntimeException) - throw (RuntimeException)nx; - else - throw new Error("Untranslated exception", nx); - } - - static void translateException(Exception x, - boolean unknownHostForUnresolved) - throws IOException - { - if (x instanceof IOException) - throw (IOException)x; - // Throw UnknownHostException from here since it cannot - // be thrown as a SocketException - if (unknownHostForUnresolved && - (x instanceof UnresolvedAddressException)) - { - throw new UnknownHostException(); - } - translateToSocketException(x); - } - - static void translateException(Exception x) - throws IOException - { - translateException(x, false); - } - - /** - * Returns the local address after performing a SecurityManager#checkConnect. - */ - static InetSocketAddress getRevealedLocalAddress(InetSocketAddress addr) { - SecurityManager sm = System.getSecurityManager(); - if (addr == null || sm == null) - return addr; - - if (!getRevealLocalAddress()) { - // Return loopback address only if security check fails - try{ - sm.checkConnect(addr.getAddress().getHostAddress(), -1); - //Security check passed - } catch (SecurityException e) { - //Return loopback address - addr = getLoopbackAddress(addr.getPort()); - } - } - return addr; - } - - static String getRevealedLocalAddressAsString(InetSocketAddress addr) { - if (!getRevealLocalAddress() && System.getSecurityManager() != null) - addr = getLoopbackAddress(addr.getPort()); - return addr.toString(); - } - - private static boolean getRevealLocalAddress() { - if (!propRevealLocalAddress) { - try { - revealLocalAddress = Boolean.parseBoolean( - AccessController.doPrivileged( - new PrivilegedExceptionAction<String>() { - public String run() { - return System.getProperty( - "jdk.net.revealLocalAddress"); - } - })); - - } catch (Exception e) { - // revealLocalAddress is false - } - propRevealLocalAddress = true; - } - return revealLocalAddress; - } - - private static InetSocketAddress getLoopbackAddress(int port) { - return new InetSocketAddress(InetAddress.getLoopbackAddress(), - port); - } - - /** - * Returns any IPv4 address of the given network interface, or - * null if the interface does not have any IPv4 addresses. - */ - static Inet4Address anyInet4Address(final NetworkInterface interf) { - return AccessController.doPrivileged(new PrivilegedAction<Inet4Address>() { - public Inet4Address run() { - Enumeration<InetAddress> addrs = interf.getInetAddresses(); - while (addrs.hasMoreElements()) { - InetAddress addr = addrs.nextElement(); - if (addr instanceof Inet4Address) { - return (Inet4Address)addr; - } - } - return null; - } - }); - } - - /** - * Returns an IPv4 address as an int. - */ - static int inet4AsInt(InetAddress ia) { - if (ia instanceof Inet4Address) { - byte[] addr = ia.getAddress(); - int address = addr[3] & 0xFF; - address |= ((addr[2] << 8) & 0xFF00); - address |= ((addr[1] << 16) & 0xFF0000); - address |= ((addr[0] << 24) & 0xFF000000); - return address; - } - throw new AssertionError("Should not reach here"); - } - - /** - * Returns an InetAddress from the given IPv4 address - * represented as an int. - */ - static InetAddress inet4FromInt(int address) { - byte[] addr = new byte[4]; - addr[0] = (byte) ((address >>> 24) & 0xFF); - addr[1] = (byte) ((address >>> 16) & 0xFF); - addr[2] = (byte) ((address >>> 8) & 0xFF); - addr[3] = (byte) (address & 0xFF); - try { - return InetAddress.getByAddress(addr); - } catch (UnknownHostException uhe) { - throw new AssertionError("Should not reach here"); - } - } - - /** - * Returns an IPv6 address as a byte array - */ - static byte[] inet6AsByteArray(InetAddress ia) { - if (ia instanceof Inet6Address) { - return ia.getAddress(); - } - - // need to construct IPv4-mapped address - if (ia instanceof Inet4Address) { - byte[] ip4address = ia.getAddress(); - byte[] address = new byte[16]; - address[10] = (byte)0xff; - address[11] = (byte)0xff; - address[12] = ip4address[0]; - address[13] = ip4address[1]; - address[14] = ip4address[2]; - address[15] = ip4address[3]; - return address; - } - - throw new AssertionError("Should not reach here"); - } - - // -- Socket options - - static void setSocketOption(FileDescriptor fd, ProtocolFamily family, - SocketOption<?> name, Object value) - throws IOException - { - if (value == null) - throw new IllegalArgumentException("Invalid option value"); - - // only simple values supported by this method - Class<?> type = name.type(); - if (type != Integer.class && type != Boolean.class) - throw new AssertionError("Should not reach here"); - - // special handling - if (name == StandardSocketOptions.SO_RCVBUF || - name == StandardSocketOptions.SO_SNDBUF) - { - int i = ((Integer)value).intValue(); - if (i < 0) - throw new IllegalArgumentException("Invalid send/receive buffer size"); - } - if (name == StandardSocketOptions.SO_LINGER) { - int i = ((Integer)value).intValue(); - if (i < 0) - value = Integer.valueOf(-1); - if (i > 65535) - value = Integer.valueOf(65535); - } - if (name == StandardSocketOptions.IP_TOS) { - int i = ((Integer)value).intValue(); - if (i < 0 || i > 255) - throw new IllegalArgumentException("Invalid IP_TOS value"); - } - if (name == StandardSocketOptions.IP_MULTICAST_TTL) { - int i = ((Integer)value).intValue(); - if (i < 0 || i > 255) - throw new IllegalArgumentException("Invalid TTL/hop value"); - } - - // map option name to platform level/name - OptionKey key = SocketOptionRegistry.findOption(name, family); - if (key == null) - throw new AssertionError("Option not found"); - - int arg; - if (type == Integer.class) { - arg = ((Integer)value).intValue(); - } else { - boolean b = ((Boolean)value).booleanValue(); - arg = (b) ? 1 : 0; - } - - boolean mayNeedConversion = (family == UNSPEC); - setIntOption0(fd, mayNeedConversion, key.level(), key.name(), arg); - } - - static Object getSocketOption(FileDescriptor fd, ProtocolFamily family, - SocketOption<?> name) - throws IOException - { - Class<?> type = name.type(); - - // only simple values supported by this method - if (type != Integer.class && type != Boolean.class) - throw new AssertionError("Should not reach here"); - - // map option name to platform level/name - OptionKey key = SocketOptionRegistry.findOption(name, family); - if (key == null) - throw new AssertionError("Option not found"); - - boolean mayNeedConversion = (family == UNSPEC); - int value = getIntOption0(fd, mayNeedConversion, key.level(), key.name()); - - if (type == Integer.class) { - return Integer.valueOf(value); - } else { - return (value == 0) ? Boolean.FALSE : Boolean.TRUE; - } - } - - // -- Socket operations -- - - private static native boolean isIPv6Available0(); - - /* - * Returns 1 for Windows versions that support exclusive binding by default, 0 - * for those that do not, and -1 for Solaris/Linux/Mac OS - */ - private static native int isExclusiveBindAvailable(); - - private static native boolean canIPv6SocketJoinIPv4Group0(); - - private static native boolean canJoin6WithIPv4Group0(); - - static FileDescriptor socket(boolean stream) throws IOException { - return socket(UNSPEC, stream); - } - - static FileDescriptor socket(ProtocolFamily family, boolean stream) - throws IOException { - boolean preferIPv6 = isIPv6Available() && - (family != StandardProtocolFamily.INET); - return socket0(preferIPv6, stream, false); - } - - static FileDescriptor serverSocket(boolean stream) { - return socket0(isIPv6Available(), stream, true); - } - - // Due to oddities SO_REUSEADDR on windows reuse is ignored - private static native FileDescriptor socket0(boolean preferIPv6, boolean stream, boolean reuse); - - static void bind(FileDescriptor fd, InetAddress addr, int port) - throws IOException - { - bind(UNSPEC, fd, addr, port); - } - - static void bind(ProtocolFamily family, FileDescriptor fd, - InetAddress addr, int port) throws IOException - { - boolean preferIPv6 = isIPv6Available() && - (family != StandardProtocolFamily.INET); - bind0(fd, preferIPv6, exclusiveBind, addr, port); - } - - private static native void bind0(FileDescriptor fd, boolean preferIPv6, - boolean useExclBind, InetAddress addr, - int port) - throws IOException; - - static native void listen(FileDescriptor fd, int backlog) throws IOException; - - static int connect(FileDescriptor fd, InetAddress remote, int remotePort) - throws IOException - { - return connect(UNSPEC, fd, remote, remotePort); - } - - static int connect(ProtocolFamily family, FileDescriptor fd, InetAddress remote, int remotePort) - throws IOException - { - boolean preferIPv6 = isIPv6Available() && - (family != StandardProtocolFamily.INET); - return connect0(preferIPv6, fd, remote, remotePort); - } - - private static native int connect0(boolean preferIPv6, - FileDescriptor fd, - InetAddress remote, - int remotePort) - throws IOException; - - - public final static int SHUT_RD = 0; - public final static int SHUT_WR = 1; - public final static int SHUT_RDWR = 2; - - static native void shutdown(FileDescriptor fd, int how) throws IOException; - - private static native int localPort(FileDescriptor fd) - throws IOException; - - private static native InetAddress localInetAddress(FileDescriptor fd) - throws IOException; - - static InetSocketAddress localAddress(FileDescriptor fd) - throws IOException - { - return new InetSocketAddress(localInetAddress(fd), localPort(fd)); - } - - private static native int remotePort(FileDescriptor fd) - throws IOException; - - private static native InetAddress remoteInetAddress(FileDescriptor fd) - throws IOException; - - static InetSocketAddress remoteAddress(FileDescriptor fd) - throws IOException - { - return new InetSocketAddress(remoteInetAddress(fd), remotePort(fd)); - } - - private static native int getIntOption0(FileDescriptor fd, boolean mayNeedConversion, - int level, int opt) - throws IOException; - - private static native void setIntOption0(FileDescriptor fd, boolean mayNeedConversion, - int level, int opt, int arg) - throws IOException; - - // -- Multicast support -- - - - /** - * Join IPv4 multicast group - */ - static int join4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - return joinOrDrop4(true, fd, group, interf, source); - } - - /** - * Drop membership of IPv4 multicast group - */ - static void drop4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - joinOrDrop4(false, fd, group, interf, source); - } - - private static native int joinOrDrop4(boolean join, FileDescriptor fd, int group, int interf, int source) - throws IOException; - - /** - * Block IPv4 source - */ - static int block4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - return blockOrUnblock4(true, fd, group, interf, source); - } - - /** - * Unblock IPv6 source - */ - static void unblock4(FileDescriptor fd, int group, int interf, int source) - throws IOException - { - blockOrUnblock4(false, fd, group, interf, source); - } - - private static native int blockOrUnblock4(boolean block, FileDescriptor fd, int group, - int interf, int source) - throws IOException; - - /** - * Join IPv6 multicast group - */ - static int join6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - return joinOrDrop6(true, fd, group, index, source); - } - - /** - * Drop membership of IPv6 multicast group - */ - static void drop6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - joinOrDrop6(false, fd, group, index, source); - } - - private static native int joinOrDrop6(boolean join, FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException; - - /** - * Block IPv6 source - */ - static int block6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - return blockOrUnblock6(true, fd, group, index, source); - } - - /** - * Unblock IPv6 source - */ - static void unblock6(FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException - { - blockOrUnblock6(false, fd, group, index, source); - } - - static native int blockOrUnblock6(boolean block, FileDescriptor fd, byte[] group, int index, byte[] source) - throws IOException; - - static native void setInterface4(FileDescriptor fd, int interf) throws IOException; - - static native int getInterface4(FileDescriptor fd) throws IOException; - - static native void setInterface6(FileDescriptor fd, int index) throws IOException; - - static native int getInterface6(FileDescriptor fd) throws IOException; - -} diff --git a/openjdk/sun/nio/ch/PollArrayWrapper.java b/openjdk/sun/nio/ch/PollArrayWrapper.java deleted file mode 100644 index 72ed9adc..00000000 --- a/openjdk/sun/nio/ch/PollArrayWrapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -class PollArrayWrapper -{ - static final short POLLIN = 0x0001; - static final short POLLCONN = 0x0002; - static final short POLLOUT = 0x0004; - static final short POLLERR = 0x0008; - static final short POLLHUP = 0x0010; - static final short POLLNVAL = 0x0020; - static final short POLLREMOVE = 0x0800; -} diff --git a/openjdk/sun/nio/ch/SelectionKeyImpl.java b/openjdk/sun/nio/ch/SelectionKeyImpl.java deleted file mode 100644 index 5edc3005..00000000 --- a/openjdk/sun/nio/ch/SelectionKeyImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - Copyright (C) 2002, 2003, 2004, 2005, 2006 Jeroen Frijters - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jeroen Frijters - jeroen@frijters.net - -*/ -package sun.nio.ch; - -import java.nio.channels.CancelledKeyException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.AbstractSelectionKey; - -final class SelectionKeyImpl extends AbstractSelectionKey -{ - final SelChImpl channel; - final SelectorImpl selector; - private final cli.System.Net.Sockets.Socket socket; - private int readyOps; - private volatile int interestOps; - - SelectionKeyImpl(SelChImpl ch, SelectorImpl sel) - { - this.channel = ch; - this.selector = sel; - socket = ch.getFD().getSocket(); - } - - public SelectableChannel channel() - { - return (SelectableChannel)channel; - } - - public int readyOps() - { - if (!isValid()) - throw new CancelledKeyException(); - - return readyOps; - } - - void readyOps(int ops) - { - readyOps = ops; - } - - public synchronized int interestOps() - { - if (!isValid()) - throw new CancelledKeyException(); - - return interestOps; - } - - public synchronized SelectionKey interestOps(int ops) - { - if (!isValid()) - throw new CancelledKeyException(); - - if ((ops & ~channel.validOps()) != 0) - throw new IllegalArgumentException(); - - interestOps = ops; - return this; - } - - public Selector selector() - { - return selector; - } - - cli.System.Net.Sockets.Socket getSocket() - { - return socket; - } - - void nioReadyOps(int ops) - { - readyOps = ops; - } - - int nioReadyOps() - { - return readyOps; - } - - int nioInterestOps() - { - return interestOps; - } - - SelectionKey nioInterestOps(int ops) - { - if ((ops & ~channel().validOps()) != 0) - throw new IllegalArgumentException(); - channel.translateAndSetInterestOps(ops, this); - interestOps = ops; - return this; - } -} diff --git a/openjdk/sun/nio/ch/SocketDispatcher.java b/openjdk/sun/nio/ch/SocketDispatcher.java deleted file mode 100644 index 7d408326..00000000 --- a/openjdk/sun/nio/ch/SocketDispatcher.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.io.*; -import java.net.SocketException; -import java.net.SocketUtil; -import java.nio.ByteBuffer; -import cli.System.Net.Sockets.SocketFlags; - -/** - * Allows different platforms to call different native methods - * for read and write operations. - */ - -class SocketDispatcher extends NativeDispatcher -{ - int read(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() == SocketUtil.WSAESHUTDOWN) - { - // the socket was shutdown, so we have to return EOF - return IOStatus.EOF; - } - else if (x.get_ErrorCode() == SocketUtil.WSAEWOULDBLOCK) - { - // nothing to read and would block - return IOStatus.UNAVAILABLE; - } - throw SocketUtil.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } - } - - int write(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() == SocketUtil.WSAEWOULDBLOCK) - { - return IOStatus.UNAVAILABLE; - } - throw SocketUtil.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new SocketException("Socket is closed"); - } - } - - native long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - native long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException; - - void close(FileDescriptor fd) throws IOException { - } - - void preClose(FileDescriptor fd) throws IOException { - closeImpl(fd); - } - - static void closeImpl(FileDescriptor fd) 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 java.net.SocketUtil.convertSocketExceptionToIOException(x); - } - catch (cli.System.ObjectDisposedException x1) - { - throw new java.net.SocketException("Socket is closed"); - } - } -} diff --git a/openjdk/sun/nio/ch/SocketOptionRegistry.java b/openjdk/sun/nio/ch/SocketOptionRegistry.java deleted file mode 100644 index 83887fbc..00000000 --- a/openjdk/sun/nio/ch/SocketOptionRegistry.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - * - */ - -package sun.nio.ch; -import java.net.SocketOption; -import java.net.StandardSocketOptions; -import java.net.ProtocolFamily; -import java.net.StandardProtocolFamily; -import java.util.Map; -import java.util.HashMap; -import cli.System.Net.Sockets.SocketOptionLevel; -import cli.System.Net.Sockets.SocketOptionName; - -class SocketOptionRegistry { - private SocketOptionRegistry() { } - private static class RegistryKey { - private final SocketOption<?> name; - private final ProtocolFamily family; - RegistryKey(SocketOption<?> name, ProtocolFamily family) { - this.name = name; - this.family = family; - } - public int hashCode() { - return name.hashCode() + family.hashCode(); - } - public boolean equals(Object ob) { - if (ob == null) return false; - if (!(ob instanceof RegistryKey)) return false; - RegistryKey other = (RegistryKey)ob; - if (this.name != other.name) return false; - if (this.family != other.family) return false; - return true; - } - } - private static class LazyInitialization { - static final Map<RegistryKey,OptionKey> options = options(); - private static Map<RegistryKey,OptionKey> options() { - Map<RegistryKey,OptionKey> map = - new HashMap<RegistryKey,OptionKey>(); - map.put(new RegistryKey(StandardSocketOptions.SO_BROADCAST, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.Broadcast)); - map.put(new RegistryKey(StandardSocketOptions.SO_KEEPALIVE, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.KeepAlive)); - map.put(new RegistryKey(StandardSocketOptions.SO_LINGER, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.Linger)); - map.put(new RegistryKey(StandardSocketOptions.SO_SNDBUF, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.SendBuffer)); - map.put(new RegistryKey(StandardSocketOptions.SO_RCVBUF, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer)); - map.put(new RegistryKey(StandardSocketOptions.SO_REUSEADDR, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress)); - map.put(new RegistryKey(StandardSocketOptions.TCP_NODELAY, Net.UNSPEC), new OptionKey(SocketOptionLevel.Tcp, SocketOptionName.NoDelay)); - map.put(new RegistryKey(StandardSocketOptions.IP_TOS, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.TypeOfService)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_IF, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.MulticastInterface)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_TTL, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_LOOP, StandardProtocolFamily.INET), new OptionKey(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_IF, StandardProtocolFamily.INET6), new OptionKey(SocketOptionLevel.IPv6, SocketOptionName.MulticastInterface)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_TTL, StandardProtocolFamily.INET6), new OptionKey(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive)); - map.put(new RegistryKey(StandardSocketOptions.IP_MULTICAST_LOOP, StandardProtocolFamily.INET6), new OptionKey(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)); - map.put(new RegistryKey(ExtendedSocketOption.SO_OOBINLINE, Net.UNSPEC), new OptionKey(SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline)); - return map; - } - } - public static OptionKey findOption(SocketOption<?> name, ProtocolFamily family) { - RegistryKey key = new RegistryKey(name, family); - return LazyInitialization.options.get(key); - } -} diff --git a/openjdk/sun/nio/ch/Util.java b/openjdk/sun/nio/ch/Util.java deleted file mode 100644 index 475c1b9b..00000000 --- a/openjdk/sun/nio/ch/Util.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.lang.ref.SoftReference; -import java.lang.reflect.*; -import java.io.IOException; -import java.io.FileDescriptor; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.*; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.*; -import sun.misc.Unsafe; -import sun.misc.Cleaner; -import sun.security.action.GetPropertyAction; - - -class Util { - - private static class SelectorWrapper { - private Selector sel; - private SelectorWrapper (Selector sel) { - this.sel = sel; - Cleaner.create(this, new Closer(sel)); - } - private static class Closer implements Runnable { - private Selector sel; - private Closer (Selector sel) { - this.sel = sel; - } - public void run () { - try { - sel.close(); - } catch (Throwable th) { - throw new Error(th); - } - } - } - public Selector get() { return sel;} - } - - // Per-thread cached selector - private static ThreadLocal<SoftReference<SelectorWrapper>> localSelector - = new ThreadLocal<SoftReference<SelectorWrapper>>(); - // Hold a reference to the selWrapper object to prevent it from - // being cleaned when the temporary selector wrapped is on lease. - private static ThreadLocal<SelectorWrapper> localSelectorWrapper - = new ThreadLocal<SelectorWrapper>(); - - // When finished, invoker must ensure that selector is empty - // by cancelling any related keys and explicitly releasing - // the selector by invoking releaseTemporarySelector() - static Selector getTemporarySelector(SelectableChannel sc) - throws IOException - { - SoftReference<SelectorWrapper> ref = localSelector.get(); - SelectorWrapper selWrapper = null; - Selector sel = null; - if (ref == null - || ((selWrapper = ref.get()) == null) - || ((sel = selWrapper.get()) == null) - || (sel.provider() != sc.provider())) { - sel = sc.provider().openSelector(); - selWrapper = new SelectorWrapper(sel); - localSelector.set(new SoftReference<SelectorWrapper>(selWrapper)); - } - localSelectorWrapper.set(selWrapper); - 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); - } - - - // -- 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; - } - - static <E> Set<E> ungrowableSet(final Set<E> s) { - 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 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(); - } - - }; - } - - - private static volatile Constructor directByteBufferConstructor = null; - - private static void initDBBConstructor() { - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - try { - Class<?> cl = Class.forName("java.nio.DirectByteBuffer"); - Constructor ctor = cl.getDeclaredConstructor( - new Class[] { int.class, - long.class, - FileDescriptor.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(); - } - return null; - }}); - } - - static MappedByteBuffer newMappedByteBuffer(int size, long addr, - FileDescriptor fd, - Runnable unmapper) - { - MappedByteBuffer dbb; - if (directByteBufferConstructor == null) - initDBBConstructor(); - try { - dbb = (MappedByteBuffer)directByteBufferConstructor.newInstance( - new Object[] { new Integer(size), - new Long(addr), - fd, - unmapper }); - } catch (InstantiationException e) { - throw new InternalError(); - } catch (IllegalAccessException e) { - throw new InternalError(); - } catch (InvocationTargetException e) { - throw new InternalError(); - } - return dbb; - } - - private static volatile Constructor directByteBufferRConstructor = null; - - private static void initDBBRConstructor() { - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - try { - Class<?> cl = Class.forName("java.nio.DirectByteBufferR"); - Constructor ctor = cl.getDeclaredConstructor( - new Class[] { int.class, - long.class, - FileDescriptor.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(); - } - return null; - }}); - } - - static MappedByteBuffer newMappedByteBufferR(int size, long addr, - FileDescriptor fd, - Runnable unmapper) - { - MappedByteBuffer dbb; - if (directByteBufferRConstructor == null) - initDBBRConstructor(); - try { - dbb = (MappedByteBuffer)directByteBufferRConstructor.newInstance( - new Object[] { new Integer(size), - new Long(addr), - fd, - unmapper }); - } catch (InstantiationException e) { - throw new InternalError(); - } catch (IllegalAccessException e) { - throw new InternalError(); - } catch (InvocationTargetException e) { - throw new InternalError(); - } - return dbb; - } - - - // -- Bug compatibility -- - - private static volatile String bugLevel = null; - - static boolean atBugLevel(String bl) { // package-private - if (bugLevel == null) { - if (!sun.misc.VM.isBooted()) - return false; - String value = AccessController.doPrivileged( - new GetPropertyAction("sun.nio.ch.bugLevel")); - bugLevel = (value != null) ? value : ""; - } - return bugLevel.equals(bl); - } - - - - // -- Initialization -- - - - static void load() { - } - -} diff --git a/openjdk/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java b/openjdk/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java deleted file mode 100644 index 4b96dfac..00000000 --- a/openjdk/sun/nio/ch/WindowsAsynchronousFileChannelImpl.java +++ /dev/null @@ -1,689 +0,0 @@ -/* - * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.util.concurrent.*; -import java.nio.ByteBuffer; -import java.nio.BufferOverflowException; -import java.io.IOException; -import java.io.FileDescriptor; -import cli.System.AsyncCallback; -import cli.System.IAsyncResult; -import cli.System.IO.FileStream; -import cli.System.IO.SeekOrigin; - -/** - * Windows implementation of AsynchronousFileChannel using overlapped I/O. - */ - -public class WindowsAsynchronousFileChannelImpl - extends AsynchronousFileChannelImpl - implements Groupable -{ - // error when EOF is detected asynchronously. - private static final int ERROR_HANDLE_EOF = 38; - - // Lazy initialization of default I/O completion port - private static class DefaultIocpHolder { - static final Iocp defaultIocp = defaultIocp(); - private static Iocp defaultIocp() { - try { - return new Iocp(null, ThreadPool.createDefault()).start(); - } catch (IOException ioe) { - InternalError e = new InternalError(); - e.initCause(ioe); - throw e; - } - } - } - - // Used for force/truncate/size methods - private static final FileDispatcher nd = new FileDispatcherImpl(); - - // I/O completion port (group) - private final Iocp iocp; - - private final boolean isDefaultIocp; - - - private WindowsAsynchronousFileChannelImpl(FileDescriptor fdObj, - boolean reading, - boolean writing, - Iocp iocp, - boolean isDefaultIocp) - throws IOException - { - super(fdObj, reading, writing, iocp.executor()); - this.iocp = iocp; - this.isDefaultIocp = isDefaultIocp; - } - - public static AsynchronousFileChannel open(FileDescriptor fdo, - boolean reading, - boolean writing, - ThreadPool pool) - throws IOException - { - Iocp iocp; - boolean isDefaultIocp; - if (pool == null) { - iocp = DefaultIocpHolder.defaultIocp; - isDefaultIocp = true; - } else { - iocp = new Iocp(null, pool).start(); - isDefaultIocp = false; - } - try { - return new - WindowsAsynchronousFileChannelImpl(fdo, reading, writing, iocp, isDefaultIocp); - } catch (IOException x) { - // error binding to port so need to close it (if created for this channel) - if (!isDefaultIocp) - iocp.implClose(); - throw x; - } - } - - @Override - public void close() throws IOException { - closeLock.writeLock().lock(); - try { - if (closed) - return; // already closed - closed = true; - } finally { - closeLock.writeLock().unlock(); - } - - // invalidate all locks held for this channel - invalidateAllLocks(); - - // close the file - fdObj.close(); - - // for the non-default group close the port - if (!isDefaultIocp) - iocp.detachFromThreadPool(); - } - - @Override - public AsynchronousChannelGroupImpl group() { - return iocp; - } - - /** - * Translates Throwable to IOException - */ - private static IOException toIOException(Throwable x) { - if (x instanceof cli.System.ArgumentException) { - return new IOException(x.getMessage()); - } - if (x instanceof cli.System.IO.IOException) { - return new IOException(x.getMessage()); - } - if (x instanceof IOException) { - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - return (IOException)x; - } - return new IOException(x); - } - - @Override - public long size() throws IOException { - try { - begin(); - return nd.size(fdObj); - } finally { - end(); - } - } - - @Override - public AsynchronousFileChannel truncate(long size) throws IOException { - if (size < 0) - throw new IllegalArgumentException("Negative size"); - if (!writing) - throw new NonWritableChannelException(); - try { - begin(); - if (size > nd.size(fdObj)) - return this; - nd.truncate(fdObj, size); - } finally { - end(); - } - return this; - } - - @Override - public void force(boolean metaData) throws IOException { - try { - begin(); - nd.force(fdObj, metaData); - } finally { - end(); - } - } - - // -- file locking -- - - /** - * Task that initiates locking operation and handles completion result. - */ - private class LockTask<A> implements Runnable, Iocp.ResultHandler { - private final long position; - private final FileLockImpl fli; - private final PendingFuture<FileLock,A> result; - - LockTask(long position, - FileLockImpl fli, - PendingFuture<FileLock,A> result) - { - this.position = position; - this.fli = fli; - this.result = result; - } - - @Override - public void run() { - FileStream fs = (FileStream)fdObj.getStream(); - for (;;) { - try { - begin(); - - try { - if (false) throw new cli.System.IO.IOException(); - fs.Lock(position, fli.size()); - result.setResult(fli); - break; - } catch (cli.System.IO.IOException _) { - // we failed to acquire the lock, try again next iteration - } - } catch (Throwable x) { - // lock failed or channel closed - removeFromFileLockTable(fli); - result.setFailure(toIOException(x)); - } finally { - end(); - } - cli.System.Threading.Thread.Sleep(100); - } - - // invoke completion handler - Invoker.invoke(result); - } - - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - // release waiters and invoke completion handler - result.setResult(fli); - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // lock not acquired so remove from lock table - removeFromFileLockTable(fli); - - // release waiters - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - - @Override - <A> Future<FileLock> implLock(final long position, - final long size, - final boolean shared, - A attachment, - final CompletionHandler<FileLock,? super A> handler) - { - if (shared && !reading) - throw new NonReadableChannelException(); - if (!shared && !writing) - throw new NonWritableChannelException(); - - // add to lock table - FileLockImpl fli = addToFileLockTable(position, size, shared); - if (fli == null) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - // create Future and task that will be invoked to acquire lock - PendingFuture<FileLock,A> result = - new PendingFuture<FileLock,A>(this, handler, attachment); - LockTask lockTask = new LockTask<A>(position, fli, result); - result.setContext(lockTask); - - // initiate I/O - if (false) { - lockTask.run(); - } else { - boolean executed = false; - try { - Invoker.invokeOnThreadInThreadPool(this, lockTask); - executed = true; - } finally { - if (!executed) { - // rollback - removeFromFileLockTable(fli); - } - } - } - return result; - } - - static final int NO_LOCK = -1; // Failed to lock - static final int LOCKED = 0; // Obtained requested lock - - @Override - public FileLock tryLock(long position, long size, boolean shared) - throws IOException - { - if (shared && !reading) - throw new NonReadableChannelException(); - if (!shared && !writing) - throw new NonWritableChannelException(); - - // add to lock table - final FileLockImpl fli = addToFileLockTable(position, size, shared); - if (fli == null) - throw new ClosedChannelException(); - - boolean gotLock = false; - try { - begin(); - // try to acquire the lock - int res; - try { - if (false) throw new cli.System.IO.IOException(); - FileStream fs = (FileStream)fdObj.getStream(); - fs.Lock(position, size); - res = LOCKED; - } catch (cli.System.IO.IOException _) { - res = NO_LOCK; - } - if (res == NO_LOCK) - return null; - gotLock = true; - return fli; - } finally { - if (!gotLock) - removeFromFileLockTable(fli); - end(); - } - } - - @Override - protected void implRelease(FileLockImpl fli) throws IOException { - try { - if (false) throw new cli.System.IO.IOException(); - FileStream fs = (FileStream)fdObj.getStream(); - fs.Unlock(fli.position(), fli.size()); - } catch (cli.System.IO.IOException x) { - if (!FileDispatcherImpl.NotLockedHack.isErrorNotLocked(x)) { - throw new IOException(x.getMessage()); - } - } - } - - /** - * Task that initiates read operation and handles completion result. - */ - private class ReadTask<A> implements Runnable, Iocp.ResultHandler, AsyncCallback.Method { - private final ByteBuffer dst; - private final int pos, rem; // buffer position/remaining - private final long position; // file position - private final PendingFuture<Integer,A> result; - - // set to dst if direct; otherwise set to substituted direct buffer - private volatile ByteBuffer buf; - - ReadTask(ByteBuffer dst, - int pos, - int rem, - long position, - PendingFuture<Integer,A> result) - { - this.dst = dst; - this.pos = pos; - this.rem = rem; - this.position = position; - this.result = result; - } - - void updatePosition(int bytesTransferred) { - // if the I/O succeeded then adjust buffer position - if (bytesTransferred > 0) { - if (buf == dst) { - try { - dst.position(pos + bytesTransferred); - } catch (IllegalArgumentException x) { - // someone has changed the position; ignore - } - } else { - // had to substitute direct buffer - buf.position(bytesTransferred).flip(); - try { - dst.put(buf); - } catch (BufferOverflowException x) { - // someone has changed the position; ignore - } - } - } - } - - @Override - public void run() { - // Substitute an array backed buffer if not - if (dst.hasArray()) { - buf = dst; - } else { - buf = ByteBuffer.allocate(rem); - } - - try { - begin(); - - // initiate read - FileStream fs = (FileStream)fdObj.getStream(); - fs.Seek(position, SeekOrigin.wrap(SeekOrigin.Begin)); - fs.BeginRead(buf.array(), buf.arrayOffset() + pos, rem, new AsyncCallback(this), null); - return; - - } catch (Throwable x) { - // failed to initiate read - result.setFailure(toIOException(x)); - } finally { - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - public void Invoke(IAsyncResult ar) { - try { - FileStream fs = (FileStream)fdObj.getStream(); - completed(fs.EndRead(ar), false); - } catch (Throwable x) { - failed(0, toIOException(x)); - } - } - - /** - * Executed when the I/O has completed - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - updatePosition(bytesTransferred); - - // release waiters and invoke completion handler - result.setResult(bytesTransferred); - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // if EOF detected asynchronously then it is reported as error - if (error == ERROR_HANDLE_EOF) { - completed(-1, false); - } else { - // release waiters - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - } - - @Override - <A> Future<Integer> implRead(ByteBuffer dst, - long position, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - if (!reading) - throw new NonReadableChannelException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (dst.isReadOnly()) - throw new IllegalArgumentException("Read-only buffer"); - - // check if channel is closed - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - int pos = dst.position(); - int lim = dst.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - // no space remaining - if (rem == 0) { - if (handler == null) - return CompletedFuture.withResult(0); - Invoker.invoke(this, handler, attachment, 0, null); - return null; - } - - // create Future and task that initiates read - PendingFuture<Integer,A> result = - new PendingFuture<Integer,A>(this, handler, attachment); - ReadTask readTask = new ReadTask<A>(dst, pos, rem, position, result); - result.setContext(readTask); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - readTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, readTask); - } - return result; - } - - /** - * Task that initiates write operation and handles completion result. - */ - private class WriteTask<A> implements Runnable, Iocp.ResultHandler, AsyncCallback.Method { - private final ByteBuffer src; - private final int pos, rem; // buffer position/remaining - private final long position; // file position - private final PendingFuture<Integer,A> result; - - // set to src if direct; otherwise set to substituted direct buffer - private volatile ByteBuffer buf; - - WriteTask(ByteBuffer src, - int pos, - int rem, - long position, - PendingFuture<Integer,A> result) - { - this.src = src; - this.pos = pos; - this.rem = rem; - this.position = position; - this.result = result; - } - - void updatePosition(int bytesTransferred) { - // if the I/O succeeded then adjust buffer position - if (bytesTransferred > 0) { - try { - src.position(pos + bytesTransferred); - } catch (IllegalArgumentException x) { - // someone has changed the position - } - } - } - - @Override - public void run() { - // Substitute an array backed buffer if not - if (src.hasArray()) { - buf = src; - } else { - buf = ByteBuffer.allocate(rem); - buf.put(src); - buf.flip(); - // temporarily restore position as we don't know how many bytes - // will be written - src.position(pos); - } - - try { - begin(); - - // initiate the write - FileStream fs = (FileStream)fdObj.getStream(); - fs.Seek(position, SeekOrigin.wrap(SeekOrigin.Begin)); - fs.BeginWrite(buf.array(), buf.arrayOffset() + pos, rem, new AsyncCallback(this), null); - return; - - } catch (Throwable x) { - // failed to initiate read: - result.setFailure(toIOException(x)); - - } finally { - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - public void Invoke(IAsyncResult ar) { - try { - FileStream fs = (FileStream)fdObj.getStream(); - fs.EndWrite(ar); - completed(rem, false); - } catch (Throwable x) { - failed(0, toIOException(x)); - } - } - - /** - * Executed when the I/O has completed - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - updatePosition(bytesTransferred); - - // release waiters and invoke completion handler - result.setResult(bytesTransferred); - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // release waiters and invoker completion handler - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - - <A> Future<Integer> implWrite(ByteBuffer src, - long position, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - if (!writing) - throw new NonWritableChannelException(); - if (position < 0) - throw new IllegalArgumentException("Negative position"); - - // check if channel is closed - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - int pos = src.position(); - int lim = src.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - - // nothing to write - if (rem == 0) { - if (handler == null) - return CompletedFuture.withResult(0); - Invoker.invoke(this, handler, attachment, 0, null); - return null; - } - - // create Future and task to initiate write - PendingFuture<Integer,A> result = - new PendingFuture<Integer,A>(this, handler, attachment); - WriteTask writeTask = new WriteTask<A>(src, pos, rem, position, result); - result.setContext(writeTask); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - writeTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, writeTask); - } - return result; - } -} diff --git a/openjdk/sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java b/openjdk/sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java deleted file mode 100644 index b95f4279..00000000 --- a/openjdk/sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.net.InetSocketAddress; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; -import java.io.FileDescriptor; -import java.io.IOException; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; - -/** - * Windows implementation of AsynchronousServerSocketChannel using overlapped I/O. - */ - -class WindowsAsynchronousServerSocketChannelImpl - extends AsynchronousServerSocketChannelImpl -{ - private final Iocp iocp; - - // flag to indicate that an accept operation is outstanding - private AtomicBoolean accepting = new AtomicBoolean(); - - - WindowsAsynchronousServerSocketChannelImpl(Iocp iocp) throws IOException { - super(iocp); - - this.iocp = iocp; - } - - @Override - void implClose() throws IOException { - // close socket (which may cause outstanding accept to be aborted). - SocketDispatcher.closeImpl(fd); - } - - @Override - public AsynchronousChannelGroupImpl group() { - return iocp; - } - - /** - * Task to initiate accept operation and to handle result. - */ - private class AcceptTask implements Runnable, Iocp.ResultHandler { - private final WindowsAsynchronousSocketChannelImpl channel; - private final AccessControlContext acc; - private final PendingFuture<AsynchronousSocketChannel,Object> result; - - AcceptTask(WindowsAsynchronousSocketChannelImpl channel, - AccessControlContext acc, - PendingFuture<AsynchronousSocketChannel,Object> result) - { - this.channel = channel; - this.acc = acc; - this.result = result; - } - - void enableAccept() { - accepting.set(false); - } - - void closeChildChannel() { - try { - channel.close(); - } catch (IOException ignore) { } - } - - // caller must have acquired read lock for the listener and child channel. - void finishAccept() throws IOException { - /** - * Set local/remote addresses. This is currently very inefficient - * in that it requires 2 calls to getsockname and 2 calls to getpeername. - * (should change this to use GetAcceptExSockaddrs) - */ - updateAcceptContext(fd, channel.fd); - - InetSocketAddress local = Net.localAddress(channel.fd); - final InetSocketAddress remote = Net.remoteAddress(channel.fd); - channel.setConnected(local, remote); - - // permission check (in context of initiating thread) - if (acc != null) { - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - SecurityManager sm = System.getSecurityManager(); - sm.checkAccept(remote.getAddress().getHostAddress(), - remote.getPort()); - return null; - } - }, acc); - } - } - - /** - * Initiates the accept operation. - */ - @Override - public void run() { - - try { - // begin usage of listener socket - begin(); - try { - // begin usage of child socket (as it is registered with - // completion port and so may be closed in the event that - // the group is forcefully closed). - channel.begin(); - - synchronized (result) { - - int n = accept0(fd, channel.fd, this); - if (n == IOStatus.UNAVAILABLE) { - return; - } - - // connection accepted immediately - finishAccept(); - - // allow another accept before the result is set - enableAccept(); - result.setResult(channel); - } - } finally { - // end usage on child socket - channel.end(); - } - } catch (Throwable x) { - // failed to initiate accept so release resources - closeChildChannel(); - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException) && !(x instanceof SecurityException)) - x = new IOException(x); - enableAccept(); - result.setFailure(x); - } finally { - // end of usage of listener socket - end(); - } - - // accept completed immediately but may not have executed on - // initiating thread in which case the operation may have been - // cancelled. - if (result.isCancelled()) { - closeChildChannel(); - } - - // invoke completion handler - Invoker.invokeIndirectly(result); - } - - /** - * Executed when the I/O has completed - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - try { - // connection accept after group has shutdown - if (iocp.isShutdown()) { - throw new IOException(new ShutdownChannelGroupException()); - } - - // finish the accept - try { - begin(); - try { - channel.begin(); - finishAccept(); - } finally { - channel.end(); - } - } finally { - end(); - } - - // allow another accept before the result is set - enableAccept(); - result.setResult(channel); - } catch (Throwable x) { - enableAccept(); - closeChildChannel(); - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException) && !(x instanceof SecurityException)) - x = new IOException(x); - result.setFailure(x); - } - - // if an async cancel has already cancelled the operation then - // close the new channel so as to free resources - if (result.isCancelled()) { - closeChildChannel(); - } - - // invoke handler (but not directly) - Invoker.invokeIndirectly(result); - } - - @Override - public void failed(int error, IOException x) { - enableAccept(); - closeChildChannel(); - - // release waiters - if (isOpen()) { - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invokeIndirectly(result); - } - } - - @Override - Future<AsynchronousSocketChannel> implAccept(Object attachment, - final CompletionHandler<AsynchronousSocketChannel,Object> handler) - { - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invokeIndirectly(this, handler, attachment, null, exc); - return null; - } - if (isAcceptKilled()) - throw new RuntimeException("Accept not allowed due to cancellation"); - - // ensure channel is bound to local address - if (localAddress == null) - throw new NotYetBoundException(); - - // create the socket that will be accepted. The creation of the socket - // is enclosed by a begin/end for the listener socket to ensure that - // we check that the listener is open and also to prevent the I/O - // port from being closed as the new socket is registered. - WindowsAsynchronousSocketChannelImpl ch = null; - IOException ioe = null; - try { - begin(); - ch = new WindowsAsynchronousSocketChannelImpl(iocp, false); - } catch (IOException x) { - ioe = x; - } finally { - end(); - } - if (ioe != null) { - if (handler == null) - return CompletedFuture.withFailure(ioe); - Invoker.invokeIndirectly(this, handler, attachment, null, ioe); - return null; - } - - // need calling context when there is security manager as - // permission check may be done in a different thread without - // any application call frames on the stack - AccessControlContext acc = (System.getSecurityManager() == null) ? - null : AccessController.getContext(); - - PendingFuture<AsynchronousSocketChannel,Object> result = - new PendingFuture<AsynchronousSocketChannel,Object>(this, handler, attachment); - AcceptTask task = new AcceptTask(ch, acc, result); - result.setContext(task); - - // check and set flag to prevent concurrent accepting - if (!accepting.compareAndSet(false, true)) - throw new AcceptPendingException(); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - task.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, task); - } - return result; - } - - // -- Native methods -- - - private static native void initIDs(); - - private static native int accept0(FileDescriptor listenSocket, FileDescriptor acceptSocket, - Iocp.ResultHandler handler) throws IOException; - - private static native void updateAcceptContext(FileDescriptor listenSocket, - FileDescriptor acceptSocket) throws IOException; - - private static native void closesocket0(long socket) throws IOException; - - static { - Util.load(); - initIDs(); - } -} diff --git a/openjdk/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java b/openjdk/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java deleted file mode 100644 index e82c1d9b..00000000 --- a/openjdk/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java +++ /dev/null @@ -1,817 +0,0 @@ -/* - * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.nio.ch; - -import java.nio.channels.*; -import java.nio.ByteBuffer; -import java.nio.BufferOverflowException; -import java.net.*; -import java.util.concurrent.*; -import java.io.FileDescriptor; -import java.io.IOException; - -/** - * Windows implementation of AsynchronousSocketChannel using overlapped I/O. - */ - -class WindowsAsynchronousSocketChannelImpl - extends AsynchronousSocketChannelImpl -{ - // maximum vector size for scatter/gather I/O - private static final int MAX_WSABUF = 16; - - // I/O completion port that the socket is associated with - private final Iocp iocp; - - - WindowsAsynchronousSocketChannelImpl(Iocp iocp, boolean failIfGroupShutdown) - throws IOException - { - super(iocp); - - this.iocp = iocp; - } - - WindowsAsynchronousSocketChannelImpl(Iocp iocp) throws IOException { - this(iocp, true); - } - - @Override - public AsynchronousChannelGroupImpl group() { - return iocp; - } - - // invoked by WindowsAsynchronousServerSocketChannelImpl when new connection - // accept - void setConnected(SocketAddress localAddress, SocketAddress remoteAddress) { - synchronized (stateLock) { - state = ST_CONNECTED; - this.localAddress = localAddress; - this.remoteAddress = remoteAddress; - } - } - - @Override - void implClose() throws IOException { - // close socket (may cause outstanding async I/O operations to fail). - SocketDispatcher.closeImpl(fd); - } - - @Override - public void onCancel(PendingFuture<?,?> task) { - if (task.getContext() instanceof ConnectTask) - killConnect(); - if (task.getContext() instanceof ReadTask) - killReading(); - if (task.getContext() instanceof WriteTask) - killWriting(); - } - - /** - * Implements the task to initiate a connection and the handler to - * consume the result when the connection is established (or fails). - */ - private class ConnectTask<A> implements Runnable, Iocp.ResultHandler { - private final InetSocketAddress remote; - private final PendingFuture<Void,A> result; - - ConnectTask(InetSocketAddress remote, PendingFuture<Void,A> result) { - this.remote = remote; - this.result = result; - } - - private void closeChannel() { - try { - close(); - } catch (IOException ignore) { } - } - - private IOException toIOException(Throwable x) { - if (x instanceof IOException) { - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - return (IOException)x; - } - return new IOException(x); - } - - /** - * Invoke after a connection is successfully established. - */ - private void afterConnect() throws IOException { - updateConnectContext(fd); - synchronized (stateLock) { - state = ST_CONNECTED; - remoteAddress = remote; - } - } - - /** - * Task to initiate a connection. - */ - @Override - public void run() { - Throwable exc = null; - try { - begin(); - - // synchronize on result to allow this thread handle the case - // where the connection is established immediately. - synchronized (result) { - // initiate the connection - int n = connect0(fd, Net.isIPv6Available(), remote.getAddress(), - remote.getPort(), this); - if (n == IOStatus.UNAVAILABLE) { - // connection is pending - return; - } - - // connection established immediately - afterConnect(); - result.setResult(null); - } - } catch (Throwable x) { - exc = x; - } finally { - end(); - } - - if (exc != null) { - closeChannel(); - result.setFailure(toIOException(exc)); - } - Invoker.invoke(result); - } - - /** - * Invoked by handler thread when connection established. - */ - @Override - public void completed(int bytesTransferred, boolean canInvokeDirect) { - Throwable exc = null; - try { - begin(); - afterConnect(); - result.setResult(null); - } catch (Throwable x) { - // channel is closed or unable to finish connect - exc = x; - } finally { - end(); - } - - // can't close channel while in begin/end block - if (exc != null) { - closeChannel(); - result.setFailure(toIOException(exc)); - } - - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - /** - * Invoked by handler thread when failed to establish connection. - */ - @Override - public void failed(int error, IOException x) { - if (isOpen()) { - closeChannel(); - result.setFailure(x); - } else { - result.setFailure(new AsynchronousCloseException()); - } - Invoker.invoke(result); - } - } - - @Override - <A> Future<Void> implConnect(SocketAddress remote, - A attachment, - CompletionHandler<Void,? super A> handler) - { - if (!isOpen()) { - Throwable exc = new ClosedChannelException(); - if (handler == null) - return CompletedFuture.withFailure(exc); - Invoker.invoke(this, handler, attachment, null, exc); - return null; - } - - InetSocketAddress isa = Net.checkAddress(remote); - - // permission check - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); - - // check and update state - // ConnectEx requires the socket to be bound to a local address - IOException bindException = null; - synchronized (stateLock) { - if (state == ST_CONNECTED) - throw new AlreadyConnectedException(); - if (state == ST_PENDING) - throw new ConnectionPendingException(); - if (localAddress == null) { - try { - bind(new InetSocketAddress(0)); - } catch (IOException x) { - bindException = x; - } - } - if (bindException == null) - state = ST_PENDING; - } - - // handle bind failure - if (bindException != null) { - try { - close(); - } catch (IOException ignore) { } - if (handler == null) - return CompletedFuture.withFailure(bindException); - Invoker.invoke(this, handler, attachment, null, bindException); - return null; - } - - // setup task - PendingFuture<Void,A> result = - new PendingFuture<Void,A>(this, handler, attachment); - ConnectTask task = new ConnectTask<A>(isa, result); - result.setContext(task); - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - task.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, task); - } - return result; - } - - /** - * Implements the task to initiate a read and the handler to consume the - * result when the read completes. - */ - private class ReadTask<V,A> implements Runnable, Iocp.ResultHandler { - private final ByteBuffer[] bufs; - private final int numBufs; - private final boolean scatteringRead; - private final PendingFuture<V,A> result; - - // set by run method - private ByteBuffer[] shadow; - - ReadTask(ByteBuffer[] bufs, - boolean scatteringRead, - PendingFuture<V,A> result) - { - this.bufs = bufs; - this.numBufs = (bufs.length > MAX_WSABUF) ? MAX_WSABUF : bufs.length; - this.scatteringRead = scatteringRead; - this.result = result; - } - - /** - * Invoked prior to read to prepare the WSABUF array. Where necessary, - * it substitutes direct buffers with managed buffers. - */ - void prepareBuffers() { - shadow = new ByteBuffer[numBufs]; - for (int i=0; i<numBufs; i++) { - ByteBuffer dst = bufs[i]; - int pos = dst.position(); - int lim = dst.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - if (!dst.hasArray()) { - // substitute with direct buffer - ByteBuffer bb = ByteBuffer.allocate(rem); - shadow[i] = bb; - } else { - shadow[i] = dst; - } - } - } - - /** - * Invoked after a read has completed to update the buffer positions - * and release any substituted buffers. - */ - void updateBuffers(int bytesRead) { - for (int i=0; i<numBufs; i++) { - ByteBuffer nextBuffer = shadow[i]; - int pos = nextBuffer.position(); - int len = nextBuffer.remaining(); - if (bytesRead >= len) { - bytesRead -= len; - int newPosition = pos + len; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by another - } - } else { // Buffers not completely filled - if (bytesRead > 0) { - assert(pos + bytesRead < (long)Integer.MAX_VALUE); - int newPosition = pos + bytesRead; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by another - } - } - break; - } - } - - // Put results from shadow into the slow buffers - for (int i=0; i<numBufs; i++) { - if (!bufs[i].hasArray()) { - shadow[i].flip(); - try { - bufs[i].put(shadow[i]); - } catch (BufferOverflowException x) { - // position changed by another - } - } - } - } - - void releaseBuffers() { - } - - @Override - @SuppressWarnings("unchecked") - public void run() { - boolean prepared = false; - boolean pending = false; - - try { - begin(); - - // substitute direct buffers - prepareBuffers(); - prepared = true; - - // initiate read - int n = read0(fd, shadow, this); - if (n == IOStatus.UNAVAILABLE) { - // I/O is pending - pending = true; - return; - } - if (n == IOStatus.EOF) { - // input shutdown - enableReading(); - if (scatteringRead) { - result.setResult((V)Long.valueOf(-1L)); - } else { - result.setResult((V)Integer.valueOf(-1)); - } - } - // read completed immediately - if (n == 0) { - n = -1; // EOF - } else { - updateBuffers(n); - } - releaseBuffers(); - enableReading(); - if (scatteringRead) { - result.setResult((V)Long.valueOf(n)); - } else { - result.setResult((V)Integer.valueOf(n)); - } - } catch (Throwable x) { - // failed to initiate read - // reset read flag before releasing waiters - enableReading(); - if (x instanceof ClosedChannelException) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException)) - x = new IOException(x); - result.setFailure(x); - } finally { - // release resources if I/O not pending - if (!pending) { - if (prepared) - releaseBuffers(); - } - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - /** - * Executed when the I/O has completed - */ - @Override - @SuppressWarnings("unchecked") - public void completed(int bytesTransferred, boolean canInvokeDirect) { - if (bytesTransferred == 0) { - bytesTransferred = -1; // EOF - } else { - updateBuffers(bytesTransferred); - } - - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - synchronized (result) { - if (result.isDone()) - return; - enableReading(); - if (scatteringRead) { - result.setResult((V)Long.valueOf(bytesTransferred)); - } else { - result.setResult((V)Integer.valueOf(bytesTransferred)); - } - } - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - if (!isOpen()) - x = new AsynchronousCloseException(); - - synchronized (result) { - if (result.isDone()) - return; - enableReading(); - result.setFailure(x); - } - Invoker.invoke(result); - } - - /** - * Invoked if timeout expires before it is cancelled - */ - void timeout() { - // synchronize on result as the I/O could complete/fail - synchronized (result) { - if (result.isDone()) - return; - - // kill further reading before releasing waiters - enableReading(true); - result.setFailure(new InterruptedByTimeoutException()); - } - - // invoke handler without any locks - Invoker.invoke(result); - } - } - - @Override - <V extends Number,A> Future<V> implRead(boolean isScatteringRead, - ByteBuffer dst, - ByteBuffer[] dsts, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<V,? super A> handler) - { - // setup task - PendingFuture<V,A> result = - new PendingFuture<V,A>(this, handler, attachment); - ByteBuffer[] bufs; - if (isScatteringRead) { - bufs = dsts; - } else { - bufs = new ByteBuffer[1]; - bufs[0] = dst; - } - final ReadTask readTask = new ReadTask<V,A>(bufs, isScatteringRead, result); - result.setContext(readTask); - - // schedule timeout - if (timeout > 0L) { - Future<?> timeoutTask = iocp.schedule(new Runnable() { - public void run() { - readTask.timeout(); - } - }, timeout, unit); - result.setTimeoutTask(timeoutTask); - } - - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - readTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, readTask); - } - return result; - } - - /** - * Implements the task to initiate a write and the handler to consume the - * result when the write completes. - */ - private class WriteTask<V,A> implements Runnable, Iocp.ResultHandler { - private final ByteBuffer[] bufs; - private final int numBufs; - private final boolean gatheringWrite; - private final PendingFuture<V,A> result; - - // set by run method - private ByteBuffer[] shadow; - - WriteTask(ByteBuffer[] bufs, - boolean gatheringWrite, - PendingFuture<V,A> result) - { - this.bufs = bufs; - this.numBufs = (bufs.length > MAX_WSABUF) ? MAX_WSABUF : bufs.length; - this.gatheringWrite = gatheringWrite; - this.result = result; - } - - /** - * Invoked prior to write to prepare the WSABUF array. Where necessary, - * it substitutes direct buffers with managed buffers. - */ - void prepareBuffers() { - shadow = new ByteBuffer[numBufs]; - for (int i=0; i<numBufs; i++) { - ByteBuffer src = bufs[i]; - int pos = src.position(); - int lim = src.limit(); - assert (pos <= lim); - int rem = (pos <= lim ? lim - pos : 0); - if (!src.hasArray()) { - // substitute with direct buffer - ByteBuffer bb = ByteBuffer.allocate(rem); - bb.put(src); - bb.flip(); - src.position(pos); // leave heap buffer untouched for now - shadow[i] = bb; - } else { - shadow[i] = src; - } - } - } - - /** - * Invoked after a write has completed to update the buffer positions - * and release any substituted buffers. - */ - void updateBuffers(int bytesWritten) { - // Notify the buffers how many bytes were taken - for (int i=0; i<numBufs; i++) { - ByteBuffer nextBuffer = bufs[i]; - int pos = nextBuffer.position(); - int lim = nextBuffer.limit(); - int len = (pos <= lim ? lim - pos : lim); - if (bytesWritten >= len) { - bytesWritten -= len; - int newPosition = pos + len; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by someone else - } - } else { // Buffers not completely filled - if (bytesWritten > 0) { - assert(pos + bytesWritten < (long)Integer.MAX_VALUE); - int newPosition = pos + bytesWritten; - try { - nextBuffer.position(newPosition); - } catch (IllegalArgumentException x) { - // position changed by someone else - } - } - break; - } - } - } - - void releaseBuffers() { - } - - @Override - //@SuppressWarnings("unchecked") - public void run() { - boolean prepared = false; - boolean pending = false; - boolean shutdown = false; - - try { - begin(); - - // substitute direct buffers - prepareBuffers(); - prepared = true; - - int n = write0(fd, shadow, this); - if (n == IOStatus.UNAVAILABLE) { - // I/O is pending - pending = true; - return; - } - if (n == IOStatus.EOF) { - // special case for shutdown output - shutdown = true; - throw new ClosedChannelException(); - } - // write completed immediately - updateBuffers(n); - releaseBuffers(); - enableWriting(); - if (gatheringWrite) { - result.setResult((V)Long.valueOf(n)); - } else { - result.setResult((V)Integer.valueOf(n)); - } - } catch (Throwable x) { - // write failed. Enable writing before releasing waiters. - enableWriting(); - if (!shutdown && (x instanceof ClosedChannelException)) - x = new AsynchronousCloseException(); - if (!(x instanceof IOException)) - x = new IOException(x); - result.setFailure(x); - } finally { - // release resources if I/O not pending - if (!pending) { - if (prepared) - releaseBuffers(); - } - end(); - } - - // invoke completion handler - Invoker.invoke(result); - } - - /** - * Executed when the I/O has completed - */ - @Override - @SuppressWarnings("unchecked") - public void completed(int bytesTransferred, boolean canInvokeDirect) { - updateBuffers(bytesTransferred); - - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - synchronized (result) { - if (result.isDone()) - return; - enableWriting(); - if (gatheringWrite) { - result.setResult((V)Long.valueOf(bytesTransferred)); - } else { - result.setResult((V)Integer.valueOf(bytesTransferred)); - } - } - if (canInvokeDirect) { - Invoker.invokeUnchecked(result); - } else { - Invoker.invoke(result); - } - } - - @Override - public void failed(int error, IOException x) { - // return direct buffer to cache if substituted - releaseBuffers(); - - // release waiters if not already released by timeout - if (!isOpen()) - x = new AsynchronousCloseException(); - - synchronized (result) { - if (result.isDone()) - return; - enableWriting(); - result.setFailure(x); - } - Invoker.invoke(result); - } - - /** - * Invoked if timeout expires before it is cancelled - */ - void timeout() { - // synchronize on result as the I/O could complete/fail - synchronized (result) { - if (result.isDone()) - return; - - // kill further writing before releasing waiters - enableWriting(true); - result.setFailure(new InterruptedByTimeoutException()); - } - - // invoke handler without any locks - Invoker.invoke(result); - } - } - - @Override - <V extends Number,A> Future<V> implWrite(boolean gatheringWrite, - ByteBuffer src, - ByteBuffer[] srcs, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<V,? super A> handler) - { - // setup task - PendingFuture<V,A> result = - new PendingFuture<V,A>(this, handler, attachment); - ByteBuffer[] bufs; - if (gatheringWrite) { - bufs = srcs; - } else { - bufs = new ByteBuffer[1]; - bufs[0] = src; - } - final WriteTask writeTask = new WriteTask<V,A>(bufs, gatheringWrite, result); - result.setContext(writeTask); - - // schedule timeout - if (timeout > 0L) { - Future<?> timeoutTask = iocp.schedule(new Runnable() { - public void run() { - writeTask.timeout(); - } - }, timeout, unit); - result.setTimeoutTask(timeoutTask); - } - - // initiate I/O (can only be done from thread in thread pool) - // initiate I/O - if (Iocp.supportsThreadAgnosticIo()) { - writeTask.run(); - } else { - Invoker.invokeOnThreadInThreadPool(this, writeTask); - } - return result; - } - - // -- Native methods -- - - private static native void initIDs(); - - private static native int connect0(FileDescriptor fd, boolean preferIPv6, - InetAddress remote, int remotePort, Iocp.ResultHandler handler) throws IOException; - - private static native void updateConnectContext(FileDescriptor fd) throws IOException; - - private static native int read0(FileDescriptor fd, ByteBuffer[] bufs, Iocp.ResultHandler handler) - throws IOException; - - private static native int write0(FileDescriptor fd, ByteBuffer[] bufs, Iocp.ResultHandler handler) - throws IOException; - - private static native void shutdown0(long socket, int how) throws IOException; - - private static native void closesocket0(long socket) throws IOException; - - static { - Util.load(); - initIDs(); - } -} |