NativeMemoryAccessHelper.scala 1.48 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
package uvm.refimpl.nat

import java.nio.charset.StandardCharsets

object NativeMemoryAccessHelper {
  import NativeSupport._
  val MAX_NAME_SIZE = 65536

  def readCString(addr: Long): String = {
    val str = theMemory.getString(addr, MAX_NAME_SIZE, StandardCharsets.US_ASCII)
    str
  }
  
  def readCStringArray(base: Long, len: Long): IndexedSeq[String] = readLongArray(base, len).map(readCString)
  
  def readCStringOptional(addr: Long): Option[String] = {
    if (addr == 0L) None else Some(readCString(addr))
  }

  def readCharArray(base: Long, len: Long): String = {
    require(len <= Int.MaxValue, "Currently Mu refimpl2 only supports string length with 32-bit range")
    val str = theMemory.getString(base, len.toInt, StandardCharsets.US_ASCII)
    str
  }
  
  def unsignedLongSeqToBigInt(nums: Seq[Long]): BigInt = {
      var bigNum = BigInt(0)
      for (num <- nums) {
        bigNum = (bigNum << 64) | (BigInt(num) & 0xffffffffffffffffL)
      }
      bigNum
  }

  def readIntArray(base: Long, len: Long): IndexedSeq[Int] = {
    if (base == 0L) {
      IndexedSeq[Int]()
    } else {
      for (i <- 0L until len) yield {
        val addr = base + i * 4L
        val v = theMemory.getInt(addr)
        v
      }
    }
  }

  def readLongArray(base: Long, len: Long): IndexedSeq[Long] = {
    if (base == 0L) {
      IndexedSeq[Long]()
    } else {
      for (i <- 0L until len) yield {
        val addr = base + i * 8L
        val v = theMemory.getLong(addr)
        v
      }
    }
  }
  
}