From c06ab883f76ddb4fad4e5f3e6ff1a80a1d2b99fe Mon Sep 17 00:00:00 2001 From: wuyangfan Date: Mon, 25 May 2026 15:17:27 +0800 Subject: [PATCH] fix(mach): detect shebang scripts before Mach-O parsing Shell scripts on macOS were reported as opaque "Invalid magic number" errors (e.g. 0x23212f75 for `#!/u`). Reject inputs starting with `#!` with a clear Malformed error instead. Fixes #494 Co-authored-by: Cursor --- src/mach/mod.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/mach/mod.rs b/src/mach/mod.rs index 034df02d..301a8eed 100644 --- a/src/mach/mod.rs +++ b/src/mach/mod.rs @@ -549,6 +549,11 @@ impl<'a> Mach<'a> { let error = error::Error::Malformed("size is smaller than a magical number".into()); return Err(error); } + if bytes.starts_with(b"#!") { + return Err(error::Error::Malformed( + "input appears to be a script with a shebang (#!), not a Mach-O binary".into(), + )); + } let magic = peek(&bytes, 0)?; match magic { fat::FAT_MAGIC => { @@ -567,6 +572,7 @@ impl<'a> Mach<'a> { #[cfg(test)] mod test { use super::{Mach, SingleArch}; + use crate::error::Error; #[test] fn parse_multi_arch_of_macho_binaries() { @@ -597,6 +603,18 @@ mod test { } } + #[test] + fn parse_rejects_shebang_scripts() { + let bytes = b"#!/usr/bin/env bash\necho hello\n"; + let err = Mach::parse(bytes).unwrap_err(); + match err { + Error::Malformed(msg) => { + assert!(msg.contains("shebang")); + } + other => panic!("expected Malformed shebang error, got {other:?}"), + } + } + #[test] fn parse_multi_arch_of_archives() { // Created with: