GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Port 4.1: Don't corrupt ChannelOutboundBuffer when a cancelled write … · lltopk/netty@7b576d9

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • transport/src
    • main/java/io/netty/channel
      • ChannelOutboundBuffer.java
    • test/java/io/netty/channel
      • ChannelOutboundBufferTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java‎

Copy file name to clipboardExpand all lines: transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java
+22-5Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@
3535

3636
import java.nio.ByteBuffer;
3737
import java.nio.channels.ClosedChannelException;
38+
import java.util.ArrayList;
3839
import java.util.Arrays;
40+
import java.util.List;
3941
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
4042
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
4143

@@ -155,18 +157,34 @@ public void addFlush() {
155157
// there is no flushedEntry yet, so start with the entry
156158
flushedEntry = entry;
157159
}
160+
long cancelledBytes = 0;
161+
List<Object> cancelledMsgs = null;
158162
do {
159163
flushed ++;
160164
if (!entry.promise.setUncancellable()) {
161-
// Was cancelled so make sure we free up memory and notify about the freed bytes
162-
int pending = entry.cancel();
163-
decrementPendingOutboundBytes(pending, false, true);
165+
// Was cancelled so make sure we free up memory. The message is released only once this buffer is
166+
// consistent again, as releasing it may run arbitrary user code.
167+
if (cancelledMsgs == null) {
168+
cancelledMsgs = new ArrayList<Object>(2);
169+
}
170+
cancelledMsgs.add(entry.msg);
171+
cancelledBytes += entry.cancel();
164172
}
165173
entry = entry.next;
166174
} while (entry != null);
167175

168176
// All flushed so reset unflushedEntry
169177
unflushedEntry = null;
178+
179+
if (cancelledMsgs != null) {
180+
for (int i = 0; i < cancelledMsgs.size(); i++) {
181+
ReferenceCountUtil.safeRelease(cancelledMsgs.get(i));
182+
}
183+
// Notify about the freed bytes only now. This may fire channelWritabilityChanged(...) synchronously,
184+
// and a handler may write, flush or close the channel from there, so this buffer must be consistent
185+
// first.
186+
decrementPendingOutboundBytes(cancelledBytes, false, true);
187+
}
170188
}
171189
}
172190

@@ -862,8 +880,7 @@ int cancel() {
862880
cancelled = true;
863881
int pSize = pendingSize;
864882

865-
// release message and replace with an empty buffer
866-
ReferenceCountUtil.safeRelease(msg);
883+
// replace the message with an empty buffer, the caller is responsible for releasing it
867884
msg = Unpooled.EMPTY_BUFFER;
868885

869886
pendingSize = 0;
Collapse file

‎transport/src/test/java/io/netty/channel/ChannelOutboundBufferTest.java‎

Copy file name to clipboardExpand all lines: transport/src/test/java/io/netty/channel/ChannelOutboundBufferTest.java
+225Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818
import io.netty.buffer.ByteBuf;
1919
import io.netty.buffer.CompositeByteBuf;
2020
import io.netty.channel.embedded.EmbeddedChannel;
21+
import io.netty.util.AbstractReferenceCounted;
2122
import io.netty.util.CharsetUtil;
23+
import io.netty.util.ReferenceCounted;
2224
import io.netty.util.concurrent.DefaultThreadFactory;
2325
import io.netty.util.concurrent.RejectedExecutionHandlers;
2426
import io.netty.util.concurrent.SingleThreadEventExecutor;
@@ -27,16 +29,25 @@
2729

2830
import java.net.SocketAddress;
2931
import java.nio.ByteBuffer;
32+
import java.nio.channels.ClosedChannelException;
33+
import java.util.ArrayList;
34+
import java.util.List;
3035
import java.util.Queue;
3136
import java.util.concurrent.CountDownLatch;
3237
import java.util.concurrent.RejectedExecutionException;
3338
import java.util.concurrent.TimeUnit;
39+
import java.util.concurrent.atomic.AtomicInteger;
40+
import java.util.concurrent.atomic.AtomicLong;
41+
import java.util.concurrent.atomic.AtomicReference;
3442

3543
import static io.netty.buffer.Unpooled.*;
3644

3745
import static org.junit.jupiter.api.Assertions.assertEquals;
46+
import static org.junit.jupiter.api.Assertions.assertFalse;
47+
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
3848
import static org.junit.jupiter.api.Assertions.assertNotNull;
3949
import static org.junit.jupiter.api.Assertions.assertNull;
50+
import static org.junit.jupiter.api.Assertions.assertSame;
4051
import static org.junit.jupiter.api.Assertions.assertTrue;
4152

4253
public class ChannelOutboundBufferTest {
@@ -427,6 +438,220 @@ public void channelWritabilityChanged(ChannelHandlerContext ctx) {
427438
safeClose(ch);
428439
}
429440

441+
@Test
442+
public void testWriteAndFlushFromWritabilityChangedCausedByCancelledWrite() {
443+
final List<ChannelFuture> reentrantWrites = new ArrayList<ChannelFuture>();
444+
EmbeddedChannel ch = new EmbeddedChannel(new ChannelInboundHandlerAdapter() {
445+
@Override
446+
public void channelWritabilityChanged(ChannelHandlerContext ctx) {
447+
if (ctx.channel().isWritable() && reentrantWrites.isEmpty()) {
448+
reentrantWrites.add(ctx.writeAndFlush(wrappedBuffer(new byte[] { 2 })));
449+
}
450+
ctx.fireChannelWritabilityChanged();
451+
}
452+
});
453+
ch.config().setWriteBufferWaterMark(new WriteBufferWaterMark(256, 512));
454+
455+
ByteBuf cancelledBuf = buffer().writeZero(512);
456+
ChannelFuture cancelled = ch.write(cancelledBuf);
457+
ChannelFuture second = ch.write(wrappedBuffer(new byte[] { 1 }));
458+
assertFalse(ch.isWritable());
459+
assertTrue(cancelled.cancel(false));
460+
461+
// Releasing the cancelled write makes the channel writable while addFlush() runs.
462+
ch.flush();
463+
464+
assertTrue(ch.isWritable());
465+
assertEquals(1, reentrantWrites.size());
466+
assertEquals(0, cancelledBuf.refCnt());
467+
assertTrue(second.isSuccess());
468+
assertTrue(reentrantWrites.get(0).isSuccess());
469+
ChannelOutboundBuffer buffer = ch.unsafe().outboundBuffer();
470+
assertTrue(buffer.isEmpty());
471+
assertEquals(0, buffer.size());
472+
assertEquals(0, buffer.totalPendingWriteBytes());
473+
// The cancelled write is replaced by an empty buffer.
474+
assertOutbound(ch, 0);
475+
assertOutbound(ch, 1);
476+
assertOutbound(ch, 2);
477+
assertNull(ch.readOutbound());
478+
479+
assertFalse(ch.finish());
480+
assertFalse(ch.isOpen());
481+
}
482+
483+
@Test
484+
public void testCloseFromWritabilityChangedCausedByCancelledWrite() {
485+
final AtomicInteger inactive = new AtomicInteger();
486+
EmbeddedChannel ch = new EmbeddedChannel(new ChannelInboundHandlerAdapter() {
487+
@Override
488+
public void channelWritabilityChanged(ChannelHandlerContext ctx) {
489+
if (ctx.channel().isWritable()) {
490+
ctx.close();
491+
}
492+
ctx.fireChannelWritabilityChanged();
493+
}
494+
495+
@Override
496+
public void channelInactive(ChannelHandlerContext ctx) {
497+
inactive.incrementAndGet();
498+
ctx.fireChannelInactive();
499+
}
500+
});
501+
ch.config().setWriteBufferWaterMark(new WriteBufferWaterMark(256, 512));
502+
503+
ByteBuf cancelledBuf = buffer().writeZero(512);
504+
ChannelFuture cancelled = ch.write(cancelledBuf);
505+
ByteBuf second = wrappedBuffer(new byte[] { 1 });
506+
ChannelFuture secondFuture = ch.write(second);
507+
ByteBuf third = wrappedBuffer(new byte[] { 2 });
508+
ChannelFuture thirdFuture = ch.write(third);
509+
assertFalse(ch.isWritable());
510+
assertTrue(cancelled.cancel(false));
511+
512+
// Releasing the cancelled write makes the channel writable while addFlush() runs.
513+
ch.flush();
514+
ch.runPendingTasks();
515+
516+
assertFalse(ch.isOpen());
517+
assertEquals(1, inactive.get());
518+
assertEquals(0, cancelledBuf.refCnt());
519+
assertInstanceOf(ClosedChannelException.class, secondFuture.cause());
520+
assertInstanceOf(ClosedChannelException.class, thirdFuture.cause());
521+
assertEquals(0, second.refCnt());
522+
assertEquals(0, third.refCnt());
523+
assertNull(ch.readOutbound());
524+
assertFalse(ch.finish());
525+
}
526+
527+
private static void assertOutbound(EmbeddedChannel ch, int expected) {
528+
ByteBuf buf = ch.readOutbound();
529+
assertNotNull(buf);
530+
try {
531+
if (expected == 0) {
532+
assertEquals(0, buf.readableBytes());
533+
} else {
534+
assertEquals(1, buf.readableBytes());
535+
assertEquals(expected, buf.readByte());
536+
}
537+
} finally {
538+
buf.release();
539+
}
540+
}
541+
542+
@Test
543+
public void testMultipleCancelledWritesWithEarlierFlush() {
544+
final AtomicInteger writable = new AtomicInteger();
545+
final AtomicInteger sizeAtEvent = new AtomicInteger(-1);
546+
final AtomicLong pendingAtEvent = new AtomicLong(-1);
547+
final AtomicReference<Object> currentAtEvent = new AtomicReference<Object>();
548+
EmbeddedChannel ch = new EmbeddedChannel();
549+
final ChannelOutboundBuffer buffer = ch.unsafe().outboundBuffer();
550+
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
551+
@Override
552+
public void channelWritabilityChanged(ChannelHandlerContext ctx) {
553+
if (ctx.channel().isWritable()) {
554+
writable.incrementAndGet();
555+
sizeAtEvent.set(buffer.size());
556+
pendingAtEvent.set(buffer.totalPendingWriteBytes());
557+
currentAtEvent.set(buffer.current());
558+
}
559+
ctx.fireChannelWritabilityChanged();
560+
}
561+
});
562+
ch.config().setWriteBufferWaterMark(new WriteBufferWaterMark(400, 800));
563+
564+
// Use the ChannelOutboundBuffer directly so nothing is written and flushedEntry stays set after the flush.
565+
ByteBuf live0 = wrappedBuffer(new byte[] { 0 });
566+
buffer.addMessage(live0, 1, ch.newPromise());
567+
buffer.addFlush();
568+
assertEquals(1, buffer.size());
569+
assertSame(live0, buffer.current());
570+
571+
// Cancelled writes at the head, in the middle and at the tail of the second batch.
572+
ByteBuf[] cancelledBufs = new ByteBuf[3];
573+
ByteBuf[] liveBufs = new ByteBuf[2];
574+
ChannelPromise[] cancelledPromises = new ChannelPromise[3];
575+
for (int i = 0; i < 3; i++) {
576+
cancelledBufs[i] = buffer().writeZero(300);
577+
cancelledPromises[i] = ch.newPromise();
578+
buffer.addMessage(cancelledBufs[i], 300, cancelledPromises[i]);
579+
if (i < 2) {
580+
liveBufs[i] = wrappedBuffer(new byte[] { (byte) (i + 1) });
581+
buffer.addMessage(liveBufs[i], 1, ch.newPromise());
582+
}
583+
}
584+
assertFalse(ch.isWritable());
585+
for (ChannelPromise promise : cancelledPromises) {
586+
assertTrue(promise.cancel(false));
587+
}
588+
589+
buffer.addFlush();
590+
591+
assertEquals(1, writable.get());
592+
// The buffer must already be consistent when the event is fired.
593+
assertEquals(6, sizeAtEvent.get());
594+
assertEquals(buffer.totalPendingWriteBytes(), pendingAtEvent.get());
595+
assertSame(live0, currentAtEvent.get());
596+
assertEquals(6, buffer.size());
597+
assertTrue(ch.isWritable());
598+
for (ByteBuf cancelledBuf : cancelledBufs) {
599+
assertEquals(0, cancelledBuf.refCnt());
600+
}
601+
assertEquals(1, live0.refCnt());
602+
for (ByteBuf liveBuf : liveBufs) {
603+
assertEquals(1, liveBuf.refCnt());
604+
}
605+
606+
ch.close();
607+
assertEquals(0, live0.refCnt());
608+
for (ByteBuf liveBuf : liveBufs) {
609+
assertEquals(0, liveBuf.refCnt());
610+
}
611+
assertEquals(0, buffer.totalPendingWriteBytes());
612+
}
613+
614+
@Test
615+
public void testWriteAndFlushFromReleaseOfCancelledWrite() {
616+
final EmbeddedChannel ch = new EmbeddedChannel();
617+
final List<ChannelFuture> reentrantWrites = new ArrayList<ChannelFuture>();
618+
ReferenceCounted cancelledMsg = new AbstractReferenceCounted() {
619+
@Override
620+
protected void deallocate() {
621+
// Release of a cancelled write runs user code which writes and flushes on the same channel.
622+
reentrantWrites.add(ch.writeAndFlush(wrappedBuffer(new byte[] { 2 })));
623+
}
624+
625+
@Override
626+
public ReferenceCounted touch(Object hint) {
627+
return this;
628+
}
629+
};
630+
631+
ChannelFuture cancelled = ch.write(cancelledMsg);
632+
ChannelFuture second = ch.write(wrappedBuffer(new byte[] { 1 }));
633+
assertTrue(cancelled.cancel(false));
634+
635+
ch.flush();
636+
637+
assertEquals(1, reentrantWrites.size());
638+
assertEquals(0, cancelledMsg.refCnt());
639+
assertTrue(second.isSuccess());
640+
assertTrue(reentrantWrites.get(0).isSuccess());
641+
ChannelOutboundBuffer buffer = ch.unsafe().outboundBuffer();
642+
assertTrue(buffer.isEmpty());
643+
assertEquals(0, buffer.size());
644+
assertEquals(0, buffer.totalPendingWriteBytes());
645+
// The cancelled write is replaced by an empty buffer.
646+
assertOutbound(ch, 0);
647+
assertOutbound(ch, 1);
648+
assertOutbound(ch, 2);
649+
assertNull(ch.readOutbound());
650+
651+
assertFalse(ch.finish());
652+
assertFalse(ch.isOpen());
653+
}
654+
430655
@Test
431656
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
432657
public void testWriteTaskRejected() throws Exception {

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.