MuCtx.scala 25.7 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5 6 7 8 9 10 11 12 13
package uvm.refimpl

import java.io.Reader
import java.nio.charset.Charset

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashSet

import org.slf4j.LoggerFactory

import com.typesafe.scalalogging.Logger

import uvm._
14
import uvm.ir.irbuilder.IRBuilder
Kunshan Wang's avatar
Kunshan Wang committed
15 16 17 18 19
import uvm.refimpl.itpr._
import uvm.refimpl.mem._
import uvm.refimpl.mem.TypeSizes._
import uvm.ssavariables._
import uvm.ssavariables.AtomicRMWOptr._
20
import uvm.ssavariables.HasKeepaliveClause
Kunshan Wang's avatar
Kunshan Wang committed
21 22
import uvm.ssavariables.MemoryOrder._
import uvm.types._
Kunshan Wang's avatar
Kunshan Wang committed
23 24
import uvm.refimpl.bootimg.FieldAndSymbol
import uvm.refimpl.bootimg.PrimordialInfo
Kunshan Wang's avatar
Kunshan Wang committed
25 26 27 28 29 30 31 32 33 34 35

object MuCtx {
  val logger = Logger(LoggerFactory.getLogger(getClass.getName))

  val US_ASCII = Charset.forName("US-ASCII")
}

/**
 * A client context. The main part of the API. It keeps thread-local states, including a set of handles. It provides
 * operations on the Mu VM.
 */
36
class MuCtx(val ctxID: MuInternalID, _mutator: Mutator)(
37
  implicit protected val microVM: MicroVM, memorySupport: MemorySupport)
Kunshan Wang's avatar
Kunshan Wang committed
38
    extends ObjectPinner with AutoCloseable {
39 40 41
  
  private val predefinedEntities = microVM.staticAnalyzer.predefinedEntities
  private val internalEntityPool = microVM.staticAnalyzer.internalEntityPool
Kunshan Wang's avatar
Kunshan Wang committed
42 43 44 45 46 47 48 49

  implicit def mutator = _mutator

  val handles = new HashSet[MuValue]()

  val pinSet = new ArrayBuffer[Word]

  /** Given a name, get the ID of an identified entity. */
Kunshan Wang's avatar
Kunshan Wang committed
50
  def idOf(name: MuName): MuID = microVM.idOf(name)
Kunshan Wang's avatar
Kunshan Wang committed
51 52

  /** Given an ID, get the name of an identified entity. */
Kunshan Wang's avatar
Kunshan Wang committed
53
  def nameOf(id: MuID): MuName = microVM.nameOf(id)
Kunshan Wang's avatar
Kunshan Wang committed
54 55 56 57 58 59 60

  /** Close the context. */
  def closeContext(): Unit = {
    handles.clear()
    mutator.close()
    microVM.contexts.remove(this)
  }
61

62 63
  /** Synonym of closeContext, for AutoCloseable. */
  override def close(): Unit = closeContext()
Kunshan Wang's avatar
Kunshan Wang committed
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

  /** Load a Mu IR bundle */
  def loadBundle(r: Reader): Unit = {
    MetaOperations.loadBundle(r)
  }

  /** Load a Mu IR bundle */
  def loadBundle(s: String): Unit = {
    MetaOperations.loadBundle(s)
  }

  /** Load a HAIL script */
  def loadHail(r: Reader): Unit = {
    MetaOperations.loadHail(r)
  }

  /** Load a HAIL script */
  def loadHail(s: String): Unit = {
    MetaOperations.loadHail(s)
  }

  protected def addHandle[T <: MuValue](h: T): T = {
    handles.add(h)
    h
  }

  /** Convert any int (BigInt) to a handle. */
  def handleFromInt(num: BigInt, len: Int): MuIntValue = {
92
    val t = internalEntityPool.intOf(len)
Kunshan Wang's avatar
Kunshan Wang committed
93 94 95 96 97 98
    val v = OpHelper.unprepare(num, len)
    addHandle(MuIntValue(t, BoxInt(v)))
  }

  /** Convert float to a handle. */
  def handleFromFloat(num: Float): MuFloatValue = {
99
    val t = predefinedEntities.FLOAT
Kunshan Wang's avatar
Kunshan Wang committed
100 101 102 103 104
    addHandle(MuFloatValue(t, BoxFloat(num)))
  }

  /** Convert double to a handle. */
  def handleFromDouble(num: Double): MuDoubleValue = {
105
    val t = predefinedEntities.DOUBLE
Kunshan Wang's avatar
Kunshan Wang committed
106 107 108 109
    addHandle(MuDoubleValue(t, BoxDouble(num)))
  }

  /** Convert pointer (Long) to a handle. */
Kunshan Wang's avatar
Kunshan Wang committed
110
  def handleFromPtr(muType: MuID, v: Word): MuUPtrValue = {
Kunshan Wang's avatar
Kunshan Wang committed
111 112 113 114 115
    val t = microVM.globalBundle.typeNs(muType).asInstanceOf[TypeUPtr]
    addHandle(MuUPtrValue(t, BoxPointer(v)))
  }

  /** Convert function pointer (Long) to a handle. */
Kunshan Wang's avatar
Kunshan Wang committed
116
  def handleFromFP(muType: MuID, v: Word): MuUFPValue = {
Kunshan Wang's avatar
Kunshan Wang committed
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
    val t = microVM.globalBundle.typeNs(muType).asInstanceOf[TypeUFuncPtr]
    addHandle(MuUFPValue(t, BoxPointer(v)))
  }

  /** Convert handle to an integer (BigInt). */
  def handleToInt(opnd: MuIntValue, signExt: Boolean): BigInt = {
    val t = opnd.ty
    val ib = opnd.vb
    if (signExt) OpHelper.prepareSigned(ib.value, t.length) else OpHelper.prepareUnsigned(ib.value, t.length)
  }

  /** Convert handle to integer (BigInt), assume signed. */
  def handleToSInt(opnd: MuIntValue) = handleToInt(opnd, true)

  /** Convert handle to integer (BigInt), assume unsigned. */
  def handleToUInt(opnd: MuIntValue) = handleToInt(opnd, false)

  /** Convert handle to float. */
  def handleToFloat(opnd: MuFloatValue): Float = {
    opnd.vb.value
  }

  /** Convert handle to double. */
  def handleToDouble(opnd: MuDoubleValue): Double = {
    opnd.vb.value
  }

  /** Convert handle to pointer (Long). */
  def handleToPtr(opnd: MuUPtrValue): Word = {
    opnd.vb.addr
  }

  /** Convert handle to function pointer (Long). */
  def handleToFP(opnd: MuUFPValue): Word = {
    opnd.vb.addr
  }

  /** Make a handle for a constant. */
Kunshan Wang's avatar
Kunshan Wang committed
155
  def handleFromConst(id: MuID): MuValue = {
Kunshan Wang's avatar
Kunshan Wang committed
156 157 158 159 160 161 162
    val c = microVM.globalBundle.constantNs(id)
    val t = c.constTy
    val box = microVM.constantPool.getGlobalVarBox(c)
    addHandle(MuValue(t, box))
  }

  /** Make a handle for a global cell (its iref). */
Kunshan Wang's avatar
Kunshan Wang committed
163
  def handleFromGlobal(id: MuID): MuIRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
164
    val g = microVM.globalBundle.globalCellNs(id)
165
    val t = internalEntityPool.irefOf(g.cellTy)
Kunshan Wang's avatar
Kunshan Wang committed
166 167 168 169 170 171
    val a = microVM.memoryManager.globalMemory.addrForGlobalCell(g)
    val box = BoxIRef(0L, a)
    addHandle(MuIRefValue(t, box))
  }

  /** Make a handle for a function (funcref). */
Kunshan Wang's avatar
Kunshan Wang committed
172
  def handleFromFunc(id: MuID): MuFuncRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
173
    val f = microVM.globalBundle.funcNs(id)
174
    val t = internalEntityPool.funcOf(f.sig)
Kunshan Wang's avatar
Kunshan Wang committed
175 176 177 178 179 180 181 182
    val box = BoxFunc(Some(f))
    addHandle(MuFuncRefValue(t, box))
  }

  /**
   * Make a handle for an exposed function. In this implementation, the type is ufuncptr, but other implementations
   * may be different.
   */
Kunshan Wang's avatar
Kunshan Wang committed
183
  def handleFromExpose(id: MuID): MuUFPValue = {
Kunshan Wang's avatar
Kunshan Wang committed
184
    val ef = microVM.globalBundle.expFuncNs(id)
185
    val t = internalEntityPool.funcPtrOf(ef.func.sig)
Kunshan Wang's avatar
Kunshan Wang committed
186 187 188 189 190 191 192 193 194 195 196
    val box = BoxPointer(microVM.nativeCallHelper.getStaticExpFuncAddr(ef))
    addHandle(MuUFPValue(t, box))
  }

  /** Delete a handle. */
  def deleteValue(opnd: MuValue): Unit = {
    handles.remove(opnd)
  }

  /** Compare general reference types for equality. */
  def refEq(lhs: MuGenRefValue, rhs: MuGenRefValue): Boolean = (lhs, rhs) match {
Kunshan Wang's avatar
Kunshan Wang committed
197 198 199
    case (l: MuRefValue, r: MuRefValue)                   => l.vb.objRef == r.vb.objRef
    case (l: MuIRefValue, r: MuIRefValue)                 => l.vb.oo == r.vb.oo
    case (l: MuOpaqueRefValue[_], r: MuOpaqueRefValue[_]) => l.vb.obj == r.vb.obj
Kunshan Wang's avatar
Kunshan Wang committed
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 242 243 244 245 246 247 248 249 250 251 252 253
    case (l, r) => {
      throw new IllegalArgumentException("Bad types for refEq: %s and %s".format(
        l.showTy, r.showTy))
    }
  }

  /** Compare general reference types for less-than. */
  def refUlt(lhs: MuIRefValue, rhs: MuIRefValue): Boolean = {
    if (lhs.vb.objRef != rhs.vb.objRef) {
      val (lb, lo) = lhs.vb.oo
      val (rb, ro) = rhs.vb.oo
      throw new UvmRefImplException(("Two operands refer to different objects. This is an undefined behaviour. " +
        "lhs: %d+%d (0x%x+0x%x); rhs: %d+%d (0x%x+0x%x)".format(lb, lo, lb, lo, rb, ro, rb, ro)))
    }
    lhs.vb.offset < rhs.vb.offset
  }

  /** Get the value of a field of a struct value. */
  def extractValue(str: MuStructValue, index: Int): MuValue = {
    val st = str.ty
    val sb = str.vb
    val ft = st.fieldTys(index)
    val fb = sb.values(index)
    addHandle(MuValue(ft, fb))
  }

  /** Copy a struct value, replacing one of its fields. */
  def insertValue(str: MuStructValue, index: Int, newval: MuValue): MuStructValue = {
    val st = str.ty
    val sb = str.vb
    val nsb = BoxSeq(for ((b, i) <- sb.values.zipWithIndex) yield if (i == index) newval.vb else b)
    addHandle(MuStructValue(st, nsb))
  }

  /** Get the value of an element of an array or value. */
  def extractElement[T <: MuSeqValue](seq: T, index: MuIntValue): MuValue = {
    val indexVal = handleToUInt(index).toInt

    val et = seq.ty.elemTy
    val eb = seq.vb.values(indexVal)
    addHandle(MuValue(et, eb))
  }

  /** Copy an array or vector value, replacing one of its elements. */
  def insertElement[T <: MuSeqValue](seq: T, index: MuIntValue, newval: MuValue): T = {
    val indexVal = handleToUInt(index).toInt

    val st = seq.ty
    val sb = seq.vb
    val nsb = BoxSeq(for ((b, i) <- sb.values.zipWithIndex) yield if (i == indexVal) newval.vb else b)
    addHandle(MuValue(st, nsb).asInstanceOf[T])
  }

  /** Allocate a fixed object in the heap. */
Kunshan Wang's avatar
Kunshan Wang committed
254
  def newFixed(muType: MuID): MuRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
255 256 257
    val t = microVM.globalBundle.typeNs(muType)
    val objRef = mutator.newScalar(t)
    val b = BoxRef(objRef)
258
    val rt = internalEntityPool.refOf(t)
Kunshan Wang's avatar
Kunshan Wang committed
259 260 261 262
    addHandle(MuRefValue(rt, b))
  }

  /** Allocate a hybrid object in the heap. */
Kunshan Wang's avatar
Kunshan Wang committed
263
  def newHybrid(tid: MuID, length: MuIntValue): MuRefValue = {
Kunshan Wang's avatar
Kunshan Wang committed
264 265 266 267
    val t = microVM.globalBundle.typeNs(tid).asInstanceOf[TypeHybrid]
    val len = handleToUInt(length).longValue
    val objRef = mutator.newHybrid(t, len)
    val b = BoxRef(objRef)
268
    val rt = internalEntityPool.refOf(t)
Kunshan Wang's avatar
Kunshan Wang committed
269 270 271 272
    addHandle(MuRefValue(rt, b))
  }

  /** Cast between two refs, two irefs or two funcrefs */
Kunshan Wang's avatar
Kunshan Wang committed
273
  def refcast[T <: MuGenRefValue](opnd: T, newType: MuID): T = {
Kunshan Wang's avatar
Kunshan Wang committed
274 275 276
    val nt = microVM.globalBundle.typeNs(newType)

    val nh = (opnd, nt) match {
Kunshan Wang's avatar
Kunshan Wang committed
277 278
      case (MuRefValue(ty, vb), ty2 @ TypeRef(_))   => MuRefValue(ty2, vb)
      case (MuIRefValue(ty, vb), ty2 @ TypeIRef(_)) => MuIRefValue(ty2, vb)
279 280
      case (MuOpaqueRefValue(ty, vb), ty2 @ TypeFuncRef(_)) => {
        require(ty.isInstanceOf[TypeFuncRef] && vb.isInstanceOf[BoxOpaque[_]],
Kunshan Wang's avatar
Kunshan Wang committed
281
          "Attempt to cast %s to funcref. funcref value required".format(opnd.showTy))
282 283
        MuFuncRefValue(ty2, vb.asInstanceOf[BoxFunc])
      }
Kunshan Wang's avatar
Kunshan Wang committed
284 285 286 287 288 289 290 291 292 293 294
      case _ => {
        throw new IllegalArgumentException("Bad types for refcast: opnd:%s, newType:%s".format(
          opnd.showTy, nt.repr))
      }
    }

    addHandle(nh.asInstanceOf[T])
  }

  /** Convert ref to iref */
  def getIRef(opnd: MuRefValue): MuIRefValue = {
295
    val nt = internalEntityPool.irefOf(opnd.ty.ty)
Kunshan Wang's avatar
Kunshan Wang committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309
    val nb = BoxIRef(opnd.vb.objRef, 0L)
    addHandle(MuIRefValue(nt, nb))
  }

  /** Get the iref to a field of a struct or hybrid location */
  def getFieldIRef(opnd: MuIRefValue, field: Int): MuIRefValue = {
    val st = try {
      opnd.ty.ty.asInstanceOf[AbstractStructType]
    } catch {
      case e: ClassCastException => throw new IllegalArgumentException(
        "opnd must refer to a struct or hybrid location. Actual referenct type: %s".format(opnd.ty.ty.repr), e)
    }

    val ft = st.fieldTys(field)
310
    val nt = internalEntityPool.irefOf(ft)
Kunshan Wang's avatar
Kunshan Wang committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    val ob = opnd.vb
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.fieldOffsetOf(st, field))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Get the iref to an element of an array or vector location. */
  def getElemIRef(opnd: MuIRefValue, index: MuIntValue): MuIRefValue = {
    val st = try {
      opnd.ty.ty.asInstanceOf[AbstractSeqType]
    } catch {
      case e: ClassCastException => throw new IllegalArgumentException(
        "opnd must refer to an array or vector location. Actual referenct type: %s".format(opnd.ty.ty.repr), e)
    }
    val i = handleToUInt(index).longValue
    val et = st.elemTy
326
    val nt = internalEntityPool.irefOf(et)
Kunshan Wang's avatar
Kunshan Wang committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    val ob = opnd.vb
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.elemOffsetOf(st, i))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Shift an iref to an array element by offset elements. */
  def shiftIRef(opnd: MuIRefValue, offset: MuIntValue): MuIRefValue = {
    val ot = opnd.ty
    val ob = opnd.vb
    val rt = ot.ty
    val nt = ot
    val off = handleToSInt(offset).longValue
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.shiftOffsetOf(rt, off))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Get the iref to the 0-th element of the variable part of a hybrid location. */
  def getVarPartIRef(opnd: MuIRefValue): MuIRefValue = {
    val ht = try {
      opnd.ty.ty.asInstanceOf[TypeHybrid]
    } catch {
      case e: ClassCastException => throw new IllegalArgumentException(
        "opnd must refer to a hybrid location. Actual referenct type: %s".format(opnd.ty.ty.repr), e)
    }
    val vt = ht.varTy
352
    val nt = internalEntityPool.irefOf(vt)
Kunshan Wang's avatar
Kunshan Wang committed
353 354 355 356 357 358 359 360 361 362 363
    val ob = opnd.vb
    val nb = BoxIRef(ob.objRef, ob.offset + TypeSizes.varPartOffsetOf(ht))
    addHandle(MuIRefValue(nt, nb))
  }

  /** Load from a location. */
  def load(ord: MemoryOrder, loc: MuIRefValue): MuValue = {
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }

364
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
365 366 367 368 369 370 371 372 373 374 375 376 377
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val nb = ValueBox.makeBoxForType(uty)

    MemoryOperations.load(ptr, uty, addr, nb)

    addHandle(MuValue(uty, nb))
  }

  /** Store to a location. */
  def store(ord: MemoryOrder, loc: MuIRefValue, newVal: MuValue): Unit = {
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }
378
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
379 380 381 382 383 384 385 386 387 388 389 390
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val nvb = newVal.vb

    MemoryOperations.store(ptr, uty, addr, nvb)
  }

  /** Perform compare exchange on a location. */
  def cmpXchg(ordSucc: MemoryOrder, ordFail: MemoryOrder, weak: Boolean,
    loc: MuIRefValue, expected: MuValue, desired: MuValue): (MuValue, Boolean) = {
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }
391
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
392 393 394 395 396 397 398 399 400 401 402 403 404
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val eb = expected.vb
    val db = desired.vb
    val br = ValueBox.makeBoxForType(uty)
    val succ = MemoryOperations.cmpXchg(ptr, uty, addr, eb, db, br)
    (addHandle(MuValue(uty, br)), succ)
  }

  /** Perform an atomic read-modify-write operation on a location. */
  def atomicRMW(ord: MemoryOrder, op: AtomicRMWOptr, loc: MuIRefValue, opnd: MuValue): MuValue = {
    val (ptr, ty) = loc.ty match {
      case TypeIRef(t) => (false, t)
    }
405
    val uty = internalEntityPool.unmarkedOf(ty)
Kunshan Wang's avatar
Kunshan Wang committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419
    val addr = MemoryOperations.addressOf(ptr, loc.vb)
    val ob = opnd.vb
    val br = ValueBox.makeBoxForType(uty)
    MemoryOperations.atomicRMW(ptr, uty, op, addr, ob, br)
    addHandle(MuValue(uty, br))
  }

  /** Memory fence */
  def fence(ord: MemoryOrder): Unit = {
    // No-op
  }

  /** Create a Mu stack with fa stack-bottom function */
  def newStack(func: MuFuncRefValue): MuStackRefValue = {
420
    val funcVal = func.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
421 422 423 424 425 426
      throw new UvmRuntimeException("Stack-bottom function must not be NULL")
    }

    val sta = microVM.threadStackManager.newStack(funcVal, mutator)

    val nb = BoxStack(Some(sta))
427
    addHandle(MuStackRefValue(predefinedEntities.STACKREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
428 429 430
  }

  private def getStackNotNull(stack: MuStackRefValue): InterpreterStack = {
431
    stack.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
432 433 434 435 436
      throw new UvmRuntimeException("Stack argument cannot be a NULL stackref value.")
    }
  }

  private def getThreadNotNull(thread: MuThreadRefValue): InterpreterThread = {
437
    thread.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
      throw new UvmRuntimeException("Thread argument cannot be a NULL threadref value.")
    }
  }

  /** Create a Mu thread and bind it to a Mu stack. */
  def newThread(stack: MuStackRefValue, threadLocal: Option[MuRefValue], htr: HowToResume): MuThreadRefValue = {
    val sv = getStackNotNull(stack)
    val itprHtr = htr match {
      case HowToResume.PassValues(values) => itpr.HowToResume.PassValues(values.map(_.vb))
      case HowToResume.ThrowExc(exc)      => itpr.HowToResume.ThrowExc(exc.vb.objRef)
    }

    val threadLocalAddr = threadLocal.map(tl => tl.vb.objRef).getOrElse(0L)
    val thr = microVM.threadStackManager.newThread(sv, threadLocalAddr, itprHtr)

    val nb = BoxThread(Some(thr))
454
    addHandle(MuThreadRefValue(predefinedEntities.THREADREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
  }

  /** Kill a Mu stack. */
  def killStack(stack: MuStackRefValue): Unit = {
    val sv = getStackNotNull(stack)

    sv.kill()
  }

  /** Set the thread-local object reference */
  def setThreadlocal(thread: MuThreadRefValue, threadLocal: MuRefValue): Unit = {
    val th = getThreadNotNull(thread)
    val threadLocalAddr = threadLocal.vb.objRef

    th.threadLocal.objRef = threadLocalAddr
  }

  /** Get the thread-local object reference */
  def getThreadlocal(thread: MuThreadRefValue): MuRefValue = {
    val th = getThreadNotNull(thread)
    val threadLocalAddr = th.threadLocal.objRef

    val nb = BoxRef(threadLocalAddr)
478
    addHandle(MuRefValue(predefinedEntities.REF_VOID, nb))
Kunshan Wang's avatar
Kunshan Wang committed
479 480 481
  }

  private def getCursorNotNull(cursor: MuFCRefValue): FrameCursor = {
482
    cursor.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
483 484 485 486 487 488 489 490 491
      throw new UvmRuntimeException("Frame cursor argument cannot be a NULL framecursorref value.")
    }
  }

  /** Create a frame cursor. */
  def newCursor(stack: MuStackRefValue): MuFCRefValue = {
    val s = getStackNotNull(stack)
    val c = microVM.threadStackManager.newFrameCursor(s)
    val nb = BoxFrameCursor(Some(c))
492
    addHandle(MuFCRefValue(predefinedEntities.FRAMECURSORREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
493 494 495 496 497 498 499 500 501 502 503 504
  }

  /** Move cursor to the frame below the current frame. */
  def nextFrame(cursor: MuFCRefValue): Unit = {
    getCursorNotNull(cursor).nextFrame()
  }

  /** Copy a frame cursor. */
  def copyCursor(cursor: MuFCRefValue): MuFCRefValue = {
    val c = getCursorNotNull(cursor)
    val nc = microVM.threadStackManager.copyCursor(c)
    val nb = BoxFrameCursor(Some(nc))
505
    addHandle(MuFCRefValue(predefinedEntities.FRAMECURSORREF, nb))
Kunshan Wang's avatar
Kunshan Wang committed
506 507 508 509 510 511 512 513 514
  }

  /** Close a frame cursor. */
  def closeCursor(cursor: MuFCRefValue): Unit = {
    val c = getCursorNotNull(cursor)
    microVM.threadStackManager.closeCursor(c)
  }

  /** Get the ID of the current function of a frame. Return 0 for native frames. */
Kunshan Wang's avatar
Kunshan Wang committed
515
  def curFunc(cursor: MuFCRefValue): MuID = {
Kunshan Wang's avatar
Kunshan Wang committed
516 517 518 519 520 521 522 523
    val c = getCursorNotNull(cursor)
    c.frame.curFuncID
  }

  /**
   * Get the ID of the current function version of a frame. Return 0 for native frames
   *  or Mu frames of undefined functions
   */
Kunshan Wang's avatar
Kunshan Wang committed
524
  def curFuncVer(cursor: MuFCRefValue): MuID = {
Kunshan Wang's avatar
Kunshan Wang committed
525 526 527 528 529 530 531 532
    val c = getCursorNotNull(cursor)
    c.frame.curFuncVerID
  }

  /**
   * Get the ID of the current instruction of a frame. Return 0 for native frames, Mu frames for undefined
   *  functions, or if the frame is just created by newStack or pushFrame.
   */
Kunshan Wang's avatar
Kunshan Wang committed
533
  def curInst(cursor: MuFCRefValue): MuID = {
Kunshan Wang's avatar
Kunshan Wang committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    val c = getCursorNotNull(cursor)
    c.frame.curInstID
  }

  /** Dump keep-alive variables of the current instruction. */
  def dumpKeepalives(cursor: MuFCRefValue): Seq[MuValue] = {
    val c = getCursorNotNull(cursor)
    val fr = c.frame
    fr match {
      case f: NativeFrame => {
        throw new UvmRefImplException("Attempt to dump keepalives from a native frame. Funciton 0x%x".format(f.func))
      }
      case f: UndefinedMuFrame => {
        for ((ty, box) <- f.func.sig.paramTys zip f.boxes) yield {
          addHandle(MuValue(ty, box))
        }
      }
      case f: DefinedMuFrame => {
        val i = f.curInst
        i match {
554 555
          case hkac: HasKeepaliveClause => {
            val kas = hkac.keepalives
Kunshan Wang's avatar
Kunshan Wang committed
556 557
            for (ka <- kas) yield {
              val box = f.boxes(ka)
558
              val ty = ka.inferredType
Kunshan Wang's avatar
Kunshan Wang committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
              addHandle(MuValue(ty, box))
            }
          }
          case _ => {
            throw new UvmRuntimeException("The current instruction %s does not have keep-alive clause.".format(i.repr))
          }
        }
      }
    }
  }

  /** Pop the top frame of a Mu stack. */
  def popFramesTo(cursor: MuFCRefValue): Unit = {
    val c = getCursorNotNull(cursor)

    c.stack.popFramesTo(c)
  }

  /** Create a new frame for a Mu function and push it to the top of a stack. */
578 579
  def pushFrame(cursor: MuFCRefValue, func: MuFuncRefValue): Unit = {
    val c = getCursorNotNull(cursor)
Kunshan Wang's avatar
Kunshan Wang committed
580

581
    val funcVal = func.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
582 583 584
      throw new UvmRuntimeException("Stack-bottom function must not be NULL")
    }

585
    val st = c.stack
Kunshan Wang's avatar
Kunshan Wang committed
586 587 588 589
    st.pushFrame(funcVal)
  }

  /** Test if a tagref64 holds a double. */
590 591
  def tr64IsFP(value: MuTagRef64Value): Boolean = {
    OpHelper.tr64IsFP(value.vb.raw)
Kunshan Wang's avatar
Kunshan Wang committed
592 593 594 595 596 597 598 599 600 601 602 603 604
  }

  /** Test if a tagref64 holds an int. */
  def tr64IsInt(value: MuTagRef64Value): Boolean = {
    OpHelper.tr64IsInt(value.vb.raw)
  }

  /** Test if a tagref64 holds a ref. */
  def tr64IsRef(value: MuTagRef64Value): Boolean = {
    OpHelper.tr64IsRef(value.vb.raw)
  }

  /** Extract the double held by a tagref64. */
605
  def tr64ToFP(value: MuTagRef64Value): MuDoubleValue = {
Kunshan Wang's avatar
Kunshan Wang committed
606
    val raw = value.vb.raw
607
    val box = new BoxDouble(OpHelper.tr64ToFP(raw))
608
    addHandle(MuDoubleValue(predefinedEntities.DOUBLE, box))
Kunshan Wang's avatar
Kunshan Wang committed
609 610 611 612 613 614
  }

  /** Extract the int held by a tagref64. */
  def tr64ToInt(value: MuTagRef64Value): MuIntValue = {
    val raw = value.vb.raw
    val box = new BoxInt(OpHelper.tr64ToInt(raw))
615
    addHandle(MuIntValue(predefinedEntities.I52, box))
Kunshan Wang's avatar
Kunshan Wang committed
616 617 618 619 620 621
  }

  /** Extract the object ref held by a tagref64. */
  def tr64ToRef(value: MuTagRef64Value): MuRefValue = {
    val raw = value.vb.raw
    val box = new BoxRef(OpHelper.tr64ToRef(raw))
622
    addHandle(MuRefValue(predefinedEntities.REF_VOID, box))
Kunshan Wang's avatar
Kunshan Wang committed
623 624 625 626 627 628
  }

  /** Extract the tag held by a tagref64. */
  def tr64ToTag(value: MuTagRef64Value): MuIntValue = {
    val raw = value.vb.raw
    val box = new BoxInt(OpHelper.tr64ToTag(raw))
629
    addHandle(MuIntValue(predefinedEntities.I6, box))
Kunshan Wang's avatar
Kunshan Wang committed
630 631 632
  }

  /** Convert a double to a tagref64. */
633
  def tr64FromFP(value: MuDoubleValue): MuTagRef64Value = {
Kunshan Wang's avatar
Kunshan Wang committed
634 635
    val fp = value.vb.value
    val box = new BoxTagRef64(OpHelper.fpToTr64(fp))
636
    addHandle(MuTagRef64Value(predefinedEntities.TAGREF64, box))
Kunshan Wang's avatar
Kunshan Wang committed
637 638 639 640 641 642 643
  }

  /** Convert an int to a tagref64. */
  def tr64FromInt(value: MuIntValue): MuTagRef64Value = {
    if (value.ty.length != 52) throw new IllegalArgumentException("Expect int<52>, found %s".format(value.ty.repr))
    val i = value.vb.value
    val box = new BoxTagRef64(OpHelper.intToTr64(i.longValue))
644
    addHandle(MuTagRef64Value(predefinedEntities.TAGREF64, box))
Kunshan Wang's avatar
Kunshan Wang committed
645 646 647 648 649 650 651 652
  }

  /** Convert an object ref and a tag to a tagref64. */
  def tr64FromRef(ref: MuRefValue, tag: MuIntValue): MuTagRef64Value = {
    if (tag.ty.length != 6) throw new IllegalArgumentException("Expect int<6> tag, found %s".format(tag.ty.repr))
    val refv = ref.vb.objRef
    val tagv = tag.vb.value
    val box = new BoxTagRef64(OpHelper.refToTr64(refv, tagv.longValue))
653
    addHandle(MuTagRef64Value(predefinedEntities.TAGREF64, box))
Kunshan Wang's avatar
Kunshan Wang committed
654 655
  }

Kunshan Wang's avatar
Kunshan Wang committed
656
  def enableWatchPoint(wpID: MuID): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
657 658 659
    microVM.trapManager.enableWatchPoint(wpID)
  }

Kunshan Wang's avatar
Kunshan Wang committed
660
  def disableWatchPoint(wpID: MuID): Unit = {
Kunshan Wang's avatar
Kunshan Wang committed
661 662 663 664 665 666 667 668 669 670 671 672
    microVM.trapManager.disableWatchPoint(wpID)
  }

  def pin(loc: MuValue): MuUPtrValue = {
    val (objTy, (objRef, offset)) = loc match {
      case MuRefValue(t, vb)  => (t, (vb.objRef, 0L))
      case MuIRefValue(t, vb) => (t, vb.oo)
      case _ => {
        throw new IllegalArgumentException("loc must be ref or iref. Found %s".format(loc.ty))
      }
    }
    pin(objRef)
673
    val ptrTy = internalEntityPool.ptrOf(objTy)
Kunshan Wang's avatar
Kunshan Wang committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687
    val box = new BoxPointer(objRef + offset)
    addHandle(MuUPtrValue(ptrTy, box))
  }

  def unpin(loc: MuValue): Unit = {
    val (objTy, objRef) = loc match {
      case MuRefValue(t, vb)  => (t, vb.objRef)
      case MuIRefValue(t, vb) => (t, vb.objRef)
      case _ => {
        throw new IllegalArgumentException("loc must be ref or iref. Found %s".format(loc.ty))
      }
    }
    unpin(objRef)
  }
Kunshan Wang's avatar
Kunshan Wang committed
688

689 690 691 692 693 694 695 696 697
  def getAddr(loc: MuValue): MuUPtrValue = {
    val (objTy, (objRef, offset)) = loc match {
      case MuRefValue(t, vb)  => (t, (vb.objRef, 0L))
      case MuIRefValue(t, vb) => (t, vb.oo)
      case _ => {
        throw new IllegalArgumentException("loc must be ref or iref. Found %s".format(loc.ty))
      }
    }
    // do nothing
Kunshan Wang's avatar
Kunshan Wang committed
698 699
    val addr = objRef + offset
    assert(microVM.memoryManager.globalMemory.isInSpace(addr) || pinSet.contains(objRef),
Kunshan Wang's avatar
Kunshan Wang committed
700 701
      "Attempt to get address of objref %d 0x%x, offset %d, 0x%x, which is neither a global cell nor pinned by the current thread.".format(
        objRef, objRef, offset, offset))
702
    val ptrTy = internalEntityPool.ptrOf(objTy)
Kunshan Wang's avatar
Kunshan Wang committed
703
    val box = new BoxPointer(addr)
704 705
    addHandle(MuUPtrValue(ptrTy, box))
  }
Kunshan Wang's avatar
Kunshan Wang committed
706 707 708

  def expose(func: MuFuncRefValue, callConv: Flag, cookie: MuIntValue): MuUFPValue = {
    val TypeFuncRef(sig) = func.ty
709
    val f = func.vb.obj.getOrElse {
Kunshan Wang's avatar
Kunshan Wang committed
710 711 712 713 714 715
      throw new UvmRuntimeException("Attempt to expose NULL Mu function")
    }

    val c = cookie.vb.value.toLong

    val addr = microVM.nativeCallHelper.exposeFuncDynamic(f, c)
716
    addHandle(MuUFPValue(internalEntityPool.funcPtrOf(sig), BoxPointer(addr)))
Kunshan Wang's avatar
Kunshan Wang committed
717 718 719 720 721 722
  }

  def unexpose(callConv: Flag, addr: MuUFPValue): Unit = {
    val a = addr.vb.addr
    microVM.nativeCallHelper.unexposeFunc(a)
  }
723

Kunshan Wang's avatar
Kunshan Wang committed
724
  def newIRBuilder(): IRBuilder = {
725
    microVM.newIRBuilder()
Kunshan Wang's avatar
Kunshan Wang committed
726
  }
Kunshan Wang's avatar
Kunshan Wang committed
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756

  def makeBootImage(whiteList: Seq[MuID],
    primordialFunc: Option[MuFuncRefValue], primordialStack: Option[MuStackRefValue], primordialThreadLocal: Option[MuRefValue],
    symFields: Seq[MuIRefValue], symStrings: Seq[String], relocFields: Seq[MuIRefValue], relocStrings: Seq[String],
    outputFile: String): Unit = {
    
    val whiteListObjs = whiteList.map(microVM.globalBundle.topLevelNs.apply)
    
    val maybePF = primordialFunc.flatMap(_.vb.obj)
    val maybePS = primordialStack.flatMap(_.vb.obj)
    val maybeTL = primordialThreadLocal.flatMap { h =>
      h.vb.objRef match {
        case 0 => None
        case a => Some(a)
      }
    }
    
    val primordial = PrimordialInfo(maybePF, maybePS, maybeTL)

    val symFlds = symFields.map { h => (h.vb.objRef, h.vb.offset) }
    val relocFlds = relocFields.map { h =>
      assert(h.ty.ty.isInstanceOf[AbstractPointerType], "Reloc field %d 0x%x is not a pointer field. field type: %s".format(
        h.vb.addr, h.vb.addr, h.ty.ty))
      (h.vb.objRef, h.vb.offset)
    }
    
    val syms = for (((obj, off), name) <- symFlds zip symStrings) yield FieldAndSymbol(obj, off, name)
    val relocs = for (((obj, off), name) <- relocFlds zip relocStrings) yield FieldAndSymbol(obj, off, name)
    
    microVM.bootImageBuilder.makeBootImage(whiteListObjs, primordial, syms, relocs, outputFile)
757
  }
Kunshan Wang's avatar
Kunshan Wang committed
758 759 760 761

  // Internal methods for the micro VM

  def handleFromInterpreterThread(thr: Option[InterpreterThread]): MuThreadRefValue = {
762
    val t = predefinedEntities.THREADREF
Kunshan Wang's avatar
Kunshan Wang committed
763 764 765 766 767
    val box = BoxThread(thr)
    addHandle(MuThreadRefValue(t, box))
  }

  def handleFromInterpreterStack(sta: Option[InterpreterStack]): MuStackRefValue = {
768
    val s = predefinedEntities.STACKREF
Kunshan Wang's avatar
Kunshan Wang committed
769 770 771 772 773
    val box = BoxStack(sta)
    addHandle(MuStackRefValue(s, box))
  }

  def handleFromAddr(addr: Long): MuRefValue = {
774
    val t = predefinedEntities.REF_VOID
Kunshan Wang's avatar
Kunshan Wang committed
775 776 777 778 779
    val box = BoxRef(addr)
    addHandle(MuRefValue(t, box))
  }
}