Skip to content

Commit 8836876

Browse files
authored
Fix potential UB in ByteString.hashCode (#208)
* Fix potential UB in ByteString.hashCode It has a benign JVM data-race on the hashCode field, but on K/N LLVM has no guarantees it will read default or written value (e.g. OoTA is one of the possibilities). The recommendation from K/N folks is to use @volatile here Fixes #190
1 parent dc63e3d commit 8836876

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

bytestring/common/src/-Platform.kt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/*
2+
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
3+
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
4+
*/
5+
package kotlinx.io.bytestring
6+
7+
/**
8+
* Annotation indicating that the marked property is the subject of benign data race.
9+
* LLVM does not support this notion, so on K/N platforms we alias it into `@Volatile` to prevent potential OoTA.
10+
*/
11+
@OptionalExpectation
12+
@Target(AnnotationTarget.FIELD)
13+
@OptIn(ExperimentalMultiplatform::class)
14+
internal expect annotation class BenignDataRace()

bytestring/common/src/ByteString.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ public class ByteString private constructor(
6969
public constructor(data: ByteArray, startIndex: Int = 0, endIndex: Int = data.size) :
7070
this(data.copyOfRange(startIndex, endIndex), null)
7171

72+
@BenignDataRace
7273
private var hashCode: Int = 0
7374

7475
public companion object {
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/*
2+
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
3+
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
4+
*/
5+
package kotlinx.io.bytestring
6+
7+
import kotlin.concurrent.*
8+
9+
@Suppress("ACTUAL_WITHOUT_EXPECT") // This suppress can be removed in 2.0: KT-59355
10+
internal actual typealias BenignDataRace = Volatile

0 commit comments

Comments
 (0)