NativeArgv.scala 985 Bytes
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5
package uvm.refimpl.cmdline

import uvm.refimpl.WORD_SIZE_BYTES
import uvm.refimpl.nat.NativeSupport

6
class NativeArgv(args: Seq[String]) extends AutoCloseable {
Kunshan Wang's avatar
Kunshan Wang committed
7 8 9 10 11 12 13
  val argc = args.size

  private val argvSB = new StringBuilder()
  private val argvOffs = new Array[Long](argc)
  
  for ((arg, i) <- (args).zipWithIndex) {
    argvOffs(i) = argvSB.length
14
    argvSB ++= arg += '\u0000'
Kunshan Wang's avatar
Kunshan Wang committed
15 16
  }

17 18 19 20 21
  val cArgvMem = NativeSupport.allocateManual(argvOffs.length * WORD_SIZE_BYTES.toInt)
  val cArgvBufMem = NativeSupport.allocateManual(argvSB.length)

  val cArgv = cArgvMem.asJnrPointer()
  val cArgvBuf = cArgvBufMem.asJnrPointer()
Kunshan Wang's avatar
Kunshan Wang committed
22 23 24 25 26 27 28 29 30

  for (i <- 0 until argvOffs.length) {
    cArgv.putAddress(i * WORD_SIZE_BYTES, cArgvBuf.address() + argvOffs(i))
  }
  for (i <- 0 until argvSB.length) {
    cArgvBuf.putByte(i, argvSB.charAt(i).toByte)    // Assume single-byte encoding
  }
  
  val argv = cArgv.address()
31 32 33 34 35
  
  override def close(): Unit = {
    cArgvBufMem.close()
    cArgvMem.close()
  }
Kunshan Wang's avatar
Kunshan Wang committed
36
}