Skip to content
Merged
Show file tree
Hide file tree
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
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ cs launch --scala 2.13 org.chipsalliance::firtool-resolver:2.2.0 \
3. If no explicit version is set, honor `llvm-firtool` on the classpath. This legacy mechanism logs a deprecation message at info level.
4. Reuse the cached binary at `<cache>/<effective-version>/bin/firtool`.
5. Download the effective version from GitHub, verify its checksum, and atomically install just the executable in the cache. Downloads are locked per version across processes.
6. As a last resort, fetch `llvm-firtool` with Coursier from Maven. This supports older versions and environments that can reach a Maven proxy but cannot reach GitHub; it only works for already-published artifacts.

### Configuration

Expand Down Expand Up @@ -59,15 +58,15 @@ To use an internal web server (HTTP or HTTPS), an Artifactory generic remote, or
| `macos-aarch64` | `firrtl-bin-macos-arm64.tar.gz` |
| `windows-x64` | `firrtl-bin-windows-x64.zip` |

GitHub fetching supports versions starting at **1.45.0**. Native macOS arm64 assets start at **1.144.0**; earlier versions fall back to macOS x64 through Rosetta. Older releases remain available through the legacy Maven path.
GitHub fetching supports versions starting at **1.45.0**. Native macOS arm64 assets start at **1.144.0**; earlier versions fall back to macOS x64 through Rosetta. For versions older than **1.45.0**, provide a local binary or a legacy jar on the classpath.

### Development and release

Run `./mill -i 'firtool-resolver[_].test'` for the tests on both Scala versions, or `./mill -i 'firtool-resolver[2.13].test'` for just Scala 2.13.

The tests are MUnit tests that run the resolver in real JVMs against local fixtures (a fake release mirror, a fake Maven repository, and local HTTP servers), once from the unshaded classes and once from the shaded jar as published. They also check the contents of the published jar.
The tests are MUnit tests that run the resolver in real JVMs against local fixtures (a fake release mirror, classpath resources, and local HTTP servers), once from the unshaded classes and once from the shaded jar as published. They also check the contents of the published jar.

`LiveTests` additionally exercise the real GitHub releases, Maven Central, and real firtool binaries. They need network access, are tagged `live`, and run by default. Use MUnit's tag filters to select which tests to run:
`LiveTests` downloads and runs a real firtool release from GitHub. It needs network access, is tagged `live`, and runs by default. Use MUnit's tag filters to select which tests to run:

```bash
# Hermetic tests only
Expand Down
27 changes: 2 additions & 25 deletions build.mill
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,6 @@ trait FirtoolResolver extends CrossScalaModule with ChipsAlliancePublishModule {
Agg(PathRef(dir))
}

// TODO These are the things stripped from upstreamAssemblyClasspath (in addition to scala-library).
// Is it possible to derive these automatically?
def ivyDeps = Agg(
ivy"org.scala-lang.modules::scala-xml:2.2.0",
ivy"org.scala-lang.modules::scala-collection-compat:2.11.0"
)

object core extends ScalaModule {

def scalaVersion = root.scalaVersion
Expand All @@ -132,14 +125,13 @@ trait FirtoolResolver extends CrossScalaModule with ChipsAlliancePublishModule {
// getting System property os.name
def ivyDeps = Agg(
ivy"dev.dirs:directories:26",
ivy"io.get-coursier::coursier:2.1.8",
ivy"org.apache.commons:commons-compress:1.24.0",
)

// Modify the classpath to remove things we want to dynamically link (Scala jars).
override def upstreamIvyAssemblyClasspath: T[Agg[PathRef]] = T {
val all = super.upstreamIvyAssemblyClasspath()
// Remove Scala jars (scala-library, scala-collection-compat, scala-xml, etc.)
// The published assembly links against Scala rather than bundling it.
val regex = """scala.*\.jar""".r
all.filterNot(p => regex.matches(p.path.last))
}
Expand All @@ -148,24 +140,9 @@ trait FirtoolResolver extends CrossScalaModule with ChipsAlliancePublishModule {
// Including the launcher causes unzip to fail.
override def prependShellScript: T[String] = T { "" }

// It would be nice if this could be derived from dependencies.
def packagesToShade = Seq(
"dev.dirs",
"coursier",
"com.github.plokhotnyuk",
"concurrentrefhashmap",
"org.codehaus",
"scala.cli",
"io.github.alexarchambault",
"javax.inject",
"org.apache.commons",
"org.slf4j",
"org.iq80.snappy",
"org.tukaani.xz",
"com.github.luben.zstd",
"org.apache.xbean",
"org.fusesource.jansi",
"org.fusesource.hawtjni",
"org.apache.commons.compress",
)

override def assemblyRules =
Expand Down
67 changes: 4 additions & 63 deletions src/Main.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@ import scala.io.Source
import java.io.File
import java.nio.file.{Path, Paths, Files, StandardCopyOption, StandardOpenOption}
import java.nio.channels.FileChannel
import java.net.URLClassLoader
import scala.sys.process._

import dev.dirs.ProjectDirectories
import coursier._
import coursier.core.Extension

final case class FirtoolBinary(path: File, version: String)

Expand All @@ -23,7 +20,6 @@ final case class FirtoolBinary(path: File, version: String)
* - Check for firtool on the CHISEL_FIRTOOL_PATH, note any version mismatch
* - Honor an explicit version override, otherwise check classpath resources
* - Reuse the version's cache, or download and verify a GitHub release
* - Use Coursier to fetch legacy Maven artifacts as a last resort
*/
object Resolve {

Expand Down Expand Up @@ -163,15 +159,15 @@ object Resolve {
}
}

private def checkResources(classloader: Option[URLClassLoader], logger: Logger): Either[String, FirtoolBinary] = {
private def checkResources(logger: Logger): Either[String, FirtoolBinary] = {
val platform = determinePlatform(logger)
logger.debug("Checking resources for firtool")
if (platform.isLeft) {
logger.debug(platform.merge)
return Left(platform.merge) // Help out the type system
}
val primaryPlatform = platform.toOption.get
val resourceLoader = classloader.getOrElse(this.getClass.getClassLoader)
val resourceLoader = this.getClass.getClassLoader

val baseDir = s"$groupId/$artId"
val versionFile = resourceLoader.getResource(s"$baseDir/project.version")
Expand Down Expand Up @@ -308,60 +304,6 @@ object Resolve {
}
}

private def fetchArtifact(logger: Logger, defaultVersion: String): Either[String, FirtoolBinary] = {
val platform =
determinePlatform(logger) match {
case Left(msg) =>
logger.debug(msg)
return Left(msg)
case Right(name) => name
}

// Try fetching for a specific platform classifier; returns Left on any failure.
def tryFetch(p: String): Either[String, FirtoolBinary] = {
// See coursier.parse.DependencyParser to understand how the classifier is added via Publication
val org = Organization(groupId)
val module = Module(org, ModuleName(s"$artId"), Map())
val dep =
Dependency(module, defaultVersion)
.withPublication("", Type.empty, Extension.empty, Classifier(p))
// One would think there'd be a built-in pretty print like this but there isn't
// (coursier.util.Print doesn't include the classifier)
logger.debug(s"Attempting to fetch ${dep.module}:${dep.version},classifier=${p}")

val resolution = Try {
coursier.Fetch()
.addDependencies(dep)
.run()
}
if (resolution.isFailure) {
val msg = resolution.failed.get.toString + "\n" // Coursier's message is already pretty good
logger.debug(msg)
return Left(msg)
}
// Head here is dangerous, without the classifier, multiple jars are fetched
val jar = resolution.get.head
logger.debug(s"Successfully fetched $jar")

logger.debug(s"Loading $jar to search its resources")
// A version override must not be shadowed by resources in the parent classloader.
val classloader = new URLClassLoader(Array(jar.toURI.toURL), null)
try checkResources(Some(classloader), logger)
finally classloader.close()
}

tryFetch(platform) match {
case right @ Right(_) => right
case left @ Left(_) =>
fallbackPlatform(platform) match {
case Some(fallback) =>
logger.debug(s"Falling back to platform $fallback")
tryFetch(fallback)
case None => left
}
}
}

/** Lookup firtool binary
*
* @param defaultVersion fallback version to fetch if not found in CHISEL_FIRTOOL_PATH nor on classpath
Expand All @@ -386,7 +328,7 @@ object Resolve {
logger.warn(s"Firtool version override $v takes precedence over llvm-firtool $classpathVersion on the classpath")
}
Left("Classpath lookup skipped because an explicit firtool version is set")
case None => checkResources(None, logger).map { binary =>
case None => checkResources(logger).map { binary =>
logger.info(s"using llvm-firtool ${binary.version} from classpath; this mechanism is deprecated, set chisel.firtool.version instead")
binary
}
Expand All @@ -400,8 +342,7 @@ object Resolve {
for {
cacheError <- checkInstalled(logger, version).left
githubError <- fetchFromGitHub(logger, version).left
mavenError <- fetchArtifact(logger, version).left
} yield List("Failed to fetch firtool:", pathError, resourceError, cacheError, githubError, mavenError).mkString("\n")
} yield List("Failed to fetch firtool:", pathError, resourceError, cacheError, githubError).mkString("\n")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion test/src/HttpTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class HttpTests extends TemporaryDirectorySuite with LogAssertions {
server.start()
try {
val url = s"http://${server.getAddress.getAddress.getHostAddress}:${server.getAddress.getPort}"
import scala.jdk.CollectionConverters._
import scala.collection.JavaConverters._
body(url, () => requests.asScala.toVector)
} finally server.stop(0)
}
Expand Down
10 changes: 7 additions & 3 deletions test/src/JarTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,13 @@ class JarTests extends munit.FunSuite {
}

test("dependencies are shaded and not left at their original packages") {
val unshaded = Seq("coursier/", "dev/dirs/", "org/apache/commons/")
val leaked = entries.filter(e => unshaded.exists(e.startsWith))
// Check every class, including any introduced by new transitive dependencies.
val leaked = entries.filter(e => e.endsWith(".class") && !e.startsWith("firtoolresolver/"))
assert(leaked.isEmpty, s"unshaded entries:\n${leaked.take(10).mkString("\n")}")
assert(entries.exists(_.startsWith("firtoolresolver/shaded/coursier/")), "coursier was not shaded")
Seq("dev/dirs/", "org/apache/commons/compress/").foreach { pkg =>
assert(entries.exists(e => e.startsWith(s"firtoolresolver/shaded/$pkg") && e.endsWith(".class")),
s"missing shaded classes for $pkg")
}
assert(!entries.exists(_.contains("coursier/")), "jar contains Coursier classes")
}
}
66 changes: 8 additions & 58 deletions test/src/LiveTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,70 +2,20 @@

package firtoolresolver

import coursier._
import coursier.core.Extension
import java.nio.file.{Files, Path, Paths}
import java.nio.file.Paths
import Check._

/** Tests of what hermetic fixtures cannot prove: the real GitHub releases, Maven Central, and real firtool binaries.
*
* These are tagged "live" and need network access (and download a few hundred MB).
* They run the resolver as published, i.e. from the shaded classpath.
*
* llvm-firtool is no longer published, so use a version already on Maven Central that is also a GitHub release.
*/
class LiveTests extends TemporaryDirectorySuite with LogAssertions {
private val firtoolVersion = "1.162.0"
private val Live = new munit.Tag("live")

private def live(name: String)(body: Sandbox => Unit): Unit =
directory.test(name.tag(Live)) { root =>
body(new Sandbox(root, "firtoolresolver.test.shaded.classpath"))
}

private def resolved(result: Result): Path = {
directory.test("downloads and runs a real GitHub release".tag(Live)) { root =>
val version = "1.162.0"
val sandbox = new Sandbox(root, "firtoolresolver.test.shaded.classpath")
val result = sandbox.launch(arg = version, envVersion = None, envURL = None).await()
assertEquals(result.exit, 0, result.output)
Paths.get(result.out.trim)
}

// Real firtool prints an LLVM banner before its CIRCT version line, and some releases append a git describe suffix.
private def assertRealFirtool(s: Sandbox, binary: Path): Unit = {
val output = s.runFirtool(binary)
assert(output.linesIterator.exists(_.matches(s"CIRCT firtool-${java.util.regex.Pattern.quote(firtoolVersion)}(-.*)?")),
output)
}

live("downloads a real release from GitHub") { s =>
val result = s.launch(arg = firtoolVersion, envVersion = None, envURL = None, envRepos = None).await()
val binary = resolved(result)
checkLog(result.err, has("Verified SHA-256 checksum:"))
assertAbsent(result.err, "Attempting to fetch org.chipsalliance:llvm-firtool:")
assertRealFirtool(s, binary)

}

live("falls back to the real llvm-firtool on Maven Central when GitHub fails") { s =>
val result = s.launch(
arg = firtoolVersion, envVersion = None, envURL = Some("file:///nonexistent"), envRepos = Some("central")).await()
val binary = resolved(result)
checkLog(result.err,
has(s"Attempting to fetch org.chipsalliance:llvm-firtool:$firtoolVersion"),
has("Successfully fetched"))
assertRealFirtool(s, binary)
}

live("copies firtool from the real llvm-firtool jar on the classpath") { s =>
def fetch(platform: String): Seq[java.io.File] = {
val dep = Dependency(Module(Organization("org.chipsalliance"), ModuleName("llvm-firtool")), firtoolVersion)
.withPublication("", Type.empty, Extension.empty, Classifier(platform))
Fetch().addDependencies(dep).run()
}
val jar = scala.util.Try(fetch(Host.platform)).getOrElse(fetch("macos-x64"))
val result = s.launch(
arg = firtoolVersion, envVersion = None, envURL = Some("file:///nonexistent"), envRepos = None,
extraClasspath = jar.map(_.toPath).take(1)).await()
val binary = resolved(result)
checkLog(result.err, has(s"using llvm-firtool $firtoolVersion from classpath"))
assertRealFirtool(s, binary)
val output = sandbox.runFirtool(Paths.get(result.out.trim))
assert(output.linesIterator.exists(_.matches(s"CIRCT firtool-${java.util.regex.Pattern.quote(version)}(-.*)?")),
output)
}
}
38 changes: 6 additions & 32 deletions test/src/ResolverTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
package firtoolresolver

import java.nio.file.{Files, Path}
import scala.jdk.CollectionConverters._
import scala.collection.JavaConverters._
import Check._
import TestFixtures._

/** Hermetic resolver tests run real JVMs against local release and Maven fixtures.
/** Hermetic resolver tests run real JVMs against local release and classpath fixtures.
*
* This covers what used to be the FileCheck scripts; the only things left out are those requiring real servers
* (see [[LiveTests]]).
Expand Down Expand Up @@ -90,7 +90,7 @@ abstract class ResolverSuite(classpathProperty: String) extends TemporaryDirecto
write(s.asset.checksum, bytes("0" * 64))
val result = failed(s.launch())
assert(result.err.contains(s"expected ${"0" * 64}, actual ${digest(s.asset.archive)}"), result.output)
assert(result.err.contains("Attempting to fetch org.chipsalliance:llvm-firtool:"), result.output)
assertAbsent(result.err, "Attempting to fetch org.chipsalliance:llvm-firtool:")
assert(result.err.contains("Failed to fetch firtool:"), result.output)
assert(!Files.exists(s.binary()))
assertEquals(walk(s.cache.resolve(s.version)).count(Files.isRegularFile(_)), 0)
Expand Down Expand Up @@ -169,29 +169,6 @@ abstract class ResolverSuite(classpathProperty: String) extends TemporaryDirecto
assert(!Files.exists(s.binary(s.classpathVersion)))
}

// ---- Maven fallback (coursier_fallback.sh) ----

directory.test("falls back to Maven when GitHub fails") { root =>
val s = sandbox(root)
s.publishMaven()
val result = succeeded(s.launch(arg = s.version, envVersion = None, envURL = Some("file:///nonexistent")))
checkLog(result.err,
has(s"Fetching firtool ${s.version} from GitHub failed:"),
has(s"Attempting to fetch org.chipsalliance:llvm-firtool:${s.version}"),
has(s"Firtool version ${s.version} found in resources"))
assertEquals(java.nio.file.Paths.get(result.out.trim), s.binary())
assertEquals(Files.readAllBytes(s.binary()).toSeq, s.executable.toSeq)
}

directory.test("Maven fallback honors the override despite a different classpath version") { root =>
val s = sandbox(root)
s.publishMaven()
val result = succeeded(s.launch(extraClasspath = Seq(s.classpathResources()), envURL = Some("file:///nonexistent")))
assert(result.err.contains(s"Firtool version ${s.version} found in resources"), result.output)
assertEquals(Files.readAllBytes(s.binary()).toSeq, s.executable.toSeq)
assert(!Files.exists(s.cache.resolve(s.classpathVersion)))
}

// ---- Platform fallback (platform_fallback.sh) ----

directory.test("macOS arm64 falls back to the x64 release asset when no arm64 asset is published") { root =>
Expand Down Expand Up @@ -220,15 +197,12 @@ abstract class ResolverSuite(classpathProperty: String) extends TemporaryDirecto
result.output)
}

directory.test("macOS arm64 falls back to x64 resources in Maven artifacts") { root =>
directory.test("macOS arm64 falls back to x64 resources on the classpath") { root =>
val s = sandbox(root, Nil)
s.publishMaven(forPlatforms = Seq("macos-x64"))
val result = succeeded(s.launch(arg = s.version, envVersion = None, javaOpts = Host.macArm64))
val result = succeeded(s.launch(arg = s.version, envVersion = None, javaOpts = Host.macArm64,
extraClasspath = Seq(s.classpathResources(platform = "macos-x64"))))
checkLog(result.err,
has("Falling back to platform macos-x64"),
has(s"Firtool version ${s.version} found in resources"),
has("Falling back to macos-x64 resources"))
assertEquals(Files.readAllBytes(s.binary()).toSeq, s.executable.toSeq)
}

// ---- CHISEL_FIRTOOL_PATH (firtool_path.sh) ----
Expand Down
Loading
Loading