Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[svsim] Make EphemeralSimulator multi-processing friendly #3847

Merged
merged 1 commit into from
Feb 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions src/main/scala/chisel3/simulator/EphemeralSimulator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,27 @@ package chisel3.simulator

import svsim._
import chisel3.RawModule
import java.nio.file.Files
import java.io.File
import scala.reflect.io.Directory

/** Provides a simple API for "ephemeral" invocations (where you don't care about the artifacts after the invocation completes) to
* simulate Chisel modules. To keep things really simple, `EphemeralSimulator` simulations can only be controlled using the
* peek/poke API, which provides enough control while hiding some of the lower-level svsim complexity.
* @example
* ```
* {{{
* import chisel3.simulator.EphemeralSimulator._
* ...
* simulate(new MyChiselModule()) { module => ... }
* ```
* }}}
*/
object EphemeralSimulator extends PeekPokeAPI {

def simulate[T <: RawModule](
module: => T
)(body: (T) => Unit
): Unit = {
synchronized {
simulator.simulate(module)({ module => body(module.wrapped) }).result
}
makeSimulator.simulate(module)({ module => body(module.wrapped) }).result
}

private class DefaultSimulator(val workspacePath: String) extends SingleBackendSimulator[verilator.Backend] {
Expand All @@ -32,15 +33,14 @@ object EphemeralSimulator extends PeekPokeAPI {

// Try to clean up temporary workspace if possible
sys.addShutdownHook {
Runtime.getRuntime().exec(Array("rm", "-rf", workspacePath)).waitFor()
(new Directory(new File(workspacePath))).deleteRecursively()
}
}
private lazy val simulator: DefaultSimulator = {
val temporaryDirectory = System.getProperty("java.io.tmpdir")
private def makeSimulator: DefaultSimulator = {
// TODO: Use ProcessHandle when we can drop Java 8 support
// val id = ProcessHandle.current().pid().toString()
val id = java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
val className = getClass().getName().stripSuffix("$")
new DefaultSimulator(Seq(temporaryDirectory, className, id).mkString("/"))
new DefaultSimulator(Files.createTempDirectory(s"${className}_${id}_").toString)
}
}
Loading