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 — pipeline5 by normanmaurer · Pull Request #17671 · netty/netty

pipeline5 #17671

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
normanmaurer wants to merge 2 commits into 5.0 from pipeline5

Uh oh!

There was an error while loading. Please reload this page.

Closed

pipeline5 #17671

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit Hold shift + click to select a range
eb25c1b
Don't leak FixedChannelPool slots on unrelated IllegalArgumentExcepti…
allthingssecurity Sep 29, 2026
b7f8b13
Port: Don't corrupt the pipeline when a handler context is removed tw…
allthingssecurity Sep 29, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Port: Don't corrupt the pipeline when a handler context is removed tw…
…ice (#17643)

Motivation:

`DefaultChannelPipeline.atomicRemoveFromHandlerList(...)` is not
idempotent. A removed context keeps its `prev` / `next` pointers, and
`replace0(...)` leaves the old context with `prev = next = newCtx`.
Unlinking such a context a second time writes its stale neighbours back
into the list. For a replaced context the replacement then points to
itself.

There are three ways to get there:

1. `remove(handler)` / `replace(handler, ...)` look up the context
outside of the pipeline lock. Two threads that remove or replace the
same handler can both find the context and both unlink it. In a stress
harness (two threads running `remove(x)` and `replace(x -> y)` on a
`LocalChannel`), the list was corrupted after a few thousand iterations.
2. `callHandlerAdded0(...)` unlinks the context when `handlerAdded(...)`
throws, even if `handlerAdded(...)` already replaced or removed its own
handler. The same happens when a handler is replaced before the channel
is registered and its deferred `handlerAdded(...)` throws at
registration. Afterwards `fireChannelRead(...)` loops forever in
`findContextInbound(...)`.
3. `destroyDown(...)` unlinks a context that a `handlerRemoved(...)`
callback of a handler further down the pipeline has replaced. `close()`
then spins forever in `destroyDown(...)` and pins the event loop.

Modification:

- `atomicRemoveFromHandlerList(...)` checks under the lock that the
context is still linked (`ctx.prev.next == ctx`) and does nothing,
returning `false`, if it is not.
- `remove(...)` and `replace(...)` throw `NoSuchElementException` when
the context was removed or replaced after it was looked up, the same as
for a handler that is not in the pipeline. `removeIfExists(...)` returns
`null` in that case.
- `callHandlerAdded0(...)` and `destroyDown(...)` skip a context that is
no longer linked. Whoever unlinked it is already responsible for calling
`handlerRemoved(...)`, so it is still called exactly once.
- No public API changes.

Added tests to `DefaultChannelPipelineTest`:

- `testHandlerAddedReplacesItselfAndThrows` (path 2)
- `testHandlerReplacedBeforeRegistrationAndHandlerAddedThrows` (path 2,
deferred `handlerAdded`)
- `testCloseWhenHandlerRemovedReplacesOtherHandler` (path 3)
- `testRemoveOfHandlerReplacedConcurrently` (path 1, made deterministic
by holding the pipeline lock until the removing thread has looked up the
context and is blocked on the lock)
- `testHandlerAddedRemovesItselfAndThrows` (the
remove-instead-of-replace variant of path 2; this one already passed
before, since the list happened to stay consistent, and is added for
coverage)

The tests check that the list is consistent, that events still reach the
replacement handler and the tail, and that `handlerAdded` /
`handlerRemoved` are each called once. Without the fix, three of the
first four time out and `testRemoveOfHandlerReplacedConcurrently` fails.

Result:

The pipeline stays consistent when a handler context is removed more
than once, and none of the three paths can hang the channel anymore.

Behaviour change: when two threads race to remove or replace the same
handler, the call that loses now throws `NoSuchElementException` (as
documented on `ChannelPipeline.remove(...)` / `replace(...)` for a
handler that is not in the pipeline) instead of also "succeeding" and
corrupting the list. A call that comes slightly later already got this
exception before this change.

Also, `PendingHandlerAddedTask`'s rejected-executor path, which unlinks
the context, can no longer unlink a context that was removed before
registration a second time.
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@allthingssecurity @normanmaurer
allthingssecurity authored and normanmaurer committed Sep 29, 2026
commit b7f8b135172cbf61ba35eb89ee3685b6cf803120

There are no files selected for viewing

64 changes: 53 additions & 11 deletions 64 transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -358,24 +358,40 @@ public final <T extends ChannelHandler> T removeIfExists(ChannelHandler handler)

@SuppressWarnings("unchecked")
private <T extends ChannelHandler> T removeIfExists(ChannelHandlerContext ctx) {
if (ctx == null) {
if (ctx == null || !tryRemove((AbstractChannelHandlerContext) ctx)) {
return null;
}
return (T) remove((AbstractChannelHandlerContext) ctx).handler();
return (T) ctx.handler();
}

private AbstractChannelHandlerContext remove(final AbstractChannelHandlerContext ctx) {
if (!tryRemove(ctx)) {
// The context was removed or replaced concurrently after it was looked up.
throw new NoSuchElementException(ctx.name());
}
return ctx;
}

/**
* Removes the given context from the pipeline and schedules the call of
* {@link ChannelHandler#handlerRemoved(ChannelHandlerContext)}.
*
* @return {@code false} if the context was not part of the pipeline anymore, in which case nothing is done.
*/
private boolean tryRemove(final AbstractChannelHandlerContext ctx) {
assert ctx != head && ctx != tail;

synchronized (this) {
atomicRemoveFromHandlerList(ctx);
if (!atomicRemoveFromHandlerList(ctx)) {
return false;
}

// If the registered is false it means that the channel was not registered on an eventloop yet.
// In this case we remove the context from the pipeline and add a task that will call
// ChannelHandler.handlerRemoved(...) once the channel is registered.
if (!registered) {
callHandlerCallbackLater(ctx, false);
return ctx;
return true;
}

EventExecutor executor = ctx.executor();
Expand All @@ -386,21 +402,38 @@ public void run() {
callHandlerRemoved0(ctx);
}
});
return ctx;
return true;
}
}
callHandlerRemoved0(ctx);
return ctx;
return true;
}

/**
* Returns {@code true} if the given context is still linked into the pipeline. A removed context keeps its
* {@code prev} and {@code next} pointers (and a replaced context points to its replacement), so the check must
* be done by looking at the neighbour.
*/
private boolean isLinked(AbstractChannelHandlerContext ctx) {
assert Thread.holdsLock(this);
return ctx.prev.next == ctx;
}

/**
* Method is synchronized to make the handler removal from the double linked list atomic.
*
* @return {@code false} if the context was already removed or replaced, in which case the list is not modified.
*/
private synchronized void atomicRemoveFromHandlerList(AbstractChannelHandlerContext ctx) {
private synchronized boolean atomicRemoveFromHandlerList(AbstractChannelHandlerContext ctx) {
if (!isLinked(ctx)) {
// Unlinking the context again would link its stale neighbours back into the pipeline.
return false;
}
AbstractChannelHandlerContext prev = ctx.prev;
AbstractChannelHandlerContext next = ctx.next;
prev.next = next;
next.prev = prev;
return true;
}

@Override
Expand Down Expand Up @@ -443,6 +476,10 @@ private ChannelHandler replace(

final AbstractChannelHandlerContext newCtx;
synchronized (this) {
if (!isLinked(ctx)) {
// The context was removed or replaced concurrently after it was looked up.
throw new NoSuchElementException(ctx.name());
}
checkMultiplicity(newHandler);
if (newName == null) {
newName = generateName(newHandler);
Expand Down Expand Up @@ -517,8 +554,11 @@ private void callHandlerAdded0(final AbstractChannelHandlerContext ctx) {
} catch (Throwable t) {
boolean removed = false;
try {
atomicRemoveFromHandlerList(ctx);
ctx.callHandlerRemoved(t);
// If handlerAdded(...) already removed or replaced the handler, whoever did that is responsible for
// calling handlerRemoved(...).
if (atomicRemoveFromHandlerList(ctx)) {
ctx.callHandlerRemoved(t);
}
removed = true;
} catch (Throwable t2) {
if (logger.isWarnEnabled()) {
Expand Down Expand Up @@ -806,8 +846,10 @@ private void destroyDown(Thread currentThread, AbstractChannelHandlerContext ctx

final EventExecutor executor = ctx.executor();
if (inEventLoop || executor.inEventLoop(currentThread)) {
atomicRemoveFromHandlerList(ctx);
callHandlerRemoved0(ctx);
// Skip a context that a handlerRemoved(...) callback already removed or replaced.
if (atomicRemoveFromHandlerList(ctx)) {
callHandlerRemoved0(ctx);
}
} else {
final AbstractChannelHandlerContext finalCtx = ctx;
executor.execute(new Runnable() {
Expand Down
246 changes: 246 additions & 0 deletions 246 transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
Expand Down Expand Up @@ -1878,6 +1880,250 @@ public void write(ChannelHandlerContext ctx, Object msg, CompletionHandler<Void>
doneLatch.await();
}

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public void testHandlerAddedReplacesItselfAndThrows() throws Exception {
final LifecycleCountingHandler replacement = new LifecycleCountingHandler();
final AtomicInteger removed = new AtomicInteger();
final IllegalStateException error = new IllegalStateException();
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast("first", new ChannelInboundHandler() { });
channel.pipeline().addLast("boot", new ChannelInboundHandler() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
ctx.pipeline().replace(this, "real", replacement);
throw error;
}

@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
removed.incrementAndGet();
}
});
assertThatThrownBy(channel::checkException)
.isInstanceOf(ChannelPipelineException.class)
.cause().isSameAs(error);

assertPipelineLinked(channel.pipeline(), "first", "real");
assertThat(removed).as("handlerRemoved(...) calls of the replaced handler").hasValue(1);
assertThat(replacement.added).as("handlerAdded(...) calls of the replacement").hasValue(1);
assertThat(replacement.removed).as("handlerRemoved(...) calls of the replacement").hasValue(0);

Object msg = new Object();
assertThat(channel.writeInbound(msg)).isTrue();
assertThat(replacement.read).as("channelRead(...) calls of the replacement").hasValue(1);
assertThat(channel.<Object>readInbound()).isSameAs(msg);

assertThat(channel.finish()).isFalse();
assertThat(removed).as("handlerRemoved(...) calls of the replaced handler").hasValue(1);
assertThat(replacement.removed).as("handlerRemoved(...) calls of the replacement").hasValue(1);
}

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public void testHandlerAddedRemovesItselfAndThrows() throws Exception {
final AtomicInteger removed = new AtomicInteger();
final IllegalStateException error = new IllegalStateException();
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast("first", new ChannelInboundHandler() { });
channel.pipeline().addLast("boot", new ChannelInboundHandler() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
ctx.pipeline().remove(this);
throw error;
}

@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
removed.incrementAndGet();
}
});
channel.pipeline().addLast("last", new ChannelInboundHandler() { });
assertThatThrownBy(channel::checkException)
.isInstanceOf(ChannelPipelineException.class)
.cause().isSameAs(error);

assertPipelineLinked(channel.pipeline(), "first", "last");
assertThat(removed).as("handlerRemoved(...) calls of the removed handler").hasValue(1);

Object msg = new Object();
assertThat(channel.writeInbound(msg)).isTrue();
assertThat(channel.<Object>readInbound()).isSameAs(msg);
assertThat(channel.finish()).isFalse();
assertThat(removed).as("handlerRemoved(...) calls of the removed handler").hasValue(1);
}

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public void testHandlerReplacedBeforeRegistrationAndHandlerAddedThrows() throws Exception {
final LifecycleCountingHandler replacement = new LifecycleCountingHandler();
final AtomicInteger removed = new AtomicInteger();
final IllegalStateException error = new IllegalStateException();
EmbeddedChannel channel = new EmbeddedChannel(false, false);
channel.pipeline().addLast("handler", new ChannelInboundHandler() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
throw error;
}

@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
removed.incrementAndGet();
}
});
channel.pipeline().replace("handler", "replacement", replacement);
// The deferred handlerAdded(...) of the replaced handler throws once the channel is registered.
channel.register();
assertThatThrownBy(channel::checkException)
.isInstanceOf(ChannelPipelineException.class)
.cause().isSameAs(error);

assertPipelineLinked(channel.pipeline(), "replacement");
assertThat(removed).as("handlerRemoved(...) calls of the replaced handler").hasValue(1);
assertThat(replacement.added).as("handlerAdded(...) calls of the replacement").hasValue(1);

Object msg = new Object();
assertThat(channel.writeInbound(msg)).isTrue();
assertThat(replacement.read).as("channelRead(...) calls of the replacement").hasValue(1);
assertThat(channel.<Object>readInbound()).isSameAs(msg);

assertThat(channel.finish()).isFalse();
assertThat(removed).as("handlerRemoved(...) calls of the replaced handler").hasValue(1);
assertThat(replacement.removed).as("handlerRemoved(...) calls of the replacement").hasValue(1);
}

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public void testCloseWhenHandlerRemovedReplacesOtherHandler() {
final LifecycleCountingHandler handler = new LifecycleCountingHandler();
final LifecycleCountingHandler replacement = new LifecycleCountingHandler();
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast("handler", handler);
channel.pipeline().addLast("replacing", new ChannelInboundHandler() {
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
ctx.pipeline().replace("handler", "replacement", replacement);
}
});

assertThat(channel.close().isSuccess()).as("close() succeeded").isTrue();

assertPipelineLinked(channel.pipeline());
assertThat(handler.added).as("handlerAdded(...) calls of the replaced handler").hasValue(1);
assertThat(handler.removed).as("handlerRemoved(...) calls of the replaced handler").hasValue(1);
assertThat(replacement.added).as("handlerAdded(...) calls of the replacement").hasValue(1);
assertThat(replacement.removed).as("handlerRemoved(...) calls of the replacement").hasValue(1);
}

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public void testRemoveOfHandlerReplacedConcurrently() throws Exception {
// remove(...) and replace(...) look up the context before they take the pipeline lock, so run them
// concurrently many times to hit the window in which one of them works on a context that the other one has
// already unlinked.
for (int i = 0; i < 2000; i++) {
final LifecycleCountingHandler handler = new LifecycleCountingHandler();
final LifecycleCountingHandler replacement = new LifecycleCountingHandler();
EmbeddedChannel channel = new EmbeddedChannel();
final ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("before", new ChannelInboundHandler() { });
pipeline.addLast("handler", handler);
pipeline.addLast("after", new ChannelInboundHandler() { });

final AtomicInteger ready = new AtomicInteger();
final AtomicReference<Throwable> removeResult = new AtomicReference<>();
final AtomicBoolean removed = new AtomicBoolean();
Thread remover = new Thread(() -> {
awaitOtherThread(ready);
try {
pipeline.remove(handler);
removed.set(true);
} catch (Throwable cause) {
removeResult.set(cause);
}
});
remover.start();
awaitOtherThread(ready);
Throwable replaceResult = null;
try {
pipeline.replace(handler, "replacement", replacement);
} catch (Throwable cause) {
replaceResult = cause;
}
remover.join();

// Exactly one of remove(...) and replace(...) wins, the other one fails as if the handler was never
// part of the pipeline.
if (removed.get()) {
assertThat(replaceResult).as("result of replace(...) after remove(...) won (iteration %d)", i)
.isInstanceOf(NoSuchElementException.class);
assertPipelineLinked(pipeline, "before", "after");
assertThat(replacement.added).as("handlerAdded(...) calls of the replacement").hasValue(0);
} else {
assertThat(removeResult.get()).as("result of remove(...) after replace(...) won (iteration %d)", i)
.isInstanceOf(NoSuchElementException.class);
assertThat(replaceResult).as("result of replace(...) (iteration %d)", i).isNull();
assertPipelineLinked(pipeline, "before", "replacement", "after");
assertThat(replacement.added).as("handlerAdded(...) calls of the replacement").hasValue(1);
}
assertThat(handler.removed).as("handlerRemoved(...) calls of the handler (iteration %d)", i).hasValue(1);
assertThat(replacement.removed).as("handlerRemoved(...) calls of the replacement").hasValue(0);

assertThat(channel.finish()).isFalse();
assertThat(handler.removed).as("handlerRemoved(...) calls of the handler (iteration %d)", i).hasValue(1);
assertThat(replacement.removed).as("handlerRemoved(...) calls of the replacement")
.hasValue(removed.get() ? 0 : 1);
}
}

private static void awaitOtherThread(AtomicInteger ready) {
// Spin instead of blocking so both threads start at (nearly) the same time.
ready.incrementAndGet();
while (ready.get() < 2) {
Thread.yield();
}
}

private static void assertPipelineLinked(ChannelPipeline pipeline, String... expectedNames) {
DefaultChannelPipeline p = (DefaultChannelPipeline) pipeline;
List<String> names = new ArrayList<>();
AbstractChannelHandlerContext ctx = p.head;
while (ctx != p.tail) {
AbstractChannelHandlerContext next = ctx.next;
assertThat(next).as("next of %s (self-loop)", ctx.name()).isNotSameAs(ctx);
assertThat(next.prev).as("prev of %s", next.name()).isSameAs(ctx);
if (next != p.tail) {
names.add(next.name());
// Stop early if the list contains a cycle.
assertThat(names).as("handlers in the pipeline").hasSizeLessThanOrEqualTo(expectedNames.length);
}
ctx = next;
}
assertThat(names).as("handlers in the pipeline").containsExactly(expectedNames);
}

private static final class LifecycleCountingHandler implements ChannelInboundHandler {
final AtomicInteger added = new AtomicInteger();
final AtomicInteger removed = new AtomicInteger();
final AtomicInteger read = new AtomicInteger();

@Override
public void handlerAdded(ChannelHandlerContext ctx) {
added.incrementAndGet();
}

@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
removed.incrementAndGet();
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
read.incrementAndGet();
ctx.fireChannelRead(msg);
}
}

private static final class TestTask implements Runnable {

private final ChannelPipeline pipeline;
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
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.