Replace UNSAFE.throwException with alternatives supported on Java 8 (#10629)

Motivation:
 We wish to use Unsafe as little as possible, and Java 8 allows us
 to take some short-cuts or play some tricks with generics,
 for the purpose of working around having to declare all checked
 exceptions. Ideally all checked exceptions would be declared, but
 the code base is not ready for that yet.

Modification:
 The call to UNSAFE.throwException has been removed, so when we need
 that feature, we instead use the generic exception trick.
 In may cases, Java 8 allows us to throw Throwable directly. This
 happens in cases where no exception is declared to be thrown in a
 scope.
 Finally, some warnings have also been fixed, and some imports have
 been reorganised and cleaned up while I was modifying the files
 anyway.

Result:
 We no longer use Unsafe for throwing any exceptions.
This commit is contained in:
Chris Vest 2020-10-02 08:29:07 +02:00 committed by GitHub
parent ba43065482
commit 86c8f24d9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 163 additions and 220 deletions

View File

@ -28,7 +28,6 @@ import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDec
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.MultiPartStatus;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.NotEnoughDataDecoderException;
import io.netty.util.ByteProcessor;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import java.io.IOException;
@ -163,7 +162,7 @@ public class HttpPostStandardRequestDecoder implements InterfaceHttpPostRequestD
}
} catch (Throwable e) {
destroy();
PlatformDependent.throwException(e);
throw e;
}
}
@ -384,11 +383,8 @@ public class HttpPostStandardRequestDecoder implements InterfaceHttpPostRequestD
if (data == null) {
return;
}
List<InterfaceHttpData> datas = bodyMapHttpData.get(data.getName());
if (datas == null) {
datas = new ArrayList<>(1);
bodyMapHttpData.put(data.getName(), datas);
}
List<InterfaceHttpData> datas = bodyMapHttpData.computeIfAbsent(
data.getName(), k -> new ArrayList<>(1));
datas.add(data);
bodyListHttpData.add(data);
}
@ -494,11 +490,7 @@ public class HttpPostStandardRequestDecoder implements InterfaceHttpPostRequestD
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw e;
} catch (IOException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
} catch (IOException | IllegalArgumentException e) {
// error while decoding
undecodedChunk.readerIndex(firstpos);
throw new ErrorDataDecoderException(e);

View File

@ -18,7 +18,6 @@ import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2FrameReader.Configuration;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.UnstableApi;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_MAX_FRAME_SIZE;
@ -166,12 +165,9 @@ public class DefaultHttp2FrameReader implements Http2FrameReader, Http2FrameSize
} catch (Http2Exception e) {
readError = !Http2Exception.isStreamError(e);
throw e;
} catch (RuntimeException e) {
} catch (Throwable e) {
readError = true;
throw e;
} catch (Throwable cause) {
readError = true;
PlatformDependent.throwException(cause);
}
}

View File

@ -22,7 +22,6 @@ import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.Http2CodecUtil.SimpleChannelPromiseAggregator;
import io.netty.handler.codec.http2.Http2FrameWriter.Configuration;
import io.netty.handler.codec.http2.Http2HeadersEncoder.SensitivityDetector;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.UnstableApi;
import static io.netty.buffer.Unpooled.directBuffer;
@ -393,7 +392,7 @@ public class DefaultHttp2FrameWriter implements Http2FrameWriter, Http2FrameSize
} catch (Throwable t) {
promiseAggregator.setFailure(t);
promiseAggregator.doneAllocatingPromises();
PlatformDependent.throwException(t);
throw t;
} finally {
if (headerBlock != null) {
headerBlock.release();
@ -540,7 +539,7 @@ public class DefaultHttp2FrameWriter implements Http2FrameWriter, Http2FrameSize
} catch (Throwable t) {
promiseAggregator.setFailure(t);
promiseAggregator.doneAllocatingPromises();
PlatformDependent.throwException(t);
throw t;
} finally {
if (headerBlock != null) {
headerBlock.release();

View File

@ -15,6 +15,13 @@
package io.netty.handler.codec.http2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2Exception.CompositeStreamException;
import io.netty.handler.codec.http2.Http2Exception.StreamException;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.UnstableApi;
import static io.netty.handler.codec.http2.Http2CodecUtil.CONNECTION_STREAM_ID;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_WINDOW_SIZE;
import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_INITIAL_WINDOW_SIZE;
@ -28,13 +35,6 @@ import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2Exception.CompositeStreamException;
import io.netty.handler.codec.http2.Http2Exception.StreamException;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.UnstableApi;
/**
* Basic implementation of {@link Http2LocalFlowController}.
* <p>

View File

@ -31,13 +31,13 @@
*/
package io.netty.handler.codec.http2;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBuf;
import io.netty.util.AsciiString;
import io.netty.util.ByteProcessor;
import io.netty.util.internal.PlatformDependent;
import static java.util.Objects.requireNonNull;
final class HpackHuffmanEncoder {
private final int[] codes;
@ -136,7 +136,7 @@ final class HpackHuffmanEncoder {
for (int i = 0; i < data.length(); i++) {
len += lengths[data.charAt(i) & 0xFF];
}
return (int) ((len + 7) >> 3);
return (int) (len + 7 >> 3);
}
private final class EncodeProcessor implements ByteProcessor {
@ -189,7 +189,7 @@ final class HpackHuffmanEncoder {
}
int length() {
return (int) ((len + 7) >> 3);
return (int) (len + 7 >> 3);
}
}
}

View File

@ -19,15 +19,14 @@
*/
package io.netty.handler.codec.base64;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.ByteProcessor;
import io.netty.util.internal.PlatformDependent;
import java.nio.ByteOrder;
import static java.util.Objects.requireNonNull;
/**
* Utility class for {@link ByteBuf} that encodes and decodes to and from
* <a href="http://en.wikipedia.org/wiki/Base64">Base64</a> notation.
@ -327,8 +326,7 @@ public final class Base64 {
return dest.slice(0, outBuffPosn);
} catch (Throwable cause) {
dest.release();
PlatformDependent.throwException(cause);
return null;
throw cause;
}
}

View File

@ -143,22 +143,22 @@ public final class NetUtil {
byte[] LOCALHOST6_BYTES = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
// Create IPv4 loopback address.
Inet4Address localhost4 = null;
Inet4Address localhost4;
try {
localhost4 = (Inet4Address) InetAddress.getByAddress("localhost", LOCALHOST4_BYTES);
} catch (Exception e) {
} catch (UnknownHostException e) {
// We should not get here as long as the length of the address is correct.
PlatformDependent.throwException(e);
throw new ExceptionInInitializerError(e);
}
LOCALHOST4 = localhost4;
// Create IPv6 loopback address.
Inet6Address localhost6 = null;
Inet6Address localhost6;
try {
localhost6 = (Inet6Address) InetAddress.getByAddress("localhost", LOCALHOST6_BYTES);
} catch (Exception e) {
// We should not get here as long as the length of the address is correct.
PlatformDependent.throwException(e);
throw new ExceptionInInitializerError(e);
}
LOCALHOST6 = localhost6;
@ -544,7 +544,7 @@ public final class NetUtil {
if (compressBegin < 0 && colons != 6 ||
// a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an
// IPv4 ending, otherwise 7 :'s is bad
(colons == 7 && compressBegin >= start || colons > 7)) {
colons == 7 && compressBegin >= start || colons > 7) {
return false;
}

View File

@ -15,10 +15,10 @@
*/
package io.netty.util.concurrent;
import static java.util.Objects.requireNonNull;
import io.netty.util.internal.PlatformDependent;
import static java.util.Objects.requireNonNull;
/**
* The {@link CompleteFuture} which is failed already. It is
* recommended to use {@link EventExecutor#newFailedFuture(Throwable)}

View File

@ -15,8 +15,6 @@
*/
package io.netty.util.concurrent;
import static java.util.Objects.requireNonNull;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.ThreadExecutorMap;
@ -43,6 +41,8 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import static java.util.Objects.requireNonNull;
/**
* {@link OrderedEventExecutor}'s implementation that execute all its submitted tasks in a single thread.
*
@ -145,7 +145,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
public SingleThreadEventExecutor(Executor executor, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) {
this.executor = ThreadExecutorMap.apply(executor, this);
taskQueue = newTaskQueue(Math.max(16, maxPendingTasks));
this.addTaskWakesUp = taskQueue instanceof BlockingQueue;
addTaskWakesUp = taskQueue instanceof BlockingQueue;
rejectedExecutionHandler = requireNonNull(rejectedHandler, "rejectedHandler");
}
@ -852,7 +852,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
boolean success = false;
updateLastExecutionTime();
try {
SingleThreadEventExecutor.this.run();
run();
success = true;
} catch (Throwable t) {
logger.warn("Unexpected exception from an event executor: ", t);
@ -860,7 +860,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
for (;;) {
int oldState = state;
if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet(
SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) {
this, oldState, ST_SHUTTING_DOWN)) {
break;
}
}
@ -889,7 +889,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
for (;;) {
int oldState = state;
if (oldState >= ST_SHUTDOWN || STATE_UPDATER.compareAndSet(
SingleThreadEventExecutor.this, oldState, ST_SHUTDOWN)) {
this, oldState, ST_SHUTDOWN)) {
break;
}
}
@ -907,7 +907,7 @@ public class SingleThreadEventExecutor extends AbstractScheduledEventExecutor im
// See https://github.com/netty/netty/issues/6596.
FastThreadLocal.removeAll();
STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED);
STATE_UPDATER.set(this, ST_TERMINATED);
threadLock.countDown();
int numUserTasks = drainTasks();
if (numUserTasks > 0 && logger.isWarnEnabled()) {

View File

@ -112,7 +112,7 @@ final class CleanerJava6 implements Cleaner {
try {
freeDirectBuffer0(buffer);
} catch (Throwable cause) {
PlatformDependent0.throwException(cause);
PlatformDependent.throwException(cause);
}
} else {
freeDirectBufferPrivileged(buffer);
@ -124,12 +124,12 @@ final class CleanerJava6 implements Cleaner {
try {
freeDirectBuffer0(buffer);
return null;
} catch (Throwable cause1) {
return cause1;
} catch (Throwable throwable) {
return throwable;
}
});
if (cause != null) {
PlatformDependent0.throwException(cause);
PlatformDependent.throwException(cause);
}
}

View File

@ -21,7 +21,6 @@ import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
@ -49,10 +48,7 @@ final class CleanerJava9 implements Cleaner {
MethodType.methodType(void.class, ByteBuffer.class)).bindTo(PlatformDependent0.UNSAFE);
m.invokeExact(buffer);
return m;
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
return e;
} catch (Throwable cause) {
PlatformDependent0.throwException(cause);
return cause;
}
});
@ -87,8 +83,10 @@ final class CleanerJava9 implements Cleaner {
if (System.getSecurityManager() == null) {
try {
INVOKE_CLEANER_HANDLE.invokeExact(buffer);
} catch (Throwable cause) {
PlatformDependent0.throwException(cause);
} catch (RuntimeException exception) {
throw exception;
} catch (Throwable throwable) {
PlatformDependent.throwException(throwable);
}
} else {
freeDirectBufferPrivileged(buffer);
@ -99,15 +97,15 @@ final class CleanerJava9 implements Cleaner {
Exception error = AccessController.doPrivileged((PrivilegedAction<Exception>) () -> {
try {
INVOKE_CLEANER_HANDLE.invokeExact(PlatformDependent0.UNSAFE, buffer);
} catch (InvocationTargetException | IllegalAccessException e) {
return e;
} catch (Throwable cause) {
PlatformDependent.throwException(cause);
} catch (RuntimeException exception) {
return exception;
} catch (Throwable throwable) {
PlatformDependent.throwException(throwable);
}
return null;
});
if (error != null) {
PlatformDependent0.throwException(error);
PlatformDependent.throwException(error);
}
}
}

View File

@ -387,11 +387,7 @@ public final class PlatformDependent {
* Raises an exception bypassing compiler checks for checked exceptions.
*/
public static void throwException(Throwable t) {
if (hasUnsafe()) {
PlatformDependent0.throwException(t);
} else {
PlatformDependent.throwException0(t);
}
throwException0(t);
}
@SuppressWarnings("unchecked")
@ -648,8 +644,7 @@ public final class PlatformDependent {
return PlatformDependent0.allocateDirectNoCleaner(capacity);
} catch (Throwable e) {
decrementMemoryCounter(capacity);
throwException(e);
return null;
throw e;
}
}
@ -666,8 +661,7 @@ public final class PlatformDependent {
return PlatformDependent0.reallocateDirectNoCleaner(buffer, capacity);
} catch (Throwable e) {
decrementMemoryCounter(len);
throwException(e);
return null;
throw e;
}
}

View File

@ -31,8 +31,6 @@ import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import static java.util.Objects.requireNonNull;
/**
* The {@link PlatformDependent} operations which requires access to {@code sun.misc.*}.
*/
@ -401,11 +399,6 @@ final class PlatformDependent0 {
return UNALIGNED;
}
static void throwException(Throwable cause) {
// JVM has been observed to crash when passing a null argument. See https://github.com/netty/netty/issues/4131.
UNSAFE.throwException(requireNonNull(cause, "cause"));
}
static boolean hasDirectBufferNoCleanerConstructor() {
return DIRECT_BUFFER_CONSTRUCTOR_HANDLE != null;
}

View File

@ -16,11 +16,11 @@
package io.netty.util.internal;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import static java.util.Objects.requireNonNull;
@ -54,7 +54,7 @@ public final class StringUtil {
// Generate the lookup table that converts a byte into a 2-digit hexadecimal integer.
for (int i = 0; i < BYTE2HEX_PAD.length; i++) {
String str = Integer.toHexString(i);
BYTE2HEX_PAD[i] = i > 0xf ? str : ('0' + str);
BYTE2HEX_PAD[i] = i > 0xf ? str : '0' + str;
BYTE2HEX_NOPAD[i] = str;
}
// Generate the lookup table that converts an hex char into its decimal value:
@ -62,28 +62,28 @@ public final class StringUtil {
// if a char type is used as an index.
HEX2B = new byte[Character.MAX_VALUE + 1];
Arrays.fill(HEX2B, (byte) -1);
HEX2B['0'] = (byte) 0;
HEX2B['1'] = (byte) 1;
HEX2B['2'] = (byte) 2;
HEX2B['3'] = (byte) 3;
HEX2B['4'] = (byte) 4;
HEX2B['5'] = (byte) 5;
HEX2B['6'] = (byte) 6;
HEX2B['7'] = (byte) 7;
HEX2B['8'] = (byte) 8;
HEX2B['9'] = (byte) 9;
HEX2B['A'] = (byte) 10;
HEX2B['B'] = (byte) 11;
HEX2B['C'] = (byte) 12;
HEX2B['D'] = (byte) 13;
HEX2B['E'] = (byte) 14;
HEX2B['F'] = (byte) 15;
HEX2B['a'] = (byte) 10;
HEX2B['b'] = (byte) 11;
HEX2B['c'] = (byte) 12;
HEX2B['d'] = (byte) 13;
HEX2B['e'] = (byte) 14;
HEX2B['f'] = (byte) 15;
HEX2B['0'] = 0;
HEX2B['1'] = 1;
HEX2B['2'] = 2;
HEX2B['3'] = 3;
HEX2B['4'] = 4;
HEX2B['5'] = 5;
HEX2B['6'] = 6;
HEX2B['7'] = 7;
HEX2B['8'] = 8;
HEX2B['9'] = 9;
HEX2B['A'] = 10;
HEX2B['B'] = 11;
HEX2B['C'] = 12;
HEX2B['D'] = 13;
HEX2B['E'] = 14;
HEX2B['F'] = 15;
HEX2B['a'] = 10;
HEX2B['b'] = 11;
HEX2B['c'] = 12;
HEX2B['d'] = 13;
HEX2B['e'] = 14;
HEX2B['f'] = 15;
}
private StringUtil() {
@ -129,7 +129,7 @@ public final class StringUtil {
try {
buf.append(byteToHexStringPadded(value));
} catch (IOException e) {
PlatformDependent.throwException(e);
throw new UncheckedIOException(e);
}
return buf;
}
@ -180,7 +180,7 @@ public final class StringUtil {
try {
buf.append(byteToHexString(value));
} catch (IOException e) {
PlatformDependent.throwException(e);
throw new UncheckedIOException(e);
}
return buf;
}
@ -241,11 +241,10 @@ public final class StringUtil {
* given, or {@code -1} if the character is invalid.
*/
public static int decodeHexNibble(final char c) {
assert HEX2B.length == (Character.MAX_VALUE + 1);
assert HEX2B.length == Character.MAX_VALUE + 1;
// Character.digit() is not used here, as it addresses a larger
// set of characters (both ASCII and full-width latin letters).
final int index = c;
return HEX2B[index];
return HEX2B[c];
}
/**
@ -466,30 +465,29 @@ public final class StringUtil {
for (int i = 0; i <= last; i++) {
char c = value.charAt(i);
if (quoted) {
switch (c) {
case DOUBLE_QUOTE:
if (i == last) {
// Add the last field and return
unescaped.add(current.toString());
return unescaped;
}
char next = value.charAt(++i);
if (next == DOUBLE_QUOTE) {
// 2 double-quotes should be unescaped to one
current.append(DOUBLE_QUOTE);
break;
}
if (next == COMMA) {
// This is the end of a field. Let's start to parse the next field.
quoted = false;
unescaped.add(current.toString());
current.setLength(0);
break;
}
// double-quote followed by other character is invalid
throw newInvalidEscapedCsvFieldException(value, i - 1);
default:
current.append(c);
if (c == DOUBLE_QUOTE) {
if (i == last) {
// Add the last field and return
unescaped.add(current.toString());
return unescaped;
}
char next = value.charAt(++i);
if (next == DOUBLE_QUOTE) {
// 2 double-quotes should be unescaped to one
current.append(DOUBLE_QUOTE);
continue;
}
if (next == COMMA) {
// This is the end of a field. Let's start to parse the next field.
quoted = false;
unescaped.add(current.toString());
current.setLength(0);
continue;
}
// double-quote followed by other character is invalid
throw newInvalidEscapedCsvFieldException(value, i - 1);
} else {
current.append(c);
}
} else {
switch (c) {
@ -646,8 +644,8 @@ public final class StringUtil {
* @return a char sequence joined by a given separator.
*/
public static CharSequence join(CharSequence separator, Iterable<? extends CharSequence> elements) {
Objects.requireNonNull(separator, "separator");
Objects.requireNonNull(elements, "elements");
requireNonNull(separator, "separator");
requireNonNull(elements, "elements");
Iterator<? extends CharSequence> iterator = elements.iterator();
if (!iterator.hasNext()) {

View File

@ -16,22 +16,20 @@
package io.netty.handler.ssl;
import static java.util.Objects.requireNonNull;
import io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelectionListener;
import io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelector;
import io.netty.util.internal.PlatformDependent;
import java.util.LinkedHashSet;
import java.util.List;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import org.eclipse.jetty.npn.NextProtoNego;
import org.eclipse.jetty.npn.NextProtoNego.ClientProvider;
import org.eclipse.jetty.npn.NextProtoNego.ServerProvider;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import java.util.LinkedHashSet;
import java.util.List;
import static java.util.Objects.requireNonNull;
final class JettyNpnSslEngine extends JdkSslEngine {
private static boolean available;

View File

@ -32,6 +32,18 @@ import io.netty.util.internal.UnstableApi;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionBindingEvent;
import javax.net.ssl.SSLSessionBindingListener;
import javax.net.ssl.SSLSessionContext;
import javax.security.cert.X509Certificate;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.security.Principal;
@ -47,19 +59,6 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionBindingEvent;
import javax.net.ssl.SSLSessionBindingListener;
import javax.net.ssl.SSLSessionContext;
import javax.security.cert.X509Certificate;
import static io.netty.handler.ssl.OpenSsl.memoryAddress;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_SSL_V2;
import static io.netty.handler.ssl.SslUtils.PROTOCOL_SSL_V2_HELLO;
@ -355,8 +354,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
// Call shutdown so we are sure we correctly release all native memory and also guard against the
// case when shutdown() will be called by the finalizer again.
shutdown();
PlatformDependent.throwException(cause);
throw cause;
}
}
@ -573,7 +571,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
return buf;
} catch (Throwable cause) {
buf.release();
PlatformDependent.throwException(cause);
throw cause;
}
}
return null;

View File

@ -15,8 +15,6 @@
*/
package io.netty.handler.ssl;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderException;
@ -26,7 +24,8 @@ import io.netty.util.Mapping;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;
import static java.util.Objects.requireNonNull;
/**
* <p>Enables <a href="https://tools.ietf.org/html/rfc3546#section-3.1">SNI
@ -115,7 +114,7 @@ public class SniHandler extends AbstractSniHandler<SslContext> {
replaceHandler(ctx, hostname, sslContext);
} catch (Throwable cause) {
selection = EMPTY_SELECTION;
PlatformDependent.throwException(cause);
throw cause;
}
}

View File

@ -49,6 +49,13 @@ import io.netty.util.internal.UnstableApi;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
@ -61,14 +68,6 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import static io.netty.buffer.ByteBufUtil.ensureWritableSuccess;
import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength;
import static java.util.Objects.requireNonNull;
@ -456,7 +455,7 @@ public class SslHandler extends ByteToMessageDecoder {
engineType = SslEngineType.forEngine(engine);
this.delegatedTaskExecutor = delegatedTaskExecutor;
this.startTls = startTls;
this.jdkCompatibilityMode = engineType.jdkCompatibilityMode(engine);
jdkCompatibilityMode = engineType.jdkCompatibilityMode(engine);
setCumulator(engineType.cumulator);
}
@ -794,7 +793,7 @@ public class SslHandler extends ByteToMessageDecoder {
wrapAndFlush(ctx);
} catch (Throwable cause) {
setHandshakeFailure(ctx, cause);
PlatformDependent.throwException(cause);
throw cause;
}
}
@ -1086,11 +1085,9 @@ public class SslHandler extends ByteToMessageDecoder {
in.skipBytes(result.bytesConsumed());
out.writerIndex(out.writerIndex() + result.bytesProduced());
switch (result.getStatus()) {
case BUFFER_OVERFLOW:
if (result.getStatus() == Status.BUFFER_OVERFLOW) {
out.ensureWritable(engine.getSession().getPacketBufferSize());
break;
default:
} else {
return result;
}
}
@ -2014,15 +2011,14 @@ public class SslHandler extends ByteToMessageDecoder {
// Not all SSLEngine implementations support calling beginHandshake multiple times while a handshake
// is in progress. See https://github.com/netty/netty/issues/4718.
return;
} else {
if (handshakePromise.isDone()) {
// If the handshake is done already lets just return directly as there is no need to trigger it again.
// This can happen if the handshake(...) was triggered before we called channelActive(...) by a
// flush() that was triggered by a ChannelFutureListener that was added to the ChannelFuture returned
// from the connect(...) method. In this case we will see the flush() happen before we had a chance to
// call fireChannelActive() on the pipeline.
return;
}
}
if (handshakePromise.isDone()) {
// If the handshake is done already lets just return directly as there is no need to trigger it again.
// This can happen if the handshake(...) was triggered before we called channelActive(...) by a
// flush() that was triggered by a ChannelFutureListener that was added to the ChannelFuture returned
// from the connect(...) method. In this case we will see the flush() happen before we had a chance to
// call fireChannelActive() on the pipeline.
return;
}
// Begin handshake.
@ -2038,7 +2034,7 @@ public class SslHandler extends ByteToMessageDecoder {
}
private void applyHandshakeTimeout() {
final Promise<Channel> localHandshakePromise = this.handshakePromise;
final Promise<Channel> localHandshakePromise = handshakePromise;
// Set timeout if necessary.
final long handshakeTimeoutMillis = this.handshakeTimeoutMillis;
@ -2228,7 +2224,7 @@ public class SslHandler extends ByteToMessageDecoder {
first.writeBytes(composite);
} catch (Throwable cause) {
first.release();
PlatformDependent.throwException(cause);
throw cause;
}
composite.release();
}

View File

@ -35,7 +35,6 @@ import io.netty.channel.sctp.SctpChannelConfig;
import io.netty.channel.sctp.SctpMessage;
import io.netty.channel.sctp.SctpNotificationHandler;
import io.netty.channel.sctp.SctpServerChannel;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
@ -281,10 +280,7 @@ public class NioSctpChannel extends AbstractNioMessageChannel implements io.nett
buffer.writerIndex(buffer.writerIndex() + allocHandle.lastBytesRead())));
free = false;
return 1;
} catch (Throwable cause) {
PlatformDependent.throwException(cause);
return -1;
} finally {
} finally {
if (free) {
buffer.release();
}

View File

@ -25,7 +25,6 @@ import java.util.ArrayDeque;
import static io.netty.util.ReferenceCountUtil.safeRelease;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
import static io.netty.util.internal.PlatformDependent.throwException;
import static java.util.Objects.requireNonNull;
@UnstableApi
@ -181,7 +180,7 @@ public abstract class AbstractCoalescingBufferQueue {
safeRelease(entryBuffer);
safeRelease(toReturn);
aggregatePromise.setFailure(cause);
throwException(cause);
throw cause;
}
decrementReadableBytes(originalBytes - bytes);
return toReturn;
@ -281,7 +280,7 @@ public abstract class AbstractCoalescingBufferQueue {
} catch (Throwable cause) {
composite.release();
safeRelease(next);
throwException(cause);
throw cause;
}
return composite;
}
@ -300,7 +299,7 @@ public abstract class AbstractCoalescingBufferQueue {
} catch (Throwable cause) {
newCumulation.release();
safeRelease(next);
throwException(cause);
throw cause;
}
cumulation.release();
next.release();

View File

@ -17,9 +17,9 @@ package io.netty.channel;
import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
@ -167,7 +167,6 @@ final class ChannelHandlerMask {
return mask;
}
@SuppressWarnings("rawtypes")
private static boolean isSkippable(
final Class<?> handlerType, final String methodName, final Class<?>... paramTypes) throws Exception {
return AccessController.doPrivileged((PrivilegedExceptionAction<Boolean>) () -> {

View File

@ -47,7 +47,7 @@ import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
*/
public class LocalChannel extends AbstractChannel {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(LocalChannel.class);
@SuppressWarnings({ "rawtypes" })
@SuppressWarnings("rawtypes")
private static final AtomicReferenceFieldUpdater<LocalChannel, Future> FINISH_READ_FUTURE_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(LocalChannel.class, Future.class, "finishReadFuture");
private static final ChannelMetadata METADATA = new ChannelMetadata(false);
@ -200,7 +200,7 @@ public class LocalChannel extends AbstractChannel {
// rejects the close Runnable but give a best effort.
peer.close();
}
PlatformDependent.throwException(cause);
throw cause;
}
}
} finally {
@ -259,7 +259,7 @@ public class LocalChannel extends AbstractChannel {
}
final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get();
final Integer stackDepth = threadLocals.localChannelReaderStackDepth();
final int stackDepth = threadLocals.localChannelReaderStackDepth();
if (stackDepth < MAX_READER_STACK_DEPTH) {
threadLocals.setLocalChannelReaderStackDepth(stackDepth + 1);
try {
@ -274,7 +274,7 @@ public class LocalChannel extends AbstractChannel {
logger.warn("Closing Local channels {}-{} because exception occurred!", this, peer, cause);
close();
peer.close();
PlatformDependent.throwException(cause);
throw cause;
}
}
}
@ -352,7 +352,7 @@ public class LocalChannel extends AbstractChannel {
logger.warn("Closing Local channels {}-{} because exception occurred!", this, peer, cause);
close();
peer.close();
PlatformDependent.throwException(cause);
throw cause;
}
}

View File

@ -15,8 +15,6 @@
*/
package io.netty.channel.socket.nio;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBuf;
import io.netty.channel.AddressedEnvelope;
import io.netty.channel.Channel;
@ -34,7 +32,6 @@ import io.netty.channel.socket.DatagramChannelConfig;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import java.io.IOException;
@ -54,6 +51,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
/**
* An NIO datagram {@link Channel} that sends and receives an
* {@link AddressedEnvelope AddressedEnvelope<ByteBuf, SocketAddress>}.
@ -252,10 +251,7 @@ public final class NioDatagramChannel
localAddress(), remoteAddress));
free = false;
return 1;
} catch (Throwable cause) {
PlatformDependent.throwException(cause);
return -1;
} finally {
} finally {
if (free) {
data.release();
}
@ -569,12 +565,6 @@ public final class NioDatagramChannel
return promise;
}
@Override
@Deprecated
protected void setReadPending(boolean readPending) {
super.setReadPending(readPending);
}
void clearReadPending0() {
clearReadPending();
}