clientInterface.scala 14.8 KB
Newer Older
1 2 3 4 5 6
package uvm.refimpl

import uvm.types._
import uvm.refimpl.itpr._
import java.io.Reader
import scala.collection.mutable.HashSet
7
import uvm.refimpl.mem.TypeSizes._
8 9
import uvm.ssavariables.MemoryOrder._
import uvm.ssavariables.AtomicRMWOptr._
10
import uvm.refimpl.mem._
11
import uvm.ssavariables.HasKeepAliveClause
12 13 14

case class Handle(ty: Type, vb: ValueBox)

Kunshan Wang's avatar
Kunshan Wang committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28
abstract class TrapHandlerResult
case class TrapExit() extends TrapHandlerResult
case class TrapRebindPassValue(newStack: Handle, value: Handle) extends TrapHandlerResult
case class TrapRebindPassVoid(newStack: Handle) extends TrapHandlerResult
case class TrapRebindThrowExc(newStack: Handle, exc: Handle) extends TrapHandlerResult

trait TrapHandler {
  def handleTrap(ca: ClientAgent, thread: Handle, stack: Handle, watchPointID: Int): TrapHandlerResult
}

trait UndefinedFunctionHandler {
  def handleUndefinedFunction(functionID: Int): Unit
}

29 30 31
class ClientAgent(microVM: MicroVM) {
  val handles = new HashSet[Handle]()

Kunshan Wang's avatar
Kunshan Wang committed
32
  microVM.clientAgents.add(this)
33

34 35
  val mutator = microVM.memoryManager.heap.makeMutator()

36 37
  def close(): Unit = {
    handles.clear()
38
    mutator.close()
Kunshan Wang's avatar
Kunshan Wang committed
39
    microVM.clientAgents.remove(this)
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
  }

  def loadBundle(r: Reader): Unit = {
    val bundle = microVM.irReader.read(r, microVM.globalBundle)
    microVM.addBundle(bundle)
  }

  private def newHandle(t: Type, vb: ValueBox): Handle = {
    val handle = Handle(t, vb)
    handles.add(handle)
    return handle
  }

  def putInt(typeID: Int, v: BigInt): Handle = {
    val t = microVM.globalBundle.typeNs(typeID).asInstanceOf[TypeInt]
55
    val preparedV = OpHelper.unprepare(v, t.length)
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    newHandle(t, BoxInt(preparedV))
  }

  def putFloat(typeID: Int, v: Float): Handle = {
    val t = microVM.globalBundle.typeNs(typeID).asInstanceOf[TypeFloat]
    newHandle(t, BoxFloat(v))
  }

  def putDouble(typeID: Int, v: Double): Handle = {
    val t = microVM.globalBundle.typeNs(typeID).asInstanceOf[TypeDouble]
    newHandle(t, BoxDouble(v))
  }

  def putIntVec(typeID: Int, vs: Seq[BigInt]): Handle = {
    val t = microVM.globalBundle.typeNs(typeID).asInstanceOf[TypeVector]
    val et = t.elemTy.asInstanceOf[TypeInt]
    val preparedVs = for (v <- vs) yield OpHelper.trunc(v, et.length)
    newHandle(t, BoxVector(preparedVs.map(BoxInt)))
  }

  def putFloatVec(typeID: Int, vs: Seq[Float]): Handle = {
    val t = microVM.globalBundle.typeNs(typeID).asInstanceOf[TypeVector]
    val et = t.elemTy.asInstanceOf[TypeFloat]
    newHandle(t, BoxVector(vs.map(BoxFloat)))
  }

  def putDoubleVec(typeID: Int, vs: Seq[Double]): Handle = {
    val t = microVM.globalBundle.typeNs(typeID).asInstanceOf[TypeVector]
    val et = t.elemTy.asInstanceOf[TypeDouble]
    newHandle(t, BoxVector(vs.map(BoxDouble)))
  }

  def putConstant(id: Int): Handle = {
    val c = microVM.globalBundle.constantNs(id)
    val t = c.constTy
    val box = microVM.constantPool.getGlobalVarBox(c)
    newHandle(t, box)
  }

  def putGlobal(id: Int): Handle = {
    val g = microVM.globalBundle.globalCellNs(id)
    val t = InternalTypePool.irefOf(g.cellTy)
    val a = microVM.memoryManager.globalMemory.addrForGlobalCell(g)
    val box = BoxIRef(0L, a)
    newHandle(t, box)
  }

  def putFunction(id: Int): Handle = {
    val f = microVM.globalBundle.funcNs(id)
    val t = InternalTypePool.funcOf(f.sig)
    val box = BoxFunc(Some(f))
    newHandle(t, box)
  }

  def deleteHandle(h: Handle): Unit = {
    handles.remove(h)
  }

  def toInt(h: Handle, signExt: Boolean = false): BigInt = {
    val t = h.ty.asInstanceOf[TypeInt]
    val ib = h.vb.asInstanceOf[BoxInt]
    if (signExt) OpHelper.prepareSigned(ib.value, t.length) else OpHelper.prepareUnsigned(ib.value, t.length)
  }

  def toFloat(h: Handle): Float = {
    h.vb.asInstanceOf[BoxFloat].value
  }

  def toDouble(h: Handle): Double = {
    h.vb.asInstanceOf[BoxDouble].value
  }

  def toIntVec(h: Handle, signExt: Boolean = false): Seq[BigInt] = {
    val t = h.ty.asInstanceOf[TypeVector]
    val et = t.elemTy.asInstanceOf[TypeInt]
    val bv = h.vb.asInstanceOf[BoxVector]
    for (b <- bv.values) yield {
      val ib = b.asInstanceOf[BoxInt]
      if (signExt) OpHelper.prepareSigned(ib.value, et.length) else OpHelper.prepareUnsigned(ib.value, et.length)
    }
  }

  def toFloatVec(h: Handle): Seq[Float] = {
    h.vb.asInstanceOf[BoxVector].values.map(b => b.asInstanceOf[BoxFloat].value)
  }

  def toDoubleVec(h: Handle): Seq[Double] = {
    h.vb.asInstanceOf[BoxVector].values.map(b => b.asInstanceOf[BoxDouble].value)
  }

  def extractValue(str: Handle, index: Int): Handle = {
    val st = str.ty.asInstanceOf[TypeStruct]
    val sb = str.vb.asInstanceOf[BoxStruct]
    val et = st.fieldTy(index)
    val eb = sb.values(index)
    newHandle(et, eb)
  }

  def insertValue(str: Handle, index: Int, newVal: Handle): Handle = {
    val st = str.ty.asInstanceOf[TypeStruct]
    val sb = str.vb.asInstanceOf[BoxStruct]
    val nsb = BoxStruct(for ((b, i) <- sb.values.zipWithIndex) yield if (i == index) newVal.vb else b)
    newHandle(st, nsb)
  }
160 161

  def newFixed(tid: Int): Handle = {
162 163 164 165 166
    val t = microVM.globalBundle.typeNs(tid)
    val objRef = mutator.newScalar(t)
    val b = BoxRef(objRef)
    val rt = InternalTypePool.refOf(t)
    newHandle(rt, b)
167 168 169
  }

  def newHybrid(tid: Int, length: Handle): Handle = {
170 171 172 173 174 175
    val t = microVM.globalBundle.typeNs(tid).asInstanceOf[TypeHybrid]
    val len = toInt(length).longValue
    val objRef = mutator.newHybrid(t, len)
    val b = BoxRef(objRef)
    val rt = InternalTypePool.refOf(t)
    newHandle(rt, b)
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
  }

  def refCast(handle: Handle, newType: Int): Handle = {
    val t = microVM.globalBundle.typeNs(newType)
    newHandle(t, handle.vb)
  }

  def getIRef(handle: Handle): Handle = {
    val t = handle.ty.asInstanceOf[TypeRef]
    val nt = InternalTypePool.irefOf(t.ty)
    val ob = handle.vb.asInstanceOf[BoxRef]
    val nb = BoxIRef(ob.objRef, 0L)
    newHandle(nt, nb)
  }

  def getFieldIRef(handle: Handle, index: Int): Handle = {
    val t = handle.ty.asInstanceOf[TypeIRef]
    val st = t.ty.asInstanceOf[TypeStruct]
    val ft = st.fieldTy(index)
    val nt = InternalTypePool.irefOf(ft)
    val ob = handle.vb.asInstanceOf[BoxIRef]
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.fieldOffsetOf(st, index))
    newHandle(nt, nb)
  }

  def getElemIRef(handle: Handle, index: Handle): Handle = {
    val t = handle.ty.asInstanceOf[TypeIRef]
    val st = t.ty.asInstanceOf[AbstractSeqType]
    val et = st.elemTy
    val nt = InternalTypePool.irefOf(et)
    val ob = handle.vb.asInstanceOf[BoxIRef]
    val i = toInt(index, signExt = true).longValue
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.elemOffsetOf(st, i))
    newHandle(nt, nb)
  }

  def shiftIRef(handle: Handle, index: Handle): Handle = {
    val t = handle.ty.asInstanceOf[TypeIRef]
    val rt = t.ty
    val nt = InternalTypePool.irefOf(rt)
    val ob = handle.vb.asInstanceOf[BoxIRef]
    val i = toInt(index, signExt = true).longValue
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.shiftOffsetOf(rt, i))
    newHandle(nt, nb)
  }

  def getFixedPartIRef(handle: Handle): Handle = {
    val t = handle.ty.asInstanceOf[TypeIRef]
    val ht = t.ty.asInstanceOf[TypeHybrid]
    val ft = ht.fixedTy
    val nt = InternalTypePool.irefOf(ft)
    val ob = handle.vb.asInstanceOf[BoxIRef]
    val nb = ob
    newHandle(nt, nb)
  }

  def getVarPartIRef(handle: Handle): Handle = {
    val t = handle.ty.asInstanceOf[TypeIRef]
    val ht = t.ty.asInstanceOf[TypeHybrid]
    val ft = ht.fixedTy
    val vt = ht.varTy
    val nt = InternalTypePool.irefOf(vt)
    val ob = handle.vb.asInstanceOf[BoxIRef]
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.varPartOffsetOf(ht))
    newHandle(nt, nb)
  }
Kunshan Wang's avatar
Kunshan Wang committed
242

243
  def load(ord: MemoryOrder, loc: Handle): Handle = {
Kunshan Wang's avatar
Kunshan Wang committed
244
    val ty = loc.ty.asInstanceOf[TypeIRef].ty
245 246 247
    val uty = InternalTypePool.unmarkedOf(ty)
    val b = loc.vb.asInstanceOf[BoxIRef]
    val iRef = b.objRef + b.offset
248 249 250 251
    val nb = ValueBox.makeBoxForType(uty) 
    
    MemoryOperations.load(uty, iRef, nb, microVM)

252
    newHandle(uty, nb)
253 254 255
  }

  def store(ord: MemoryOrder, loc: Handle, newVal: Handle): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
256
    val ty = loc.ty.asInstanceOf[TypeIRef].ty
257 258 259
    val uty = InternalTypePool.unmarkedOf(ty)
    val lb = loc.vb.asInstanceOf[BoxIRef]
    val iRef = lb.objRef + lb.offset
260 261 262 263
    val nvb = newVal.vb    
    val nb = ValueBox.makeBoxForType(uty)

    MemoryOperations.store(uty, iRef, nvb, nb, microVM)
264 265 266
  }

  def cmpXchg(ordSucc: MemoryOrder, ordFail: MemoryOrder, weak: Boolean, loc: Handle, expected: Handle, desired: Handle): (Boolean, Handle) = {
Kunshan Wang's avatar
Kunshan Wang committed
267
    val ty = loc.ty.asInstanceOf[TypeIRef].ty
268 269 270 271 272
    val uty = InternalTypePool.unmarkedOf(ty)
    val lb = loc.vb.asInstanceOf[BoxIRef]
    val iRef = lb.objRef + lb.offset
    val eb = expected.vb
    val db = desired.vb
273 274 275
    val br = ValueBox.makeBoxForType(uty)
    val succ = MemoryOperations.cmpXchg(uty, iRef, eb, db, br, microVM)
    (succ, newHandle(uty, br))
276 277 278
  }

  def atomicRMW(ord: MemoryOrder, op: AtomicRMWOptr, loc: Handle, opnd: Handle): Handle = {
Kunshan Wang's avatar
Kunshan Wang committed
279
    val ty = loc.ty.asInstanceOf[TypeIRef].ty
280 281 282 283
    val uty = InternalTypePool.unmarkedOf(ty)
    val lb = loc.vb.asInstanceOf[BoxIRef]
    val iRef = lb.objRef + lb.offset
    val ob = opnd.vb
284 285 286
    val br = ValueBox.makeBoxForType(uty)
    MemoryOperations.atomicRMW(uty, op, iRef, ob, br, microVM)
    newHandle(uty, br)
287
  }
Kunshan Wang's avatar
Kunshan Wang committed
288

289 290 291 292
  def fence(ord: MemoryOrder): Unit = {
  }

  def newStack(func: Handle, args: Seq[Handle]): Handle = {
Kunshan Wang's avatar
Kunshan Wang committed
293 294
    val funcVal = func.vb.asInstanceOf[BoxFunc].func.getOrElse {
      throw new UvmRuntimeException("Stack-bottom function must not be NULL")
Kunshan Wang's avatar
Kunshan Wang committed
295
    }
296 297 298 299
    
    val funcVer = funcVal.versions.headOption.getOrElse {
      throw new UvmRuntimeException("Stack-bottom function %s is not defined.".format(funcVal.repr))
    }
Kunshan Wang's avatar
Kunshan Wang committed
300 301 302

    val argBoxes = args.map(_.vb)

303
    val sta = microVM.threadStackManager.newStack(funcVer, argBoxes, mutator)
Kunshan Wang's avatar
Kunshan Wang committed
304 305 306

    val nb = BoxStack(Some(sta))
    newHandle(InternalTypes.STACK, nb)
307 308
  }

309 310
  private def getStackNotNull(stack: Handle): InterpreterStack = {
    stack.vb.asInstanceOf[BoxStack].stack match {
Kunshan Wang's avatar
Kunshan Wang committed
311
      case None    => throw new UvmRuntimeException("Stack argument cannot be a NULL micro VM stack value.")
312 313 314 315
      case Some(v) => v
    }
  }

316
  def newThread(stack: Handle): Handle = {
317 318 319 320 321
    val sv = getStackNotNull(stack)
    val thr = microVM.threadStackManager.newThread(sv)

    val nb = BoxThread(Some(thr))
    newHandle(InternalTypes.THREAD, nb)
322
  }
Kunshan Wang's avatar
Kunshan Wang committed
323 324

  def killStack(stack: Handle): Unit = {
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    val sv = getStackNotNull(stack)

    sv.state = StackState.Dead
  }

  private def nthFrame(stack: InterpreterStack, n: Int): InterpreterFrame = {
    val it = stack.frames
    for (i <- (0 until n)) {
      if (it.hasNext) {
        it.next()
      } else {
        throw new UvmRuntimeException("The stack only has %d frames, but the %d-th frame is requested.".format(i, n))
      }
    }
    if (it.hasNext) {
      it.next()
    } else {
      throw new UvmRuntimeException("The stack only has %d frames, but the %d-th frame is requested.".format(n, n))
    }

Kunshan Wang's avatar
Kunshan Wang committed
345 346 347
  }

  def currentFuncVer(stack: Handle, frame: Int): Int = {
348 349 350
    val sv = getStackNotNull(stack)
    val fr = nthFrame(sv, frame)
    fr.funcVer.id
Kunshan Wang's avatar
Kunshan Wang committed
351 352 353
  }

  def currentInstruction(stack: Handle, frame: Int): Int = {
354 355 356
    val sv = getStackNotNull(stack)
    val fr = nthFrame(sv, frame)
    fr.curInst.id
Kunshan Wang's avatar
Kunshan Wang committed
357 358 359
  }

  def dumpKeepalives(stack: Handle, frame: Int): Seq[Handle] = {
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    val sv = getStackNotNull(stack)
    val fr = nthFrame(sv, frame)
    val i = fr.curInst
    i match {
      case hkac: HasKeepAliveClause => {
        val kas = hkac.keepAlives
        for (ka <- kas) yield {
          val box = fr.boxes(ka)
          val ty = TypeInferer.inferType(ka)
          newHandle(ty, box)
        }
      }
      case _ => {
        throw new UvmRuntimeException("The current instruction %s does not have keep-alive clause.".format(i.repr))
      }
    }
Kunshan Wang's avatar
Kunshan Wang committed
376 377 378
  }

  def popFrame(stack: Handle): Unit = {
379 380 381 382 383 384
    val st = getStackNotNull(stack)
    val top = st.top
    top.prev match {
      case None => throw new UvmRuntimeException("Attempting to pop the last frame of a stack.")
      case Some(prev) => st.top = prev
    }
Kunshan Wang's avatar
Kunshan Wang committed
385 386
  }

Kunshan Wang's avatar
Kunshan Wang committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
  def pushFrame(stack: Handle, func: Handle, argList: Seq[Handle]): Unit = {    
    val sta = stack.vb.asInstanceOf[BoxStack].stack.getOrElse {
      throw new UvmRuntimeException("Stack must not be NULL")
    }

    val funcVal = func.vb.asInstanceOf[BoxFunc].func.getOrElse {
      throw new UvmRuntimeException("Stack-bottom function must not be NULL")
    }
    
    val funcVer = funcVal.versions.headOption.getOrElse {
      throw new UvmRuntimeException("Stack-bottom function %s is not defined.".format(funcVal.repr))
    }

    val argBoxes = argList.map(_.vb)
    
    sta.pushFrame(funcVer, argBoxes)
  }
Kunshan Wang's avatar
Kunshan Wang committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439

  def tr64IsFp(handle: Handle): Boolean = {
    OpHelper.tr64IsFp(handle.vb.asInstanceOf[BoxTagRef64].raw)
  }

  def tr64IsInt(handle: Handle): Boolean = {
    OpHelper.tr64IsInt(handle.vb.asInstanceOf[BoxTagRef64].raw)
  }

  def tr64IsRef(handle: Handle): Boolean = {
    OpHelper.tr64IsRef(handle.vb.asInstanceOf[BoxTagRef64].raw)
  }

  def tr64ToFp(handle: Handle): Handle = {
    val raw = handle.vb.asInstanceOf[BoxTagRef64].raw
    val box = new BoxDouble(OpHelper.tr64ToFp(raw))
    newHandle(InternalTypes.DOUBLE, box)
  }

  def tr64ToInt(handle: Handle): Handle = {
    val raw = handle.vb.asInstanceOf[BoxTagRef64].raw
    val box = new BoxInt(OpHelper.tr64ToInt(raw))
    newHandle(InternalTypes.I52, box)
  }

  def tr64ToRef(handle: Handle): Handle = {
    val raw = handle.vb.asInstanceOf[BoxTagRef64].raw
    val box = new BoxRef(OpHelper.tr64ToRef(raw))
    newHandle(InternalTypes.REF_VOID, box)
  }

  def tr64ToTag(handle: Handle): Handle = {
    val raw = handle.vb.asInstanceOf[BoxTagRef64].raw
    val box = new BoxInt(OpHelper.tr64ToTag(raw))
    newHandle(InternalTypes.I6, box)
  }
440

Kunshan Wang's avatar
Kunshan Wang committed
441 442 443 444 445
  def tr64FromFp(handle: Handle): Handle = {
    val fp = handle.vb.asInstanceOf[BoxDouble].value
    val box = new BoxTagRef64(OpHelper.fpToTr64(fp))
    newHandle(InternalTypes.TAGREF64, box)
  }
446

Kunshan Wang's avatar
Kunshan Wang committed
447 448 449 450 451 452 453 454 455 456 457 458
  def tr64FromInt(handle: Handle): Handle = {
    val i = handle.vb.asInstanceOf[BoxInt].value
    val box = new BoxTagRef64(OpHelper.intToTr64(i.longValue))
    newHandle(InternalTypes.TAGREF64, box)
  }

  def tr64FromRef(ref: Handle, tag: Handle): Handle = {
    val refv = ref.vb.asInstanceOf[BoxRef].objRef
    val tagv = tag.vb.asInstanceOf[BoxInt].value
    val box = new BoxTagRef64(OpHelper.refToTr64(refv, tagv.longValue))
    newHandle(InternalTypes.TAGREF64, box)
  }
459 460 461 462 463 464 465 466
  
  def enableWatchPoint(wpID: Int): Unit = {
    microVM.trapManager.enableWatchPoint(wpID)
  }

  def disableWatchPoint(wpID: Int): Unit = {
    microVM.trapManager.disableWatchPoint(wpID)
  }
Kunshan Wang's avatar
Kunshan Wang committed
467

Kunshan Wang's avatar
Kunshan Wang committed
468
  // Internal methods for the micro VM
469 470 471 472 473 474

  def putThread(thr: Option[InterpreterThread]): Handle = {
    val t = InternalTypes.THREAD
    val box = BoxThread(thr)
    newHandle(t, box)
  }
475

476 477 478 479 480 481
  def putStack(sta: Option[InterpreterStack]): Handle = {
    val t = InternalTypes.STACK
    val box = BoxStack(sta)
    newHandle(t, box)
  }

482
}