From 86c8f24d9a40612de224d2e3d4279a4e7e3c8b09 Mon Sep 17 00:00:00 2001 From: Chris Vest Date: Fri, 2 Oct 2020 08:29:07 +0200 Subject: [PATCH] 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. --- .../HttpPostStandardRequestDecoder.java | 16 +-- .../codec/http2/DefaultHttp2FrameReader.java | 6 +- .../codec/http2/DefaultHttp2FrameWriter.java | 5 +- .../DefaultHttp2LocalFlowController.java | 14 +-- .../codec/http2/HpackHuffmanEncoder.java | 8 +- .../io/netty/handler/codec/base64/Base64.java | 8 +- .../src/main/java/io/netty/util/NetUtil.java | 12 +- .../netty/util/concurrent/FailedFuture.java | 4 +- .../concurrent/SingleThreadEventExecutor.java | 14 +-- .../io/netty/util/internal/CleanerJava6.java | 8 +- .../io/netty/util/internal/CleanerJava9.java | 20 ++-- .../util/internal/PlatformDependent.java | 12 +- .../util/internal/PlatformDependent0.java | 7 -- .../io/netty/util/internal/StringUtil.java | 108 +++++++++--------- .../netty/handler/ssl/JettyNpnSslEngine.java | 16 ++- .../ssl/ReferenceCountedOpenSslEngine.java | 30 +++-- .../java/io/netty/handler/ssl/SniHandler.java | 7 +- .../java/io/netty/handler/ssl/SslHandler.java | 46 ++++---- .../channel/sctp/nio/NioSctpChannel.java | 6 +- .../AbstractCoalescingBufferQueue.java | 7 +- .../io/netty/channel/ChannelHandlerMask.java | 3 +- .../io/netty/channel/local/LocalChannel.java | 10 +- .../socket/nio/NioDatagramChannel.java | 16 +-- 23 files changed, 163 insertions(+), 220 deletions(-) diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostStandardRequestDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostStandardRequestDecoder.java index 325e4107eb..3894d8372d 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostStandardRequestDecoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostStandardRequestDecoder.java @@ -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 datas = bodyMapHttpData.get(data.getName()); - if (datas == null) { - datas = new ArrayList<>(1); - bodyMapHttpData.put(data.getName(), datas); - } + List 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); diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java index cc63b28474..8f50927e1c 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java @@ -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); } } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriter.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriter.java index dc84c91042..897d8b69d8 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriter.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameWriter.java @@ -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(); diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowController.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowController.java index a22e47e5ca..8e724f591e 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowController.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowController.java @@ -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}. *

diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java index c0013f9fa6..65b1378284 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java @@ -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); } } } diff --git a/codec/src/main/java/io/netty/handler/codec/base64/Base64.java b/codec/src/main/java/io/netty/handler/codec/base64/Base64.java index 2fb503bd2d..4aa7f57a53 100644 --- a/codec/src/main/java/io/netty/handler/codec/base64/Base64.java +++ b/codec/src/main/java/io/netty/handler/codec/base64/Base64.java @@ -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 * Base64 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; } } diff --git a/common/src/main/java/io/netty/util/NetUtil.java b/common/src/main/java/io/netty/util/NetUtil.java index 0a47e83502..2321164bc3 100644 --- a/common/src/main/java/io/netty/util/NetUtil.java +++ b/common/src/main/java/io/netty/util/NetUtil.java @@ -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; } diff --git a/common/src/main/java/io/netty/util/concurrent/FailedFuture.java b/common/src/main/java/io/netty/util/concurrent/FailedFuture.java index ac27e86010..bfcae9ba4c 100644 --- a/common/src/main/java/io/netty/util/concurrent/FailedFuture.java +++ b/common/src/main/java/io/netty/util/concurrent/FailedFuture.java @@ -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)} diff --git a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java index 969c15b017..39c3a07823 100644 --- a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java @@ -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()) { diff --git a/common/src/main/java/io/netty/util/internal/CleanerJava6.java b/common/src/main/java/io/netty/util/internal/CleanerJava6.java index f40cb9e0de..3279874571 100644 --- a/common/src/main/java/io/netty/util/internal/CleanerJava6.java +++ b/common/src/main/java/io/netty/util/internal/CleanerJava6.java @@ -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); } } diff --git a/common/src/main/java/io/netty/util/internal/CleanerJava9.java b/common/src/main/java/io/netty/util/internal/CleanerJava9.java index 96e04cf2d9..296824e5df 100644 --- a/common/src/main/java/io/netty/util/internal/CleanerJava9.java +++ b/common/src/main/java/io/netty/util/internal/CleanerJava9.java @@ -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) () -> { 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); } } } diff --git a/common/src/main/java/io/netty/util/internal/PlatformDependent.java b/common/src/main/java/io/netty/util/internal/PlatformDependent.java index 7ced669ae8..d9392dd8b4 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent.java @@ -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; } } diff --git a/common/src/main/java/io/netty/util/internal/PlatformDependent0.java b/common/src/main/java/io/netty/util/internal/PlatformDependent0.java index fc784346d5..207fe97017 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent0.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent0.java @@ -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; } diff --git a/common/src/main/java/io/netty/util/internal/StringUtil.java b/common/src/main/java/io/netty/util/internal/StringUtil.java index 60309da89e..720b6e8401 100644 --- a/common/src/main/java/io/netty/util/internal/StringUtil.java +++ b/common/src/main/java/io/netty/util/internal/StringUtil.java @@ -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 elements) { - Objects.requireNonNull(separator, "separator"); - Objects.requireNonNull(elements, "elements"); + requireNonNull(separator, "separator"); + requireNonNull(elements, "elements"); Iterator iterator = elements.iterator(); if (!iterator.hasNext()) { diff --git a/handler/src/main/java/io/netty/handler/ssl/JettyNpnSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/JettyNpnSslEngine.java index ca8ecce3d9..57858215d0 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JettyNpnSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/JettyNpnSslEngine.java @@ -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; diff --git a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java index e8ae7d1e8d..d96c156b1b 100644 --- a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java @@ -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; diff --git a/handler/src/main/java/io/netty/handler/ssl/SniHandler.java b/handler/src/main/java/io/netty/handler/ssl/SniHandler.java index 0e5e232116..38a2078a6d 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SniHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SniHandler.java @@ -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; /** *

Enables SNI @@ -115,7 +114,7 @@ public class SniHandler extends AbstractSniHandler { replaceHandler(ctx, hostname, sslContext); } catch (Throwable cause) { selection = EMPTY_SELECTION; - PlatformDependent.throwException(cause); + throw cause; } } diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index c48fa47c98..c6baf9e9b0 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -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 localHandshakePromise = this.handshakePromise; + final Promise 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(); } diff --git a/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java b/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java index b670a291e0..d11b8be321 100644 --- a/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java +++ b/transport-sctp/src/main/java/io/netty/channel/sctp/nio/NioSctpChannel.java @@ -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(); } diff --git a/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java b/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java index 8549c0b6cb..9a9b3b8a73 100644 --- a/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java +++ b/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java @@ -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(); diff --git a/transport/src/main/java/io/netty/channel/ChannelHandlerMask.java b/transport/src/main/java/io/netty/channel/ChannelHandlerMask.java index 7e54b5d4d1..4036aaacd3 100644 --- a/transport/src/main/java/io/netty/channel/ChannelHandlerMask.java +++ b/transport/src/main/java/io/netty/channel/ChannelHandlerMask.java @@ -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) () -> { diff --git a/transport/src/main/java/io/netty/channel/local/LocalChannel.java b/transport/src/main/java/io/netty/channel/local/LocalChannel.java index 4e8711defa..05e4fa5949 100644 --- a/transport/src/main/java/io/netty/channel/local/LocalChannel.java +++ b/transport/src/main/java/io/netty/channel/local/LocalChannel.java @@ -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 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; } } diff --git a/transport/src/main/java/io/netty/channel/socket/nio/NioDatagramChannel.java b/transport/src/main/java/io/netty/channel/socket/nio/NioDatagramChannel.java index d148defd80..c01206649a 100644 --- a/transport/src/main/java/io/netty/channel/socket/nio/NioDatagramChannel.java +++ b/transport/src/main/java/io/netty/channel/socket/nio/NioDatagramChannel.java @@ -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}. @@ -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(); }