aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/util/JvmUtil.kt
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/kotlin/util/JvmUtil.kt')
-rw-r--r--src/main/kotlin/util/JvmUtil.kt32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/main/kotlin/util/JvmUtil.kt b/src/main/kotlin/util/JvmUtil.kt
new file mode 100644
index 0000000..5be5ebd
--- /dev/null
+++ b/src/main/kotlin/util/JvmUtil.kt
@@ -0,0 +1,32 @@
+package moe.nea.firmament.util
+
+import com.sun.tools.attach.VirtualMachine
+import java.lang.management.ManagementFactory
+import java.nio.file.Path
+import kotlin.io.path.absolutePathString
+
+object JvmUtil {
+ fun guessJVMPid(): String {
+ val name = ManagementFactory.getRuntimeMXBean().name
+ val pid = name.substringBefore('@')
+ ErrorUtil.softCheck("Not a valid PID: $pid", pid.toIntOrNull() != null)
+ return pid
+ }
+
+ fun getVM(): VirtualMachine {
+ return VirtualMachine.attach(guessJVMPid())
+ }
+
+ fun useVM(block: (VirtualMachine) -> Unit) {
+ val vm = getVM()
+ block(vm)
+ vm.detach()
+ }
+
+ fun loadAgent(jarPath: Path, options: String? = null) {
+ useVM {
+ it.loadAgent(jarPath.absolutePathString(), options)
+ }
+ }
+
+}