Skip to content

Commit

Permalink
check target array length before allocating.
Browse files Browse the repository at this point in the history
  • Loading branch information
counter2015 committed Oct 28, 2024
1 parent ecf93db commit 11d63c6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
13 changes: 12 additions & 1 deletion core/jvm-native/src/main/scala/cats/effect/ArrayStack.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package cats.effect

import Platform.static
import PlatformStatics.VM_MaxArraySize

private final class ArrayStack[A <: AnyRef](
private[this] var buffer: Array[AnyRef],
Expand Down Expand Up @@ -72,7 +73,17 @@ private final class ArrayStack[A <: AnyRef](
private[this] def checkAndGrow(): Unit =
if (index >= buffer.length) {
val len = buffer.length
val buffer2 = new Array[AnyRef](len * 2)
val targetLen = len * 2

val resizeLen =
if (targetLen < 0)
throw new Exception(s"Overflow while resizing array. Request length: $targetLen")
else if (len > VM_MaxArraySize / 2)
VM_MaxArraySize
else
targetLen

val buffer2 = new Array[AnyRef](resizeLen)
System.arraycopy(buffer, 0, buffer2, 0, len)
buffer = buffer2
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package cats.effect

// copy from scala.runtime.PStatics
private[effect] object PlatformStatics {
// `Int.MaxValue - 8` traditional soft limit to maximize compatibility with diverse JVMs
// See https://stackoverflow.com/a/8381338 for example
final val VM_MaxArraySize = 2147483639
}

0 comments on commit 11d63c6

Please sign in to comment.