Skip to content

Commit

Permalink
runtime (chan): fix blocking select on a nil channel
Browse files Browse the repository at this point in the history
Previously, a blocking select on a nil channel would result in a nil panic inside the channel runtime code.
This change fixes the nil checks so that the select works as intended.
  • Loading branch information
niaow authored and deadprogram committed Apr 13, 2020
1 parent 9890c76 commit 9c78f70
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/runtime/chan.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,12 @@ func (b *channelBlockedList) detach() {
}
for i, v := range b.allSelectOps {
// cancel all other channel operations that are part of this select statement
if &b.allSelectOps[i] == b {
switch {
case &b.allSelectOps[i] == b:
// This entry is the one that was already detatched.
continue
}
if v.s.ch == nil {
case v.t == nil:
// This entry is not used (nil channel).
continue
}
v.s.ch.blocked = v.s.ch.blocked.remove(&b.allSelectOps[i])
Expand Down Expand Up @@ -512,6 +514,13 @@ func chanSelect(recvbuf unsafe.Pointer, states []chanSelectState, ops []channelB

// construct blocked operations
for i, v := range states {
if v.ch == nil {
// A nil channel receive will never complete.
// A nil channel send would have panicked during tryChanSelect.
ops[i] = channelBlockedList{}
continue
}

ops[i] = channelBlockedList{
next: v.ch.blocked,
t: task.Current(),
Expand Down
2 changes: 2 additions & 0 deletions testdata/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ func main() {
select {
case make(chan int) <- 3:
println("unreachable")
case <-(chan int)(nil):
println("unreachable")
case n := <-ch:
println("select n from chan:", n)
case n := <-make(chan int):
Expand Down

0 comments on commit 9c78f70

Please sign in to comment.