Skip to content

Commit a294089

Browse files
committed
Fix StackOverflowException with select expressions
* onSend/onReceive clauses on the same channel: Instead of StackOverflowError we throw IllegalStateException and leave the channel in the original state. * Fix SOE in select with "opposite channels" stress-test. The fix is based on the sequential numbering of atomic select operation. Deadlock is detected and the operation with the lower sequential number is aborted and restarted (with a larger number). Fixes #504 Fixes #1411
1 parent bf33052 commit a294089

23 files changed

+746
-324
lines changed

binary-compatibility-validator/reference-public-api/kotlinx-coroutines-core.txt

+9-2
Original file line numberDiff line numberDiff line change
@@ -1049,7 +1049,9 @@ public final class kotlinx/coroutines/selects/SelectBuilderImpl : kotlinx/corout
10491049
public fun performAtomicTrySelect (Lkotlinx/coroutines/internal/AtomicDesc;)Ljava/lang/Object;
10501050
public fun resumeSelectCancellableWithException (Ljava/lang/Throwable;)V
10511051
public fun resumeWith (Ljava/lang/Object;)V
1052-
public fun trySelect (Ljava/lang/Object;)Z
1052+
public fun toString ()Ljava/lang/String;
1053+
public fun trySelect ()Z
1054+
public fun trySelectOther (Lkotlinx/coroutines/internal/LockFreeLinkedListNode$PrepareOp;)Ljava/lang/Object;
10531055
}
10541056

10551057
public abstract interface class kotlinx/coroutines/selects/SelectClause0 {
@@ -1070,13 +1072,18 @@ public abstract interface class kotlinx/coroutines/selects/SelectInstance {
10701072
public abstract fun isSelected ()Z
10711073
public abstract fun performAtomicTrySelect (Lkotlinx/coroutines/internal/AtomicDesc;)Ljava/lang/Object;
10721074
public abstract fun resumeSelectCancellableWithException (Ljava/lang/Throwable;)V
1073-
public abstract fun trySelect (Ljava/lang/Object;)Z
1075+
public abstract fun trySelect ()Z
1076+
public abstract fun trySelectOther (Lkotlinx/coroutines/internal/LockFreeLinkedListNode$PrepareOp;)Ljava/lang/Object;
10741077
}
10751078

10761079
public final class kotlinx/coroutines/selects/SelectKt {
10771080
public static final fun select (Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
10781081
}
10791082

1083+
public synthetic class kotlinx/coroutines/selects/SelectKtSelectOpSequenceNumberRefVolatile {
1084+
public fun <init> (J)V
1085+
}
1086+
10801087
public final class kotlinx/coroutines/selects/SelectUnbiasedKt {
10811088
public static final fun selectUnbiased (Lkotlin/jvm/functions/Function1;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
10821089
}

kotlinx-coroutines-core/common/src/JobSupport.kt

+4-4
Original file line numberDiff line numberDiff line change
@@ -553,7 +553,7 @@ public open class JobSupport constructor(active: Boolean) : Job, ChildJob, Paren
553553
if (select.isSelected) return
554554
if (state !is Incomplete) {
555555
// already complete -- select result
556-
if (select.trySelect(null)) {
556+
if (select.trySelect()) {
557557
block.startCoroutineUnintercepted(select.completion)
558558
}
559559
return
@@ -1181,7 +1181,7 @@ public open class JobSupport constructor(active: Boolean) : Job, ChildJob, Paren
11811181
if (select.isSelected) return
11821182
if (state !is Incomplete) {
11831183
// already complete -- select result
1184-
if (select.trySelect(null)) {
1184+
if (select.trySelect()) {
11851185
if (state is CompletedExceptionally) {
11861186
select.resumeSelectCancellableWithException(state.cause)
11871187
}
@@ -1362,7 +1362,7 @@ private class SelectJoinOnCompletion<R>(
13621362
private val block: suspend () -> R
13631363
) : JobNode<JobSupport>(job) {
13641364
override fun invoke(cause: Throwable?) {
1365-
if (select.trySelect(null))
1365+
if (select.trySelect())
13661366
block.startCoroutineCancellable(select.completion)
13671367
}
13681368
override fun toString(): String = "SelectJoinOnCompletion[$select]"
@@ -1374,7 +1374,7 @@ private class SelectAwaitOnCompletion<T, R>(
13741374
private val block: suspend (T) -> R
13751375
) : JobNode<JobSupport>(job) {
13761376
override fun invoke(cause: Throwable?) {
1377-
if (select.trySelect(null))
1377+
if (select.trySelect())
13781378
job.selectAwaitCompletion(select, block)
13791379
}
13801380
override fun toString(): String = "SelectAwaitOnCompletion[$select]"

kotlinx-coroutines-core/common/src/channels/AbstractChannel.kt

+56-33
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
4646
protected open fun offerInternal(element: E): Any {
4747
while (true) {
4848
val receive = takeFirstReceiveOrPeekClosed() ?: return OFFER_FAILED
49-
val token = receive.tryResumeReceive(element, idempotent = null)
49+
val token = receive.tryResumeReceive(element, null)
5050
if (token != null) {
5151
receive.completeResumeReceive(token)
5252
return receive.offerResult
@@ -56,7 +56,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
5656

5757
/**
5858
* Tries to add element to buffer or to queued receiver if select statement clause was not selected yet.
59-
* Return type is `ALREADY_SELECTED | OFFER_SUCCESS | OFFER_FAILED | Closed`.
59+
* Return type is `ALREADY_SELECTED | OFFER_SUCCESS | OFFER_FAILED | RETRY_ATOMIC | Closed`.
6060
* @suppress **This is unstable API and it is subject to change.**
6161
*/
6262
protected open fun offerSelectInternal(element: E, select: SelectInstance<*>): Any {
@@ -362,10 +362,13 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
362362
else -> null
363363
}
364364

365-
override fun validatePrepared(node: ReceiveOrClosed<E>): Boolean {
366-
val token = node.tryResumeReceive(element, idempotent = this) ?: return false
365+
@Suppress("UNCHECKED_CAST")
366+
override fun onPrepare(prepareOp: PrepareOp): Any? {
367+
val affected = prepareOp.affected as ReceiveOrClosed<E> // see "failure" impl
368+
val token = affected.tryResumeReceive(element, prepareOp) ?: return REMOVE_PREPARED
369+
if (token === RETRY_ATOMIC) return RETRY_ATOMIC
367370
resumeToken = token
368-
return true
371+
return null
369372
}
370373
}
371374

@@ -398,6 +401,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
398401
when {
399402
offerResult === ALREADY_SELECTED -> return
400403
offerResult === OFFER_FAILED -> {} // retry
404+
offerResult === RETRY_ATOMIC -> {} // retry
401405
offerResult === OFFER_SUCCESS -> {
402406
block.startCoroutineUnintercepted(receiver = this, completion = select.completion)
403407
return
@@ -447,8 +451,8 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
447451
@JvmField val select: SelectInstance<R>,
448452
@JvmField val block: suspend (SendChannel<E>) -> R
449453
) : Send(), DisposableHandle {
450-
override fun tryResumeSend(idempotent: Any?): Any? =
451-
if (select.trySelect(idempotent)) SELECT_STARTED else null
454+
override fun tryResumeSend(otherOp: PrepareOp?): Any? =
455+
select.trySelectOther(otherOp)
452456

453457
override fun completeResumeSend(token: Any) {
454458
assert { token === SELECT_STARTED }
@@ -460,7 +464,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
460464
}
461465

462466
override fun resumeSendClosed(closed: Closed<*>) {
463-
if (select.trySelect(null))
467+
if (select.trySelect())
464468
select.resumeSelectCancellableWithException(closed.sendException)
465469
}
466470

@@ -471,7 +475,7 @@ internal abstract class AbstractSendChannel<E> : SendChannel<E> {
471475
@JvmField val element: E
472476
) : Send() {
473477
override val pollResult: Any? get() = element
474-
override fun tryResumeSend(idempotent: Any?): Any? = SEND_RESUMED
478+
override fun tryResumeSend(otherOp: PrepareOp?): Any? = SEND_RESUMED.also { otherOp?.finishPrepare() }
475479
override fun completeResumeSend(token: Any) { assert { token === SEND_RESUMED } }
476480
override fun resumeSendClosed(closed: Closed<*>) {}
477481
}
@@ -505,7 +509,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
505509
protected open fun pollInternal(): Any? {
506510
while (true) {
507511
val send = takeFirstSendOrPeekClosed() ?: return POLL_FAILED
508-
val token = send.tryResumeSend(idempotent = null)
512+
val token = send.tryResumeSend(null)
509513
if (token != null) {
510514
send.completeResumeSend(token)
511515
return send.pollResult
@@ -515,7 +519,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
515519

516520
/**
517521
* Tries to remove element from buffer or from queued sender if select statement clause was not selected yet.
518-
* Return type is `ALREADY_SELECTED | E | POLL_FAILED | Closed`
522+
* Return type is `ALREADY_SELECTED | E | POLL_FAILED | RETRY_ATOMIC | Closed`
519523
* @suppress **This is unstable API and it is subject to change.**
520524
*/
521525
protected open fun pollSelectInternal(select: SelectInstance<*>): Any? {
@@ -665,11 +669,13 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
665669
}
666670

667671
@Suppress("UNCHECKED_CAST")
668-
override fun validatePrepared(node: Send): Boolean {
669-
val token = node.tryResumeSend(idempotent = this) ?: return false
672+
override fun onPrepare(prepareOp: PrepareOp): Any? {
673+
val affected = prepareOp.affected as Send // see "failure" impl
674+
val token = affected.tryResumeSend(prepareOp) ?: return REMOVE_PREPARED
675+
if (token === RETRY_ATOMIC) return RETRY_ATOMIC
670676
resumeToken = token
671-
pollResult = node.pollResult as E
672-
return true
677+
pollResult = affected.pollResult as E
678+
return null
673679
}
674680
}
675681

@@ -691,6 +697,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
691697
when {
692698
pollResult === ALREADY_SELECTED -> return
693699
pollResult === POLL_FAILED -> {} // retry
700+
pollResult === RETRY_ATOMIC -> {} // retry
694701
pollResult is Closed<*> -> throw recoverStackTrace(pollResult.receiveException)
695702
else -> {
696703
block.startCoroutineUnintercepted(pollResult as E, select.completion)
@@ -719,9 +726,10 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
719726
when {
720727
pollResult === ALREADY_SELECTED -> return
721728
pollResult === POLL_FAILED -> {} // retry
729+
pollResult === RETRY_ATOMIC -> {} // retry
722730
pollResult is Closed<*> -> {
723731
if (pollResult.closeCause == null) {
724-
if (select.trySelect(null))
732+
if (select.trySelect())
725733
block.startCoroutineUnintercepted(null, select.completion)
726734
return
727735
} else {
@@ -756,6 +764,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
756764
when {
757765
pollResult === ALREADY_SELECTED -> return
758766
pollResult === POLL_FAILED -> {} // retry
767+
pollResult === RETRY_ATOMIC -> {} // retry
759768
pollResult is Closed<*> -> {
760769
block.startCoroutineUnintercepted(ValueOrClosed.closed(pollResult.closeCause), select.completion)
761770
}
@@ -880,7 +889,11 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
880889
}
881890

882891
@Suppress("IMPLICIT_CAST_TO_ANY")
883-
override fun tryResumeReceive(value: E, idempotent: Any?): Any? = cont.tryResume(resumeValue(value), idempotent)
892+
override fun tryResumeReceive(value: E, otherOp: PrepareOp?): Any? {
893+
otherOp?.finishPrepare()
894+
return cont.tryResume(resumeValue(value), otherOp?.desc)
895+
}
896+
884897
override fun completeResumeReceive(token: Any) = cont.completeResume(token)
885898
override fun resumeReceiveClosed(closed: Closed<*>) {
886899
when {
@@ -896,15 +909,16 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
896909
@JvmField val iterator: Itr<E>,
897910
@JvmField val cont: CancellableContinuation<Boolean>
898911
) : Receive<E>() {
899-
override fun tryResumeReceive(value: E, idempotent: Any?): Any? {
900-
val token = cont.tryResume(true, idempotent)
912+
override fun tryResumeReceive(value: E, otherOp: PrepareOp?): Any? {
913+
otherOp?.finishPrepare()
914+
val token = cont.tryResume(true, otherOp?.desc)
901915
if (token != null) {
902916
/*
903-
When idempotent != null this invocation can be stale and we cannot directly update iterator.result
917+
When otherOp != null this invocation can be stale and we cannot directly update iterator.result
904918
Instead, we save both token & result into a temporary IdempotentTokenValue object and
905919
set iterator result only in completeResumeReceive that is going to be invoked just once
906920
*/
907-
if (idempotent != null) return IdempotentTokenValue(token, value)
921+
if (otherOp != null) return IdempotentTokenValue(token, value)
908922
iterator.result = value
909923
}
910924
return token
@@ -938,8 +952,10 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
938952
@JvmField val block: suspend (Any?) -> R,
939953
@JvmField val receiveMode: Int
940954
) : Receive<E>(), DisposableHandle {
941-
override fun tryResumeReceive(value: E, idempotent: Any?): Any? =
942-
if (select.trySelect(idempotent)) (value ?: NULL_VALUE) else null
955+
override fun tryResumeReceive(value: E, otherOp: PrepareOp?): Any? {
956+
val result = select.trySelectOther(otherOp)
957+
return if (result === SELECT_STARTED) value ?: NULL_VALUE else result
958+
}
943959

944960
@Suppress("UNCHECKED_CAST")
945961
override fun completeResumeReceive(token: Any) {
@@ -948,7 +964,7 @@ internal abstract class AbstractChannel<E> : AbstractSendChannel<E>(), Channel<E
948964
}
949965

950966
override fun resumeReceiveClosed(closed: Closed<*>) {
951-
if (!select.trySelect(null)) return
967+
if (!select.trySelect()) return
952968
when (receiveMode) {
953969
RECEIVE_THROWS_ON_CLOSE -> select.resumeSelectCancellableWithException(closed.receiveException)
954970
RECEIVE_RESULT -> block.startCoroutine(ValueOrClosed.closed<R>(closed.closeCause), select.completion)
@@ -995,10 +1011,6 @@ internal val POLL_FAILED: Any = Symbol("POLL_FAILED")
9951011
@SharedImmutable
9961012
internal val ENQUEUE_FAILED: Any = Symbol("ENQUEUE_FAILED")
9971013

998-
@JvmField
999-
@SharedImmutable
1000-
internal val SELECT_STARTED: Any = Symbol("SELECT_STARTED")
1001-
10021014
@JvmField
10031015
@SharedImmutable
10041016
internal val NULL_VALUE: Symbol = Symbol("NULL_VALUE")
@@ -1022,7 +1034,11 @@ internal typealias Handler = (Throwable?) -> Unit
10221034
*/
10231035
internal abstract class Send : LockFreeLinkedListNode() {
10241036
abstract val pollResult: Any? // E | Closed
1025-
abstract fun tryResumeSend(idempotent: Any?): Any?
1037+
// Returns: null - failure,
1038+
// RETRY_ATOMIC for retry (only when otherOp != null),
1039+
// otherwise token for completeResumeSend
1040+
// Must call otherOp?.finishPrepare() before deciding on result other than RETRY_ATOMIC
1041+
abstract fun tryResumeSend(otherOp: PrepareOp?): Any?
10261042
abstract fun completeResumeSend(token: Any)
10271043
abstract fun resumeSendClosed(closed: Closed<*>)
10281044
}
@@ -1032,7 +1048,11 @@ internal abstract class Send : LockFreeLinkedListNode() {
10321048
*/
10331049
internal interface ReceiveOrClosed<in E> {
10341050
val offerResult: Any // OFFER_SUCCESS | Closed
1035-
fun tryResumeReceive(value: E, idempotent: Any?): Any?
1051+
// Returns: null - failure,
1052+
// RETRY_ATOMIC for retry (only when otherOp != null),
1053+
// otherwise token for completeResumeReceive
1054+
// Must call otherOp?.finishPrepare() before deciding on result other than RETRY_ATOMIC
1055+
fun tryResumeReceive(value: E, otherOp: PrepareOp?): Any?
10361056
fun completeResumeReceive(token: Any)
10371057
}
10381058

@@ -1044,7 +1064,10 @@ internal class SendElement(
10441064
override val pollResult: Any?,
10451065
@JvmField val cont: CancellableContinuation<Unit>
10461066
) : Send() {
1047-
override fun tryResumeSend(idempotent: Any?): Any? = cont.tryResume(Unit, idempotent)
1067+
override fun tryResumeSend(otherOp: PrepareOp?): Any? {
1068+
otherOp?.finishPrepare()
1069+
return cont.tryResume(Unit, otherOp?.desc)
1070+
}
10481071
override fun completeResumeSend(token: Any) = cont.completeResume(token)
10491072
override fun resumeSendClosed(closed: Closed<*>) = cont.resumeWithException(closed.sendException)
10501073
override fun toString(): String = "SendElement($pollResult)"
@@ -1061,9 +1084,9 @@ internal class Closed<in E>(
10611084

10621085
override val offerResult get() = this
10631086
override val pollResult get() = this
1064-
override fun tryResumeSend(idempotent: Any?): Any? = CLOSE_RESUMED
1087+
override fun tryResumeSend(otherOp: PrepareOp?): Any? = CLOSE_RESUMED.also { otherOp?.finishPrepare() }
10651088
override fun completeResumeSend(token: Any) { assert { token === CLOSE_RESUMED } }
1066-
override fun tryResumeReceive(value: E, idempotent: Any?): Any? = CLOSE_RESUMED
1089+
override fun tryResumeReceive(value: E, otherOp: PrepareOp?): Any? = CLOSE_RESUMED.also { otherOp?.finishPrepare() }
10671090
override fun completeResumeReceive(token: Any) { assert { token === CLOSE_RESUMED } }
10681091
override fun resumeSendClosed(closed: Closed<*>) = assert { false } // "Should be never invoked"
10691092
override fun toString(): String = "Closed[$closeCause]"

kotlinx-coroutines-core/common/src/channels/ArrayBroadcastChannel.kt

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
44

55
package kotlinx.coroutines.channels
@@ -105,7 +105,7 @@ internal class ArrayBroadcastChannel<E>(
105105
val size = this.size
106106
if (size >= capacity) return OFFER_FAILED
107107
// let's try to select sending this element to buffer
108-
if (!select.trySelect(null)) { // :todo: move trySelect completion outside of lock
108+
if (!select.trySelect()) { // :todo: move trySelect completion outside of lock
109109
return ALREADY_SELECTED
110110
}
111111
val tail = this.tail
@@ -163,7 +163,7 @@ internal class ArrayBroadcastChannel<E>(
163163
while (true) {
164164
send = takeFirstSendOrPeekClosed() ?: break // when when no sender
165165
if (send is Closed<*>) break // break when closed for send
166-
token = send!!.tryResumeSend(idempotent = null)
166+
token = send!!.tryResumeSend(null)
167167
if (token != null) {
168168
// put sent element to the buffer
169169
buffer[(tail % capacity).toInt()] = (send as Send).pollResult
@@ -245,7 +245,7 @@ internal class ArrayBroadcastChannel<E>(
245245
// find a receiver for an element
246246
receive = takeFirstReceiveOrPeekClosed() ?: break // break when no one's receiving
247247
if (receive is Closed<*>) break // noting more to do if this sub already closed
248-
token = receive.tryResumeReceive(result as E, idempotent = null)
248+
token = receive.tryResumeReceive(result as E, null)
249249
if (token == null) continue // bail out here to next iteration (see for next receiver)
250250
val subHead = this.subHead
251251
this.subHead = subHead + 1 // retrieved element for this subscriber
@@ -299,7 +299,7 @@ internal class ArrayBroadcastChannel<E>(
299299
result === POLL_FAILED -> { /* just bail out of lock */ }
300300
else -> {
301301
// let's try to select receiving this element from buffer
302-
if (!select.trySelect(null)) { // :todo: move trySelect completion outside of lock
302+
if (!select.trySelect()) { // :todo: move trySelect completion outside of lock
303303
result = ALREADY_SELECTED
304304
} else {
305305
// update subHead after retrieiving element from buffer

0 commit comments

Comments
 (0)