Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

C#: launch through the apphost, scan --duration, better attribution (#79)

EL4CTEOd6195ae1f12d
diff --git a/.gitignore b/.gitignore
index 776818e..c2735f0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ examples/*/bin/
examples/*/obj/
src/csharp/bin/
src/csharp/obj/
+__pycache__/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3bccfdd..493de95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,16 @@
# Changelog
+## 0.8.6
+
+- C#: apps start through their own launcher (`App.exe`), as `dotnet run` does, so WinUI 3 / Windows App SDK apps no longer crash with `0xc000027b` (#79).
+- C#: `scan --duration 30` stops a GUI or server after 30 seconds and ranks what ran (#79).
+- C#: async methods, lambdas and local functions count toward the method that holds them; waiting threads no longer dilute the shares (#79).
+- C#: when the time is in libraries reached from `Main` or async code, `scan` says which; `dotnet test` gets a clear explanation (#79).
+- `doctor` tells "ready to scan" from "ready to port": scanning doesn't need Rust (#79).
+- MCP `fast_scan` returns `why_not` for each function and the scan's notes.
+
+Thanks @JuggyBob.
+
## 0.8.5
- `scan`: a function whose helper does I/O or is nondeterministic is no longer ranked portable (#75).
diff --git a/README.md b/README.md
index 43cd790..e7f6388 100644
--- a/README.md
+++ b/README.md
@@ -100,7 +100,7 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo) | ✅ |
| PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`) | ✅ |
| C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ |
-| C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install | ✅ |
+| C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install; GUIs and servers: `scan --duration 30` | ✅ |
| R 4.0+ (`Rscript app.R`) | the same C bridge, through base R's `.C()`; profiled with Rprof, no packages or R headers needed | ✅ |
It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions and `@staticmethod`s (dataclasses, NamedTuples and numeric NumPy arrays count as plain data), in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
diff --git a/src/backend.rs b/src/backend.rs
index 0a01af6..734aa08 100644
--- a/src/backend.rs
+++ b/src/backend.rs
@@ -34,6 +34,9 @@ pub struct Profile {
pub wall: f64,
pub base: String,
pub functions: Vec<Hotspot>,
+ /// What the scan should tell the user besides the ranking.
+ #[serde(default)]
+ pub notes: Vec<String>,
}
#[derive(Deserialize)]
@@ -145,7 +148,7 @@ impl Lang {
Lang::Go => golang::profile(ctx, exe, args),
Lang::Php => php::profile(ctx, exe, args),
Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),
- Lang::CSharp => csharp::profile(ctx, exe, args),
+ Lang::CSharp => csharp::profile(ctx, exe, args, None),
Lang::R => r::profile(ctx, exe, args),
Lang::Kotlin => kotlin::profile(ctx, exe, args),
}
diff --git a/src/cfamily.rs b/src/cfamily.rs
index 419a21c..4a52a4d 100644
--- a/src/cfamily.rs
+++ b/src/cfamily.rs
@@ -894,7 +894,7 @@ pub fn profile(ctx: &Ctx, cc: &str, args: &[String], lang: Lang) -> Result<Profi
None => {}
}
}
- Ok(Profile { wall, base: ".".into(), functions })
+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })
}
// ------------------------------------------------------------------ recording
diff --git a/src/csharp.rs b/src/csharp.rs
index 89459c5..381eafa 100644
--- a/src/csharp.rs
+++ b/src/csharp.rs
@@ -16,7 +16,7 @@ use std::fs;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
-use std::time::Instant;
+use std::time::{Duration, Instant};
const TOOLS_PROJECT: &str = include_str!("csharp/Tools.csproj");
const TOOLS_PROGRAM: &str = include_str!("csharp/Program.cs");
@@ -49,6 +49,11 @@ impl DotnetRun {
fn parse(args: &[String]) -> Result<DotnetRun> {
let usage =
"run the app as a project: fast-anything scan -- dotnet run -c Release (or --project path/App.csproj)";
+ ensure!(
+ args.first().map(String::as_str) != Some("test"),
+ "dotnet test runs your code in a separate testhost process, which isn't profiled. Scan the app itself, or a \
+ small console project that calls the code under test with real input:\n fast-anything scan -- dotnet run -c Release --project path/App.csproj"
+ );
ensure!(args.first().map(String::as_str) == Some("run"), "{usage}");
let mut run = DotnetRun::default();
let mut i = 1;
@@ -130,18 +135,39 @@ fn build(ctx: &Ctx, dotnet: &str, run: &DotnetRun) -> Result<PathBuf> {
Ok(target)
}
+/// The app's own launcher next to its assembly (App.exe, or App on Linux and macOS), as dotnet run starts it.
+/// It carries the app's manifest: WinUI 3 and other Windows App SDK apps crash with 0xc000027b without it.
+fn apphost(dll: &Path) -> Option<PathBuf> {
+ let host = dll.with_extension(std::env::consts::EXE_EXTENSION);
+ (host != dll && host.is_file()).then_some(host)
+}
+
+/// How to start the built app: its launcher if it has one, else dotnet App.dll.
+fn app_argv(dotnet: &str, dll: &Path, args: &[String]) -> (String, Vec<String>) {
+ let (program, mut argv) = match apphost(dll) {
+ Some(host) => (host.to_string_lossy().into_owned(), vec![]),
+ None => (dotnet.to_string(), vec![dll.to_string_lossy().into_owned()]),
+ };
+ argv.extend(args.iter().cloned());
+ (program, argv)
+}
+
fn app_command(dotnet: &str, dll: &Path, args: &[String]) -> Command {
- let mut cmd = Command::new(dotnet);
- cmd.arg(dll).args(args);
+ let (program, argv) = app_argv(dotnet, dll, args);
+ let mut cmd = Command::new(program);
+ cmd.args(argv);
+ // the launcher looks for the runtime here first, so it runs on the same .NET as dotnet
+ let dir = Path::new(dotnet).parent().filter(|d| Path::new(dotnet).is_absolute() && d.is_dir());
+ if let (Some(dir), None) = (dir, std::env::var_os("DOTNET_ROOT")) {
+ cmd.env("DOTNET_ROOT", dir);
+ }
cmd
}
pub fn bench_command(ctx: &Ctx, dotnet: &str) -> Result<(String, Vec<String>)> {
let run = DotnetRun::parse(&ctx.state.command[1..])?;
let dll = build(ctx, dotnet, &run)?;
- let mut args = vec![dll.to_string_lossy().into_owned()];
- args.extend(run.args);
- Ok((dotnet.to_string(), args))
+ Ok(app_argv(dotnet, &dll, &run.args))
}
// ------------------------------------------------------------------ the helper (Roslyn + TraceEvent)
@@ -250,28 +276,89 @@ fn describe(ctx: &Ctx, dotnet: &str, dir: &Path) -> Result<Vec<Method>> {
serde_json::from_str(&fs::read_to_string(&out)?).context("reading the method list")
}
-/// "Ns.Outer+Inner.Method(int32,class System.String)" -> ("Ns.Outer+Inner", "Method")
+/// "Ns.Outer+Inner.Method(int32,class System.String)" -> ("Ns.Outer+Inner", "Method"). Code the compiler writes
+/// for a method counts as that method: its async or iterator state machine ("Ns.App+<RunAsync>d__3.MoveNext()"),
+/// its lambdas ("Ns.App+<>c.<Main>b__0_0()") and its local functions ("Ns.App.<Main>g__Step|0_0()").
fn split_frame(frame: &str) -> Option<(&str, &str)> {
let head = frame.split('(').next()?;
- head.rsplit_once('.')
+ let (class, name) = head.rsplit_once('.')?;
+ // "<Method>..." -> "Method"
+ fn generated(s: &str) -> Option<&str> {
+ s.strip_prefix('<')?.split_once('>').map(|(m, _)| m)
+ }
+ // a class the compiler nested in the method's class: "Ns.App+<>c" -> "Ns.App"
+ let owner = match class.rsplit_once('+') {
+ Some((o, nested)) if nested.starts_with('<') => Some((o, nested)),
+ _ => None,
+ };
+ if let Some(m) = generated(name).filter(|m| !m.is_empty()) {
+ return Some((owner.map_or(class, |(o, _)| o), m));
+ }
+ if let Some((o, nested)) = owner
+ && let Some(m) = generated(nested).filter(|m| !m.is_empty())
+ {
+ return Some((o, m));
+ }
+ Some((class, name))
+}
+
+/// A sample of a thread that was waiting (a blocked Main, an idle thread-pool worker), not working. The wait can
+/// sit a frame or two under the leaf, in the call into the OS that does it.
+fn idle(frames: &[String]) -> bool {
+ const WAITS: [&str; 13] = [
+ "Interop+Kernel32.GetQueuedCompletionStatus",
+ "System.Threading.Monitor.Wait",
+ "System.Threading.WaitHandle.Wait",
+ "System.Threading.Thread.Sleep",
+ "System.Threading.Thread.Join",
+ "System.Threading.LowLevelLifoSemaphore.",
+ "System.Threading.LowLevelMonitor.Wait",
+ "System.Threading.ManualResetEventSlim.Wait",
+ "System.Threading.SemaphoreSlim.Wait",
+ "System.Threading.Tasks.Task.SpinThenBlockingWait",
+ "System.Threading.Tasks.Task.InternalWaitCore",
+ "System.Threading.PortableThreadPool+GateThread.",
+ "System.Threading.WaitSubsystem.",
+ ];
+ frames.iter().take(3).any(|f| WAITS.iter().any(|w| f.starts_with(w)))
+}
+
+/// "SixLabors.ImageSharp.Formats.Webp.Encoder.Encode(...)" -> "SixLabors.ImageSharp"
+fn library(frame: &str) -> String {
+ let head = frame.split('(').next().unwrap_or(frame);
+ let parts: Vec<&str> = head.split('.').collect();
+ parts[..parts.len().saturating_sub(2).clamp(1, 2)].join(".")
}
fn rel(ctx: &Ctx, p: &Path) -> String {
util::forward_slashes(p.strip_prefix(&ctx.root).unwrap_or(p))
}
-pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String]) -> Result<Profile> {
+/// `duration`: stop the app after that many seconds, for GUIs and servers that run until closed.
+pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {
let run = DotnetRun::parse(args)?;
let dll = build(ctx, dotnet, &run)?;
let trace_dir = ctx.fast.join("nettrace");
let _ = fs::remove_dir_all(&trace_dir);
fs::create_dir_all(&trace_dir)?;
+ let mut cmd = app_command(dotnet, &dll, &run.args);
+ if let Some(d) = duration {
+ crate::ui::line(format!(" stopping it after {d}s"));
+ // the helper's startup hook ends the app from inside, so its trace is complete
+ let hook = tools(dotnet)?;
+ let hooks = match std::env::var_os("DOTNET_STARTUP_HOOKS") {
+ Some(theirs) => std::env::join_paths([hook.into_os_string(), theirs])?,
+ None => hook.into_os_string(),
+ };
+ cmd.env("DOTNET_STARTUP_HOOKS", hooks).env("FAST_ANYTHING_STOP_AFTER_MS", ((d * 1000.0) as u64).to_string());
+ }
let started = Instant::now();
- let out = output(
- app_command(dotnet, &dll, &run.args)
- .current_dir(&ctx.root)
+ let (out, stopped) = util::output_for(
+ cmd.current_dir(&ctx.root)
.env("DOTNET_EnableEventPipe", "1")
.env("DOTNET_EventPipeOutputPath", trace_dir.join("app-{pid}.nettrace"))
+ // write the trace as it goes, so a run that's stopped (or crashes) still leaves its samples
+ .env("DOTNET_EventPipeOutputStreaming", "1")
.env(
"DOTNET_EventPipeConfig",
"Microsoft-DotNETCore-SampleProfiler:0:5,Microsoft-Windows-DotNETRuntime:0x4c14fccbd:5",
@@ -279,9 +366,24 @@ pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String]) -> Result<Profile> {
.env(DISABLE_ENV, "1")
.stdin(Stdio::null()),
dotnet,
+ // in case the hook can't run (a trimmed app): close it from outside
+ duration.map(|d| Duration::from_secs_f64(d + 15.0)),
+ Duration::from_secs(10),
)?;
let wall = started.elapsed().as_secs_f64();
- ensure!(out.status.success(), "the app failed ({}):\n{}", out.status, tail(&combined(&out), 30));
+ ensure!(
+ stopped || out.status.success(),
+ "the app failed ({}):\n{}{}",
+ out.status,
+ tail(&combined(&out), 30),
+ if out.status.code() == Some(0xc000027bu32 as i32) {
+ "\n(0xc000027b is a stowed WinRT exception, usually XAML failing at startup: does the app start with dotnet run on its own?)"
+ } else if duration.is_none() {
+ "\n(a GUI or server that runs until it's closed: add --duration 30 to stop it after 30 seconds)"
+ } else {
+ ""
+ }
+ );
let stacks_path = ctx.fast.join("cs-stacks.json");
helper(ctx, dotnet, "trace", &trace_dir, &stacks_path)?;
let stacks: Vec<Stack> = serde_json::from_str(&fs::read_to_string(&stacks_path)?).context("reading the samples")?;
@@ -294,12 +396,20 @@ pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String]) -> Result<Profile> {
by_name.entry((m.class.as_str(), m.name.as_str())).or_insert(i);
}
let resolve = |f: &str| split_frame(f).and_then(|k| by_name.get(&k).copied());
- // threads that ran the app's own code; the runtime's idle threads don't count
+ // threads that ran the app's own code; the runtime's idle threads don't count, nor do samples of a thread
+ // that was waiting (a Main blocked on a task, a thread-pool worker with nothing to do)
let app_threads: HashSet<i64> =
stacks.iter().filter(|s| s.frames.iter().any(|f| resolve(f).is_some())).map(|s| s.thread).collect();
let (mut total, mut own, mut incl) = (0u64, HashMap::<usize, u64>::new(), HashMap::<usize, u64>::new());
- for s in stacks.iter().filter(|s| app_threads.contains(&s.thread)) {
+ let mut libraries = HashMap::<String, u64>::new();
+ for s in stacks.iter().filter(|s| app_threads.contains(&s.thread) && !idle(&s.frames)) {
total += s.count;
+ // library work that only code which can't be ported leads to (Main, async methods, I/O): porting won't
+ // touch it, so the ranking alone can't say where the time went
+ let ported_from = |f: &String| resolve(f).is_some_and(|i| methods[i].blockers.is_empty());
+ if resolve(&s.frames[0]).is_none() && !s.frames.iter().any(ported_from) {
+ *libraries.entry(library(&s.frames[0])).or_default() += s.count;
+ }
let mut seen = HashSet::new();
for (depth, f) in s.frames.iter().enumerate() {
let Some(i) = resolve(f) else { continue };
@@ -311,7 +421,41 @@ pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String]) -> Result<Profile> {
}
}
}
- ensure!(total > 0, "no samples landed in the app's code: does it run long enough (a second or more)?");
+ if total == 0 {
+ // say where the time went instead
+ let mut seen = HashMap::<String, u64>::new();
+ let busy: Vec<&Stack> = stacks.iter().filter(|s| !idle(&s.frames)).collect();
+ for s in &busy {
+ *seen.entry(library(&s.frames[0])).or_default() += s.count;
+ }
+ let all: u64 = busy.iter().map(|s| s.count).sum();
+ let mut seen: Vec<(String, u64)> = seen.into_iter().collect();
+ seen.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
+ let top: Vec<String> =
+ seen.iter().take(3).map(|(l, n)| format!("{l} {:.0}%", *n as f64 / all.max(1) as f64 * 100.0)).collect();
+ bail!(
+ "no samples landed in the app's own methods (top-level statements don't count: move the work into a method){}{}",
+ if duration.is_some() {
+ "; does its work start before it's stopped?"
+ } else {
+ "; does it run long enough (a second or more)?"
+ },
+ if top.is_empty() { String::new() } else { format!("\nThe time went to: {}", top.join(", ")) }
+ );
+ }
+ let mut notes = Vec::new();
+ let mut libs: Vec<(String, u64)> = libraries.into_iter().filter(|(l, _)| !l.is_empty()).collect();
+ libs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
+ let in_libs: u64 = libs.iter().map(|l| l.1).sum();
+ if in_libs * 2 >= total {
+ let top: Vec<String> =
+ libs.iter().take(3).map(|(l, n)| format!("{l} {:.0}%", *n as f64 / total as f64 * 100.0)).collect();
+ notes.push(format!(
+ "{:.0}% of the app's time is spent inside libraries ({}), called from code that can't move to Rust",
+ in_libs as f64 / total as f64 * 100.0,
+ top.join(", ")
+ ));
+ }
let mut keep: Vec<usize> = incl.keys().copied().collect();
let helpers: Vec<usize> = keep
.iter()
@@ -354,7 +498,7 @@ pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String]) -> Result<Profile> {
}
})
.collect();
- Ok(Profile { wall, base: ".".into(), functions })
+ Ok(Profile { wall, base: ".".into(), functions, notes })
}
// ------------------------------------------------------------------ editing the source
@@ -582,6 +726,16 @@ mod tests {
assert_eq!(plain_type("List<string?>?"), "List<string>");
assert_eq!(plain_type("System.Int32?[]?"), "System.Int32?[]");
assert_eq!(split_frame("Ns.Outer+Inner.Run(int32,class System.String)"), Some(("Ns.Outer+Inner", "Run")));
+ assert_eq!(split_frame("Ns.App+<RunAsync>d__3.MoveNext()"), Some(("Ns.App", "RunAsync")));
+ assert_eq!(split_frame("Ns.App+<>c.<Main>b__0_0(int32)"), Some(("Ns.App", "Main")));
+ assert_eq!(split_frame("Ns.App+<>c__DisplayClass2_0.<Load>b__1()"), Some(("Ns.App", "Load")));
+ assert_eq!(split_frame("Ns.App.<Main>g__Step|0_0()"), Some(("Ns.App", "Main")));
+ assert_eq!(split_frame("Ns.App+<>c.<<Main>$>b__0_0()").map(|f| f.0), Some("Ns.App"));
+ let frames = |v: &[&str]| v.iter().map(|f| f.to_string()).collect::<Vec<_>>();
+ assert!(idle(&frames(&["Interop+Kernel32.Foo()", "System.Threading.Monitor.Wait(class System.Object,int32)"])));
+ assert!(!idle(&frames(&["Ns.App.Run()", "Ns.App.Main()"])));
+ assert_eq!(library("SixLabors.ImageSharp.Formats.Webp.WebpEncoder.Encode(class X)"), "SixLabors.ImageSharp");
+ assert_eq!(library("System.String.Concat(string,string)"), "System");
let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
let r = DotnetRun::parse(&s(&["run", "-c", "Release", "--project", "app", "--", "x", "-y"])).unwrap();
assert_eq!(r.project.as_deref(), Some("app"));
@@ -589,6 +743,7 @@ mod tests {
assert_eq!(r.args, s(&["x", "-y"]));
assert!(DotnetRun::parse(&s(&["run", "app.cs"])).is_err());
assert!(DotnetRun::parse(&s(&["app.dll"])).is_err());
+ assert!(DotnetRun::parse(&s(&["test"])).unwrap_err().to_string().contains("testhost"));
assert!(is_csharp("C:\\Program Files\\dotnet\\dotnet.exe") && !is_csharp("dotnet-trace"));
}
}
diff --git a/src/csharp/Program.cs b/src/csharp/Program.cs
index 6b1d08e..968ffbf 100644
--- a/src/csharp/Program.cs
+++ b/src/csharp/Program.cs
@@ -1,6 +1,7 @@
// C# side of fast-anything's scan. The CLI runs it as
// FastAnythingTools describe <file list> <out.json> every method in the app's sources (Roslyn)
// FastAnythingTools trace <dir> <out.json> sampled stacks from the .nettrace files in dir
+// and loads it into the app as a startup hook to stop it after scan --duration.
// Not meant to be run by hand.
using System.Text;
using System.Text.Json;
@@ -26,6 +27,17 @@ static class Tools
}
}
+// Loaded into the app (DOTNET_STARTUP_HOOKS) when a scan has a --duration: ends the app cleanly once the time is
+// up, so the runtime finishes writing its trace. GUIs and servers don't exit on their own.
+public static class StartupHook
+{
+ public static void Initialize()
+ {
+ if (!int.TryParse(Environment.GetEnvironmentVariable("FAST_ANYTHING_STOP_AFTER_MS"), out var ms)) return;
+ new Thread(() => { Thread.Sleep(ms); Environment.Exit(0); }) { IsBackground = true, Name = "fast-anything stop" }.Start();
+ }
+}
+
static class Trace
{
public static object Run(string dir)
diff --git a/src/doctor.rs b/src/doctor.rs
index 231ab83..354aebe 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -63,7 +63,12 @@ struct Check {
pub fn run() -> Result<()> {
let python = version("python", &["--version"]).or_else(|| version("python3", &["--version"]));
let checks = [
- Check { name: "cargo", found: version("cargo", &["--version"]), need: "required", hint: "https://rustup.rs" },
+ Check {
+ name: "cargo",
+ found: version("cargo", &["--version"]),
+ need: "to port (scan works without it)",
+ hint: "https://rustup.rs",
+ },
Check { name: "python", found: python, need: "for Python apps (3.10+)", hint: "https://python.org" },
Check {
name: "node",
@@ -147,7 +152,7 @@ pub fn run() -> Result<()> {
None => ui::line(format!(" {} {:<8} {}", green("✓"), bold(c.name), dim(v))),
Some(why) => ui::line(format!(" {} {:<8} {} {}", red("✗"), bold(c.name), dim(v), why)),
},
- None if c.need == "required" => {
+ None if c.name == "cargo" => {
ui::line(format!(" {} {:<8} missing, {}: {}", red("✗"), bold(c.name), c.need, c.hint))
}
None => ui::line(format!(
@@ -158,12 +163,13 @@ pub fn run() -> Result<()> {
)),
}
}
- ensure!(usable(&checks[0]), "Rust 1.85 or newer is needed to build ports");
ensure!(
checks[1..12].iter().any(usable),
"install Python, Node.js (or Bun, Deno), Ruby, Java, Go, PHP, .NET, R or a C compiler"
);
- ui::ok("ready");
+ ui::ok("ready to scan");
+ ensure!(usable(&checks[0]), "Rust 1.85 or newer is needed to port, verify and enable");
+ ui::ok("ready to port");
Ok(())
}
diff --git a/src/golang.rs b/src/golang.rs
index eb6a181..7ed9fa6 100644
--- a/src/golang.rs
+++ b/src/golang.rs
@@ -334,7 +334,7 @@ pub fn profile(ctx: &Ctx, go: &str, args: &[String]) -> Result<Profile> {
functions.push(hotspot(ctx, f, flat, cum));
}
}
- Ok(Profile { wall, base: ".".into(), functions })
+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })
}
fn pkg_name(ctx: &Ctx, hs: &Hotspot) -> Result<String> {
diff --git a/src/hotspot.rs b/src/hotspot.rs
index 88e9e37..3ebe614 100644
--- a/src/hotspot.rs
+++ b/src/hotspot.rs
@@ -60,6 +60,23 @@ impl Hotspot {
pub fn worth_it(&self) -> bool {
self.portable() && self.covered_by.is_none() && self.share >= WORTH_IT
}
+
+ /// Why it isn't worth porting, if it isn't.
+ pub fn why_not(&self) -> Option<String> {
+ if let Some(b) = self.blockers.first() {
+ Some(b.clone())
+ } else if let Some(by) = &self.covered_by {
+ Some(format!("ported inside {by}"))
+ } else if self.share < WORTH_IT {
+ Some(format!(
+ "too small to matter ({:.1}% of the run, {:.0}% needed)",
+ self.share * 100.0,
+ WORTH_IT * 100.0
+ ))
+ } else {
+ None
+ }
+ }
}
/// Blockers about what a function does, not where it lives or what its signature looks like.
diff --git a/src/java.rs b/src/java.rs
index f8ce941..a737388 100644
--- a/src/java.rs
+++ b/src/java.rs
@@ -364,7 +364,7 @@ pub(crate) fn profile_with(
)
})
.collect();
- Ok(Profile { wall, base: ".".into(), functions })
+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })
}
// ------------------------------------------------------------------ editing the source
diff --git a/src/main.rs b/src/main.rs
index 59ae663..d1bd8a6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -67,6 +67,9 @@ enum Cmd {
},
/// Run your app under a profiler and rank what's worth porting
Scan {
+ /// Stop the app after this many seconds and rank what ran (C#: GUIs and servers that don't exit)
+ #[arg(long, value_name = "SECS")]
+ duration: Option<f64>,
/// How you run your app, after --
#[arg(last = true, required = true)]
command: Vec<String>,
@@ -152,8 +155,8 @@ fn run(cmd: Cmd, root: &Path) -> Result<()> {
Cmd::Go { agent, top, attempts, runs, samples, command } => {
pipeline::go(root, command, agent.as_deref(), top, attempts, runs, samples)
}
- Cmd::Scan { command } => {
- show::scan(&pipeline::scan(root, command)?);
+ Cmd::Scan { command, duration } => {
+ show::scan(&pipeline::scan(root, command, duration)?);
Ok(())
}
Cmd::Port { id, agent, attempts, samples } => {
diff --git a/src/mcp.rs b/src/mcp.rs
index e2a83fe..34dab80 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -23,7 +23,7 @@ fn tools() -> Value {
tool(
"fast_scan",
"Run the app under a profiler and rank functions by time share and portability to Rust.",
- json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "path": path }),
+ json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "duration": { "type": "number", "description": "C# only: stop the app after this many seconds (GUIs, servers)" }, "path": path }),
json!(["command"])
),
tool(
@@ -76,17 +76,17 @@ fn call(params: &Value) -> Result<Value> {
.as_array()
.map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
.unwrap_or_default();
- let scan = pipeline::scan(&root, command)?;
+ let scan = pipeline::scan(&root, command, args["duration"].as_f64())?;
let top: Vec<Value> = scan
.hotspots
.iter()
.take(10)
.map(|h| {
- json!({ "id": h.id, "share": h.share, "calls": h.ncalls, "worth_porting": h.worth_it(),
+ json!({ "id": h.id, "share": h.share, "calls": h.ncalls, "worth_porting": h.worth_it(), "why_not": h.why_not(),
"blockers": h.blockers, "warnings": h.warnings, "file": h.file, "line": h.line })
})
.collect();
- json!({ "wall_seconds": scan.wall, "hotspots": top })
+ json!({ "wall_seconds": scan.wall, "hotspots": top, "notes": scan.notes })
}
"fast_port" => {
let samples = args["samples"].as_u64().unwrap_or(500) as usize;
diff --git a/src/php.rs b/src/php.rs
index 2941232..2a05ff3 100644
--- a/src/php.rs
+++ b/src/php.rs
@@ -205,7 +205,7 @@ pub fn profile(ctx: &Ctx, php: &str, args: &[String]) -> Result<Profile> {
None => {}
}
}
- Ok(Profile { wall, base: ".".into(), functions })
+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })
}
fn name_const(hs: &Hotspot) -> &'static str {
diff --git a/src/pipeline.rs b/src/pipeline.rs
index 1cfb052..e0c2bdc 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -16,9 +16,11 @@ pub struct ScanOut {
pub command: Vec<String>,
pub wall: f64,
pub hotspots: Vec<Hotspot>,
+ pub notes: Vec<String>,
}
-pub fn scan(root: &Path, command: Vec<String>) -> Result<ScanOut> {
+/// `duration`: stop the app after that many seconds (a GUI or a server that doesn't exit on its own).
+pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<ScanOut> {
ensure!(
!command.is_empty(),
"put the command that runs your app after --, e.g. fast-anything scan -- python app.py"
@@ -33,9 +35,16 @@ pub fn scan(root: &Path, command: Vec<String>) -> Result<ScanOut> {
};
let lang = crate::cfamily::refine(Lang::detect(&command[0])?, &command[1..]);
let lang = crate::kotlin::refine(lang, &command[0], &ctx.root);
+ if let Some(d) = duration {
+ ensure!(lang == Lang::CSharp, "--duration works for C# apps only so far");
+ ensure!(d.is_finite() && d > 0.0, "--duration takes a number of seconds, e.g. --duration 30");
+ }
let exe = lang.resolve(&command[0], &ctx.root)?;
ui::step(format!("profiling {}", ui::bold(command.join(" "))));
- let profile = lang.profile(&ctx, &exe, &command[1..])?;
+ let profile = match duration {
+ Some(d) => crate::csharp::profile(&ctx, &exe, &command[1..], Some(d))?,
+ None => lang.profile(&ctx, &exe, &command[1..])?,
+ };
let hotspots = hotspot::rank(profile.functions, profile.wall);
ctx.state.command = command.clone();
ctx.state.lang = lang;
@@ -44,7 +53,7 @@ pub fn scan(root: &Path, command: Vec<String>) -> Result<ScanOut> {
ctx.state.wall = profile.wall;
ctx.state.hotspots = hotspots.clone();
ctx.save()?;
- Ok(ScanOut { command, wall: profile.wall, hotspots })
+ Ok(ScanOut { command, wall: profile.wall, hotspots, notes: profile.notes })
}
/// What an env runner (uv, poetry, ...) prints for a command run in the project.
@@ -504,7 +513,7 @@ pub fn go(
runs: usize,
samples: usize,
) -> Result<()> {
- let scanned = scan(root, command)?;
+ let scanned = scan(root, command, None)?;
show::scan(&scanned);
let picks: Vec<String> =
scanned.hotspots.iter().filter(|h| h.worth_it()).take(top.max(1)).map(|h| h.id.clone()).collect();
diff --git a/src/python/__pycache__/runner.cpython-315.pyc b/src/python/__pycache__/runner.cpython-315.pyc
deleted file mode 100644
index 39456f8..0000000
Binary files a/src/python/__pycache__/runner.cpython-315.pyc and /dev/null differ
diff --git a/src/show.rs b/src/show.rs
index b55ddac..3451e17 100644
--- a/src/show.rs
+++ b/src/show.rs
@@ -42,6 +42,9 @@ pub fn scan(s: &ScanOut) {
ui::line("");
if s.hotspots.is_empty() {
ui::line(" No functions from your own code showed up. Is the app doing its work in a library?");
+ for n in &s.notes {
+ ui::line(format!(" {}", yellow(format!("! {n}"))));
+ }
return;
}
ui::line(dim(format!(" # {} {:<16}{:>11} verdict", pad("function", 30), "time", "calls")));
@@ -71,6 +74,12 @@ pub fn scan(s: &ScanOut) {
}
}
ui::line("");
+ for n in &s.notes {
+ ui::line(format!(" {}", yellow(format!("! {n}"))));
+ }
+ if !s.notes.is_empty() {
+ ui::line("");
+ }
match s.hotspots.iter().find(|h| h.worth_it()) {
Some(h) => next(&format!("fast-anything port {}", h.id)),
None => {
diff --git a/src/util.rs b/src/util.rs
index ae505e3..3faf875 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -1,8 +1,10 @@
//! Small helpers: paths, processes, number formatting.
use anyhow::{Context, Result};
+use std::io::Read;
use std::path::{Component, Path, PathBuf};
-use std::process::{Command, Output};
+use std::process::{Command, Output, Stdio};
+use std::time::{Duration, Instant};
pub fn absolute(p: &Path) -> PathBuf {
std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf())
@@ -42,6 +44,61 @@ pub fn output(cmd: &mut Command, what: &str) -> Result<Output> {
cmd.output().with_context(|| format!("couldn't start {what} ({})", cmd.get_program().to_string_lossy()))
}
+/// Like [`output`], but stops the command once `limit` has passed: asks it to close first (WM_CLOSE on Windows,
+/// SIGTERM elsewhere), so it can shut down cleanly and write what it has, then ends it for good after `grace`.
+/// Also says whether it had to be stopped.
+pub fn output_for(cmd: &mut Command, what: &str, limit: Option<Duration>, grace: Duration) -> Result<(Output, bool)> {
+ let Some(limit) = limit else { return Ok((output(cmd, what)?, false)) };
+ let mut child = cmd
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .with_context(|| format!("couldn't start {what} ({})", cmd.get_program().to_string_lossy()))?;
+ fn drain<R: Read + Send + 'static>(r: Option<R>) -> std::thread::JoinHandle<Vec<u8>> {
+ std::thread::spawn(move || {
+ let mut buf = Vec::new();
+ if let Some(mut r) = r {
+ let _ = r.read_to_end(&mut buf);
+ }
+ buf
+ })
+ }
+ let (stdout, stderr) = (drain(child.stdout.take()), drain(child.stderr.take()));
+ let started = Instant::now();
+ let mut asked: Option<Instant> = None;
+ let status = loop {
+ if let Some(status) = child.try_wait()? {
+ break status;
+ }
+ match asked {
+ None if started.elapsed() >= limit => {
+ asked = Some(if ask_to_close(child.id()) { Instant::now() } else { Instant::now() - grace });
+ }
+ Some(at) if at.elapsed() >= grace => {
+ let _ = child.kill();
+ break child.wait()?;
+ }
+ _ => {}
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ };
+ let out = Output { status, stdout: stdout.join().unwrap_or_default(), stderr: stderr.join().unwrap_or_default() };
+ Ok((out, asked.is_some()))
+}
+
+/// Ask a process to close the way a user would. False if it can't be asked (a console app on Windows).
+fn ask_to_close(pid: u32) -> bool {
+ let (program, args) = if cfg!(windows) { ("taskkill", ["/PID"]) } else { ("kill", ["-TERM"]) };
+ Command::new(program)
+ .args(args)
+ .arg(pid.to_string())
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .is_ok_and(|s| s.success())
+}
+
pub fn combined(out: &Output) -> String {
format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr))
}