Skip to content

Instantly share code, notes, and snippets.

@hongjiang
Forked from tyrcho/JDIDemo.scala
Created February 18, 2016 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongjiang/3c40e751701c24d9d750 to your computer and use it in GitHub Desktop.
Save hongjiang/3c40e751701c24d9d750 to your computer and use it in GitHub Desktop.
JDI in Scala (Java Debug Interface)
// see http://wayne-adams.blogspot.fr/2011/10/generating-minable-event-stream-with.html
import scala.collection.JavaConversions.asScalaBuffer
import scala.collection.JavaConversions.asScalaIterator
import com.sun.jdi.connect.Connector
import com.sun.jdi.event.BreakpointEvent
import com.sun.jdi.request.BreakpointRequest
import com.sun.jdi.request.EventRequest
import com.sun.jdi.Bootstrap
import com.sun.jdi.StringReference
object JDIDemo extends App {
val debugPort = args(0).toInt
val lineNumber = args(1).toInt
val varName = args(2)
val vmMgr = Bootstrap.virtualMachineManager
val socketConnector = vmMgr.attachingConnectors.find(_.transport.name == "dt_socket") match {
case Some(c) => c
case None => throw new Exception("not found : dt_socket")
}
val paramsMap = socketConnector.defaultArguments
val portArg = paramsMap.get("port").asInstanceOf[Connector.IntegerArgument]
portArg.setValue(debugPort)
val vm = socketConnector.attach(paramsMap)
println("Attached to process '" + vm.name + "'")
val refTypes = vm.allClasses
val breakpointLocations = for (r <- refTypes; l <- r.allLineLocations if l.lineNumber == lineNumber) yield l
val breakpointLocation = breakpointLocations(0)
val evtReqMgr = vm.eventRequestManager
val bReq = evtReqMgr.createBreakpointRequest(breakpointLocation)
bReq.setSuspendPolicy(EventRequest.SUSPEND_ALL)
bReq.enable()
val evtQueue = vm.eventQueue
while (true) {
val evtSet = evtQueue.remove()
for (evt <- evtSet.eventIterator) {
evt.request match {
case bpReq: BreakpointRequest if bpReq.location.lineNumber == lineNumber =>
System.out.println("Breakpoint at line " + lineNumber + ": ")
val brEvt = evt.asInstanceOf[BreakpointEvent]
val threadRef = brEvt.thread
val stackFrame = threadRef.frame(0)
for (visibleVar <- stackFrame.visibleVariables if (visibleVar.name == varName))
stackFrame.getValue(visibleVar) match {
case varNameValue: StringReference => println(varName + " = '" + varNameValue + "'")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment