From 7caa3dd4ce93cdfad1feff837b3dbc87d25b5e37 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Wed, 18 Nov 2026 18:20:38 +0000 Subject: [PATCH] feat(iconv): code pages via encoding_rs (iconv_charsets feature) Adds windows-125x, iso-8859-x, koi8, macintosh and the CJK sets from the WHATWG tables, behind a default-on `iconv_charsets` feature (absent from the browser wasm package, like tzdata). Built-in names win; WHATWG labels that alias latin1/ascii to windows-1252 resolve to the real charsets. Errors keep exact byte positions; unmappable chars never become NCRs. Closes #2935 --- Cargo.lock | 1 + Cargo.toml | 1 + crates/bashkit-capi/Cargo.toml | 2 +- crates/bashkit-cli/Cargo.toml | 2 +- crates/bashkit/Cargo.toml | 12 +- crates/bashkit/src/builtins/iconv.rs | 430 +++++++++++++++++- .../tests/integration/byte_stream_tests.rs | 26 ++ knowledge/log.md | 1 + knowledge/operations/dependencies.md | 6 + knowledge/operations/limitations.md | 2 +- knowledge/runtimes/browser-package.md | 4 +- knowledge/security/threat-model.md | 2 +- 12 files changed, 472 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3c321669f..8875bfee0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -453,6 +453,7 @@ dependencies = [ "clap", "criterion", "ed25519-dalek", + "encoding_rs", "fail", "fancy-regex", "fetchkit", diff --git a/Cargo.toml b/Cargo.toml index f83d2cee4..ce448e728 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,6 +72,7 @@ fancy-regex = "0.20" # embedders. Re-enabled by the bashkit `wasm_js` feature for the JS packages. chrono = { version = "0.4", default-features = false, features = ["std", "clock"] } chrono-tz = "0.10" +encoding_rs = "0.8" # In-process terminal screen model (terminal feature) vt100 = "0.18" diff --git a/crates/bashkit-capi/Cargo.toml b/crates/bashkit-capi/Cargo.toml index 256c5dff0..5c1d57b22 100644 --- a/crates/bashkit-capi/Cargo.toml +++ b/crates/bashkit-capi/Cargo.toml @@ -17,7 +17,7 @@ crate-type = ["cdylib", "rlib"] # `tzdata` is listed explicitly: the C ABI is a general-purpose embedding # surface, so `date` must keep honouring named `TZ=` zones the way it did # before that became a feature. -bashkit = { path = "../bashkit", default-features = false, features = ["git", "jq", "tzdata", "realfs", "python", "typescript"] } +bashkit = { path = "../bashkit", default-features = false, features = ["git", "jq", "tzdata", "iconv_charsets", "realfs", "python", "typescript"] } serde = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true } diff --git a/crates/bashkit-cli/Cargo.toml b/crates/bashkit-cli/Cargo.toml index 2e6a009bf..b7d8fce57 100644 --- a/crates/bashkit-cli/Cargo.toml +++ b/crates/bashkit-cli/Cargo.toml @@ -39,7 +39,7 @@ interactive = ["dep:rustyline", "dep:terminal_size", "dep:signal-hook"] # `tzdata` is listed explicitly: an interactive shell must keep honouring # named `TZ=` zones in `date`, which stopped being implied when chrono-tz # moved behind a feature. -bashkit = { path = "../bashkit", version = "0.21.0", default-features = false, features = ["http_client", "ring", "git", "jq", "tzdata"] } +bashkit = { path = "../bashkit", version = "0.21.0", default-features = false, features = ["http_client", "ring", "git", "jq", "tzdata", "iconv_charsets"] } tokio = { workspace = true, features = ["macros", "net", "rt", "rt-multi-thread", "time", "io-std"] } clap.workspace = true anyhow.workspace = true diff --git a/crates/bashkit/Cargo.toml b/crates/bashkit/Cargo.toml index 0a4ba01cd..2e964d206 100644 --- a/crates/bashkit/Cargo.toml +++ b/crates/bashkit/Cargo.toml @@ -40,6 +40,7 @@ fancy-regex = { workspace = true } # Date/Time chrono = { workspace = true } chrono-tz = { workspace = true, optional = true } +encoding_rs = { workspace = true, optional = true } vt100 = { workspace = true, optional = true } # HTTP client (for curl/wget) - optional, enabled with http_client feature @@ -153,7 +154,7 @@ turso_core = { workspace = true, optional = true } branches = { workspace = true, optional = true } [features] -default = ["bash_tool", "ring", "tzdata"] +default = ["bash_tool", "ring", "tzdata", "iconv_charsets"] # Named IANA timezone support for the `date` builtin's `TZ=` handling, via the # chrono-tz database. On by default. # @@ -170,6 +171,15 @@ default = ["bash_tool", "ring", "tzdata"] # is still never consulted. `TZ=UTC`, unset, empty, and path-style values are # unaffected. tzdata = ["dep:chrono-tz"] +# Code pages for the `iconv` builtin beyond UTF-8/ASCII/Latin-1/UTF-16: +# windows-125x, iso-8859-x, koi8, macintosh and the CJK sets, from the WHATWG +# Encoding Standard tables in encoding_rs. On by default. +# +# Important decision: a feature for the same reason as `tzdata`: the CJK +# tables are a few hundred KB of static data that the slim browser wasm +# package should not carry. Without it `iconv` names other charsets as +# unsupported and exits 1; the built-in charsets are unaffected. +iconv_charsets = ["dep:encoding_rs"] # Enable the LLM-facing `BashTool` wrapper: the `Tool` trait, `ToolExecution`, # OpenAI tool-definition/JSON-schema helpers, and the `tower::Service` bridge. # On by default. Disable with `--no-default-features` to compile just the diff --git a/crates/bashkit/src/builtins/iconv.rs b/crates/bashkit/src/builtins/iconv.rs index 492f1d8cd..495e68c31 100644 --- a/crates/bashkit/src/builtins/iconv.rs +++ b/crates/bashkit/src/builtins/iconv.rs @@ -56,6 +56,9 @@ enum Charset { Utf16, Utf16Le, Utf16Be, + /// Any other WHATWG charset (cp1252, iso-8859-15, gbk, ...), via encoding_rs. + #[cfg(feature = "iconv_charsets")] + Other(&'static encoding_rs::Encoding), } /// Look up a charset name, ignoring case, `-` and `_`. @@ -72,10 +75,131 @@ fn lookup_charset(name: &str) -> Option { "utf16" => Charset::Utf16, "utf16le" => Charset::Utf16Le, "utf16be" => Charset::Utf16Be, + #[cfg(feature = "iconv_charsets")] + _ => return charsets::lookup(name, &key), + #[cfg(not(feature = "iconv_charsets"))] _ => return None, }) } +/// Code pages beyond the built-in set, from the WHATWG Encoding Standard +/// tables in `encoding_rs`. +/// +/// Decisions: +/// - Built-in names win. WHATWG maps `latin1`, `iso-8859-1` and `ascii` to +/// windows-1252 (a browser rule); iconv users mean the real charsets, so +/// any windows-1252 label not spelled 1252 resolves to Latin-1 or ASCII. +/// - UTF-16 labels resolve to the built-in UTF-16 (encoding_rs cannot encode +/// UTF-16); the WHATWG `replacement` encoding is refused. +/// - Encoding never uses HTML numeric references: unmappable characters are +/// errors, or dropped under `-c`, like GNU. +/// - WHATWG tables are not glibc tables: windows-1252 decodes the five +/// unassigned bytes 0x81/0x8D/0x8F/0x90/0x9D to C1 controls instead of +/// failing (L-ICONV-001). +#[cfg(feature = "iconv_charsets")] +mod charsets { + use super::Charset; + use encoding_rs::Encoding; + + /// GNU/glibc spellings that are not WHATWG labels (key: lowercase, + /// `-`/`_` removed). + const ALIASES: &[(&str, &str)] = &[ + ("latin2", "iso-8859-2"), + ("latin3", "iso-8859-3"), + ("latin4", "iso-8859-4"), + ("latin5", "windows-1254"), + ("latin6", "iso-8859-10"), + ("latin7", "iso-8859-13"), + ("latin8", "iso-8859-14"), + ("latin9", "iso-8859-15"), + ("latin10", "iso-8859-16"), + ("cyrillic", "iso-8859-5"), + ("arabic", "iso-8859-6"), + ("greek", "iso-8859-7"), + ("hebrew", "iso-8859-8"), + ("cp866", "ibm866"), + ("cp874", "windows-874"), + ("cp932", "shift_jis"), + ("ms932", "shift_jis"), + ("cp936", "gbk"), + ("cp949", "euc-kr"), + ("cp950", "big5"), + ("eucjp", "euc-jp"), + ("euckr", "euc-kr"), + ("eucchinese", "gbk"), + ("koi8r", "koi8-r"), + ("koi8u", "koi8-u"), + ("mac", "macintosh"), + ("macroman", "macintosh"), + ("maccyrillic", "x-mac-cyrillic"), + ]; + + pub(super) fn lookup(name: &str, key: &str) -> Option { + let encoding = Encoding::for_label(name.as_bytes()).or_else(|| { + let (_, label) = ALIASES.iter().find(|(alias, _)| *alias == key)?; + Encoding::for_label(label.as_bytes()) + })?; + Some( + if encoding == encoding_rs::WINDOWS_1252 && !key.contains("1252") { + if key.contains("ascii") || key.contains("646") || key.contains("x3.4") { + Charset::Ascii + } else { + Charset::Latin1 + } + } else if encoding == encoding_rs::UTF_8 { + Charset::Utf8 + } else if encoding == encoding_rs::UTF_16LE { + Charset::Utf16Le + } else if encoding == encoding_rs::UTF_16BE { + Charset::Utf16Be + } else if encoding == encoding_rs::REPLACEMENT { + return None; + } else { + Charset::Other(encoding) + }, + ) + } + + /// Canonical names listed by `iconv -l`. + pub(super) const NAMES: &[&str] = &[ + "BIG5", + "EUC-JP", + "EUC-KR", + "GB18030", + "GBK", + "IBM866", + "ISO-2022-JP", + "ISO-8859-2", + "ISO-8859-3", + "ISO-8859-4", + "ISO-8859-5", + "ISO-8859-6", + "ISO-8859-7", + "ISO-8859-8", + "ISO-8859-8-I", + "ISO-8859-10", + "ISO-8859-13", + "ISO-8859-14", + "ISO-8859-15", + "ISO-8859-16", + "KOI8-R", + "KOI8-U", + "MACINTOSH", + "SHIFT_JIS", + "WINDOWS-874", + "WINDOWS-1250", + "WINDOWS-1251", + "WINDOWS-1252", + "WINDOWS-1253", + "WINDOWS-1254", + "WINDOWS-1255", + "WINDOWS-1256", + "WINDOWS-1257", + "WINDOWS-1258", + "X-MAC-CYRILLIC", + ]; +} + /// A parsed encoding argument like `ASCII//TRANSLIT//IGNORE`. struct EncodingSpec { charset: Charset, @@ -245,6 +369,9 @@ fn decode_one(input: &[u8], pos: usize, charset: Charset, big_endian: bool) -> ( }, } } + // Decoded by `Converter::convert_other`, which keeps decoder state. + #[cfg(feature = "iconv_charsets")] + Charset::Other(_) => (Decoded::Invalid, rest.len()), } } @@ -259,9 +386,12 @@ fn first_char(s: &str) -> (Decoded, usize) { fn encode_one( ch: char, charset: Charset, + encoder: &mut Option, out: &mut BudgetedBytes, ) -> std::result::Result { let mut buf = [0u8; 4]; + #[cfg(not(feature = "iconv_charsets"))] + let _ = encoder; match charset { Charset::Utf8 => out.try_extend_from_slice(ch.encode_utf8(&mut buf).as_bytes())?, Charset::Ascii if ch.is_ascii() => out.try_push(ch as u8)?, @@ -278,10 +408,28 @@ fn encode_one( out.try_extend_from_slice(&bytes)?; } } + #[cfg(feature = "iconv_charsets")] + Charset::Other(encoding) => { + let encoder = encoder.get_or_insert_with(|| encoding.new_encoder()); + let mut tmp = [0u8; 16]; + let (result, _, written) = encoder.encode_from_utf8_without_replacement( + ch.encode_utf8(&mut buf), + &mut tmp, + false, + ); + // Stateful encoders (ISO-2022-JP) may emit an escape first. + out.try_extend_from_slice(&tmp[..written])?; + return Ok(result == encoding_rs::EncoderResult::InputEmpty); + } } Ok(true) } +#[cfg(feature = "iconv_charsets")] +type CharsetEncoder = encoding_rs::Encoder; +#[cfg(not(feature = "iconv_charsets"))] +type CharsetEncoder = (); + /// Why a conversion stopped early. enum ConvertError { Illegal(usize), @@ -308,6 +456,8 @@ struct Converter { /// Set when `skip` dropped anything (exit status 1). skipped: bool, bom_written: bool, + /// Encoder state for `Charset::Other` targets, kept across files. + encoder: Option, } impl Converter { @@ -337,16 +487,16 @@ impl Converter { if let Some(budget) = budget { budget.consume_work(input.len() as u64)?; } + #[cfg(feature = "iconv_charsets")] + if let Charset::Other(encoding) = self.from { + return self.convert_other(encoding, input, out); + } while pos < input.len() { let (decoded, len) = decode_one(input, pos, self.from, big_endian); match decoded { Decoded::Char(ch) => { - if !self.emit(ch, out)? { - if self.skip { - self.skipped = true; - } else { - return Ok(Err(ConvertError::Illegal(pos))); - } + if let Err(e) = self.take(ch, pos, out)? { + return Ok(Err(e)); } } Decoded::Invalid if self.skip => self.skipped = true, @@ -360,13 +510,93 @@ impl Converter { Ok(Ok(())) } + /// Write one decoded char that started at input byte `pos`. + fn take( + &mut self, + ch: char, + pos: usize, + out: &mut BudgetedBytes, + ) -> Result> { + if !self.emit(ch, out)? { + if self.skip { + self.skipped = true; + } else { + return Ok(Err(ConvertError::Illegal(pos))); + } + } + Ok(Ok(())) + } + + /// Decode with encoding_rs. Bytes are fed one at a time so every char + /// and every malformed sequence gets its exact input position. + #[cfg(feature = "iconv_charsets")] + fn convert_other( + &mut self, + encoding: &'static encoding_rs::Encoding, + input: &[u8], + out: &mut BudgetedBytes, + ) -> Result> { + use encoding_rs::DecoderResult; + let mut decoder = encoding.new_decoder_without_bom_handling(); + let mut buf = [0u8; 64]; + let mut char_start = 0; + for i in 0..=input.len() { + let last = i == input.len(); + let mut src: &[u8] = if last { &[] } else { &input[i..=i] }; + loop { + let (result, read, written) = + decoder.decode_to_utf8_without_replacement(src, &mut buf, last); + src = &src[read..]; + // Input bytes the decoder has taken so far. + let consumed = i + usize::from(!last) - src.len(); + // decode_to_utf8 writes whole UTF-8 chars only. + let text = std::str::from_utf8(&buf[..written]).unwrap_or_default(); + for ch in text.chars() { + if let Err(e) = self.take(ch, char_start, out)? { + return Ok(Err(e)); + } + } + if written > 0 { + char_start = consumed; + } + match result { + DecoderResult::InputEmpty => break, + DecoderResult::OutputFull => continue, + DecoderResult::Malformed(_, _) if self.skip => self.skipped = true, + DecoderResult::Malformed(_, _) if last => { + return Ok(Err(ConvertError::Incomplete)); + } + DecoderResult::Malformed(bad, after) => { + let pos = consumed.saturating_sub(usize::from(bad) + usize::from(after)); + return Ok(Err(ConvertError::Illegal(pos))); + } + } + char_start = consumed; + } + } + Ok(Ok(())) + } + + /// Flush a stateful target encoder (ISO-2022-JP returns to ASCII). + fn finish(&mut self, out: &mut BudgetedBytes) -> Result<()> { + #[cfg(feature = "iconv_charsets")] + if let Some(encoder) = self.encoder.as_mut() { + let mut tmp = [0u8; 16]; + let (_, _, written) = encoder.encode_from_utf8_without_replacement("", &mut tmp, true); + out.try_extend_from_slice(&tmp[..written])?; + } + #[cfg(not(feature = "iconv_charsets"))] + let _ = out; + Ok(()) + } + /// Encode `ch`, transliterating when asked. False when it cannot be written. fn emit( - &self, + &mut self, ch: char, out: &mut BudgetedBytes, ) -> std::result::Result { - if encode_one(ch, self.to, out)? { + if encode_one(ch, self.to, &mut self.encoder, out)? { return Ok(true); } if !self.translit { @@ -376,14 +606,14 @@ impl Converter { if let Some(rep) = transliterate(ch) { let mut ok = true; for c in rep.chars() { - ok &= encode_one(c, self.to, out)?; + ok &= encode_one(c, self.to, &mut self.encoder, out)?; } if ok { return Ok(true); } out.truncate(mark); } - encode_one('?', self.to, out) + encode_one('?', self.to, &mut self.encoder, out) } } @@ -471,7 +701,10 @@ impl Builtin for Iconv { if list { let mut out = String::new(); - for enc in SUPPORTED_ENCODINGS { + let names = SUPPORTED_ENCODINGS.iter(); + #[cfg(feature = "iconv_charsets")] + let names = names.chain(charsets::NAMES.iter()); + for enc in names { out.push_str(enc); out.push('\n'); } @@ -519,6 +752,7 @@ impl Builtin for Iconv { skip: omit_invalid || to.ignore, skipped: false, bom_written: false, + encoder: None, }; let mut failure: Option = None; @@ -543,6 +777,9 @@ impl Builtin for Iconv { break; } } + if failure.is_none() { + converter.finish(&mut out)?; + } let (bytes, _lease) = out.into_parts(); let exit_code = i32::from(failure.is_some() || converter.skipped); @@ -1039,4 +1276,175 @@ mod tests { } } } + + // --- code pages (iconv_charsets) --- + + #[cfg(feature = "iconv_charsets")] + mod charsets { + use super::*; + + #[tokio::test] + async fn cp1252_export_to_utf8() { + // "Köln – 5€" from an Excel CSV export (cp1252). + let fs = fs_with("/e.csv", b"K\xf6ln \x96 5\x80\n").await; + let r = run_bytes(&["-f", "cp1252", "-t", "utf-8", "/e.csv"], None, fs).await; + assert_eq!(r.exit_code, 0); + assert_eq!(r.stdout, "Köln – 5€\n"); + } + + #[tokio::test] + async fn cp1250_and_iso_8859_15() { + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes( + &["-f", "CP1250", "-t", "UTF-8"], + Some(b"\x8a\xe8"), + fs.clone(), + ) + .await; + assert_eq!(r.stdout, "Šč"); + let r = run_bytes( + &["-f", "ISO-8859-15", "-t", "UTF-8"], + Some(b"\xa4"), + fs.clone(), + ) + .await; + assert_eq!(r.stdout, "€"); + let r = run_bytes(&["-f", "latin9", "-t", "UTF-8"], Some(b"\xa4"), fs).await; + assert_eq!(r.stdout, "€"); + } + + #[tokio::test] + async fn utf8_to_code_page_bytes() { + let r = run(&["-f", "utf-8", "-t", "windows-1250"], Some("Šč")).await; + assert_eq!(r.exit_code, 0); + assert_eq!(r.stdout.as_bytes(), b"\x8a\xe8"); + let r = run(&["-f", "utf-8", "-t", "cp1252"], Some("5€")).await; + assert_eq!(r.stdout.as_bytes(), b"5\x80"); + } + + #[tokio::test] + async fn latin1_and_ascii_are_not_windows_1252() { + // WHATWG would read 0x80 as € under these labels; iconv must not. + let fs = Arc::new(InMemoryFs::new()); + let r = run_bytes( + &["-f", "ISO_8859-1:1987", "-t", "utf-8"], + Some(b"\x80"), + fs.clone(), + ) + .await; + assert_eq!(r.stdout, "\u{80}"); + let r = run_bytes(&["-f", "csASCII", "-t", "utf-8"], Some(b"\x80"), fs).await; + assert_eq!(r.exit_code, 1); + } + + #[tokio::test] + async fn multibyte_charsets_round_trip() { + for (name, text) in [ + ("shift_jis", "日本語テキスト"), + ("euc-jp", "日本語"), + ("gbk", "中文"), + ("gb18030", "中文😀"), + ("big5", "中文"), + ("euc-kr", "한국어"), + ("iso-2022-jp", "日本 abc"), + ("koi8-r", "Привет"), + ] { + let enc = run(&["-f", "utf-8", "-t", name], Some(text)).await; + assert_eq!(enc.exit_code, 0, "{name}"); + let fs = Arc::new(InMemoryFs::new()); + let dec = run_bytes( + &["-f", name, "-t", "utf-8"], + Some(enc.stdout.as_bytes()), + fs, + ) + .await; + assert_eq!(dec.exit_code, 0, "{name}"); + assert_eq!(dec.stdout, text, "{name}"); + } + } + + #[tokio::test] + async fn unmappable_char_reports_position_without_ncr() { + let r = run(&["-f", "utf-8", "-t", "cp1252"], Some("aЖb")).await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "a"); + assert!(r.stderr.contains("position 1")); + let r = run(&["-c", "-f", "utf-8", "-t", "cp1252"], Some("aЖb")).await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "ab"); + let r = run(&["-f", "utf-8", "-t", "cp1252//TRANSLIT"], Some("aЖ€")).await; + assert_eq!(r.stdout.as_bytes(), b"a?\x80"); + } + + #[tokio::test] + async fn malformed_multibyte_input_reports_position() { + let fs = Arc::new(InMemoryFs::new()); + // 0x82 0xA0 is a valid Shift_JIS pair; a space is never a trail byte. + let r = run_bytes( + &["-f", "shift_jis", "-t", "utf-8"], + Some(b"ab\x82\xa0\x82 "), + fs.clone(), + ) + .await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "abあ"); + assert!(r.stderr.contains("position 4"), "{}", r.stderr.text_lossy()); + let r = run_bytes( + &["-c", "-f", "shift_jis", "-t", "utf-8"], + Some(b"ab\x82 "), + fs.clone(), + ) + .await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "ab "); + // Lead byte at end of input. + let r = run_bytes(&["-f", "gbk", "-t", "utf-8"], Some(b"a\x81"), fs).await; + assert_eq!(r.exit_code, 1); + assert_eq!(r.stdout, "a"); + assert!(r.stderr.contains("incomplete character")); + } + + #[tokio::test] + async fn list_includes_code_pages() { + let r = run(&["-l"], None).await; + for name in charsets_names() { + assert!(r.stdout.contains(name), "{name}"); + let spec = parse_encoding_spec(name); + assert!(spec.is_some(), "{name} must resolve"); + } + } + + fn charsets_names() -> &'static [&'static str] { + super::super::charsets::NAMES + } + + #[tokio::test] + async fn replacement_encoding_is_refused() { + let r = run(&["-f", "csiso2022kr", "-t", "utf-8"], Some("x")).await; + assert_eq!(r.exit_code, 1); + assert!(r.stderr.contains("unsupported encoding")); + } + + #[tokio::test] + async fn arbitrary_bytes_never_panic_in_code_pages() { + let fs = Arc::new(InMemoryFs::new()); + let all: Vec = (0u8..=255).collect(); + let mut inputs: Vec> = vec![all.clone()]; + inputs.extend(all.chunks(3).map(<[u8]>::to_vec)); + inputs.extend((0u8..=255).map(|b| vec![b, b'x'])); + for name in charsets_names() { + for input in &inputs { + for flags in [&["-c"][..], &[][..]] { + let mut args = flags.to_vec(); + args.extend(["-f", name, "-t", "utf-16"]); + let r = run_bytes(&args, Some(input), fs.clone()).await; + // Round-trip back must also hold up. + let mut back = flags.to_vec(); + back.extend(["-f", "utf-16", "-t", name]); + let _ = run_bytes(&back, Some(r.stdout.as_bytes()), fs.clone()).await; + } + } + } + } + } } diff --git a/crates/bashkit/tests/integration/byte_stream_tests.rs b/crates/bashkit/tests/integration/byte_stream_tests.rs index adda69fc8..6d93e8fab 100644 --- a/crates/bashkit/tests/integration/byte_stream_tests.rs +++ b/crates/bashkit/tests/integration/byte_stream_tests.rs @@ -215,3 +215,29 @@ async fn iconv_matches_real_iconv_byte_for_byte() { ); } } + +#[cfg(feature = "iconv_charsets")] +#[tokio::test] +async fn iconv_code_pages_match_real_iconv() { + if Command::new("iconv").arg("-l").output().is_err() { + return; + } + for script in [ + "printf 'K\\366ln \\226 5\\200\\n' | iconv -f cp1252 -t utf-8", + "printf '\\212\\350\\n' | iconv -f CP1250 -t UTF-8", + "printf '\\305\\240\\304\\215 \\342\\202\\254\\n' | iconv -f utf-8 -t windows-1250", + "printf '\\244\\n' | iconv -f ISO-8859-15 -t UTF-8", + "printf '\\344\\270\\255\\346\\226\\207\\n' | iconv -f utf-8 -t gbk", + "printf '\\344\\270\\255\\346\\226\\207\\n' | iconv -f utf-8 -t shift_jis | iconv -f shift_jis -t utf-8", + ] { + let expected = Command::new("bash").args(["-c", script]).output().unwrap(); + let mut bash = Bash::new(); + let actual = bash.exec(script).await.unwrap(); + assert_eq!(actual.stdout.as_bytes(), expected.stdout, "{script}"); + assert_eq!( + actual.exit_code, + expected.status.code().unwrap(), + "{script}" + ); + } +} diff --git a/knowledge/log.md b/knowledge/log.md index e2ae0153d..63a5fe118 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,7 @@ ## 2026-11-18 +* **iconv code pages** (issue #2935): new default feature `iconv_charsets` adds `encoding_rs` (already in the lockfile through markkit) for windows-125x, iso-8859-x, koi8, macintosh and the CJK sets. Built-in names win, and any WHATWG windows-1252 label not spelled 1252 resolves to real Latin-1/ASCII, because WHATWG maps `latin1`/`ascii` to windows-1252. Decoding feeds encoding_rs one byte at a time so errors keep exact byte positions; encoding uses the no-replacement API, so unmappable characters are errors or `-c` drops, never `&#NNN;`. Listed by `bashkit-cli`/`bashkit-capi`, absent from `bashkit-wasm` like `tzdata`. See [Dependency Policy](operations/dependencies.md), L-ICONV-001. * **iconv writes real bytes; `-o`, `-c`, `//IGNORE`** (issue #2935): `iconv` built its output as a `String`, so `-t latin1` wrote UTF-8 again (double-encoded `Köln` could not be repaired) and `-t utf-16` went through a lossy decode. Conversion now runs char by char from input bytes to output bytes, with GNU positions in errors and the converted prefix on stdout when it stops. `UTF-16LE`/`UTF-16BE` write no BOM (`utf-16le` was an alias of the BOM form). `-o FILE` writes only after a full conversion, so `-o in.csv in.csv` with a wrong `-f` leaves the file intact. `-c`/`//IGNORE` drop bad input and unconvertible characters and exit 1. Output growth is charged to the execution budget. See [Limitations](operations/limitations.md) L-ICONV-001. * **Windows `/dev/stderr` redirects hit the VFS (#2933), and four more host-separator joins**: `dev_fd_alias` re-normalized the already-clean redirect target with `PathBuf::push`, which joins with `\` on Windows, so `/dev\stderr` missed the string match and `echo x > /dev/stderr` wrote a VFS file. It now uses the shared `normalize_path`. A clippy trial run with the join methods banned found the rest of the class: `PosixFs::mkdir -p` parent checks (backend saw `/a\b`), `cd x/..`, `readlink -f`/`realpath` prefix probes, and `OverlayFs` upper-dir counting, all now `vfs_join`. Second sweep after #2425, so the fix is a guard, not a sweep: `crates/bashkit/clippy.toml` bans `Path::join`/`PathBuf::push`/`set_file_name`/`with_file_name` with scoped allows for host-path code; `testing::CheckedFs` records paths a filesystem receives; the Windows CI job now runs the device-path and separator integration tests. Fuzzing could not have found it: Linux's separator is `/`. See [Virtual Filesystem](foundations/vfs.md). diff --git a/knowledge/operations/dependencies.md b/knowledge/operations/dependencies.md index 2dabd4b36..ab8d35331 100644 --- a/knowledge/operations/dependencies.md +++ b/knowledge/operations/dependencies.md @@ -57,6 +57,12 @@ lives there, next to the pin, so it cannot drift away from what it explains. - **`chrono-tz` behind the `tzdata` feature** (on by default). Worth 911 KB of the browser wasm binary. See [Gate rather than reimplement](#gate-rather-than-reimplement). +- **`encoding_rs` behind the `iconv_charsets` feature** (on by default, listed + by `bashkit-cli` and `bashkit-capi`, absent from `bashkit-wasm`). Gives + `iconv` the WHATWG code pages (windows-125x, iso-8859-x, koi8, CJK). + `for_label` reaches every table, so LTO keeps them all; same gate-don't- + reimplement reasoning as `tzdata`. Without it, other charsets are refused + with exit 1. ## Monty forks diff --git a/knowledge/operations/limitations.md b/knowledge/operations/limitations.md index 9a7e5c373..be37c86c3 100644 --- a/knowledge/operations/limitations.md +++ b/knowledge/operations/limitations.md @@ -227,7 +227,7 @@ pass in CI); only divergences and boundaries are recorded here. | L-OD-001 | od | Floating-point types (`-t f`, `-e`, `-f`, `-F`) are refused with an error; `-S`/`--strings` and `--traditional` are accepted but ignored | `test_od_float_rejected` | | L-FOLD-001 | fold | Every character counts one column (no East Asian wide-char widths); `-b` counts UTF-8 bytes | `fold.rs` | | L-STR-001 | strings | Accepts dash-prefixed filenames (e.g. `-data.bin`), so only a lone unknown short option (`-Q`) is rejected as invalid; GNU rejects `-data.bin` too | `strings.rs` | -| L-ICONV-001 | iconv | Charsets: UTF-8, ASCII, Latin-1, UTF-16 (BOM, LE default), UTF-16LE, UTF-16BE. `-c`/`//IGNORE` exit 1 when anything was dropped (POSIX, GNU libiconv); glibc 2.39 exits 0 when only unconvertible characters were dropped. `-c` also drops a sequence truncated at end of input, where glibc still errors. `-c -o FILE` writes the converted rest (dropping was requested); without `-c`, `-o` never writes after an error. `-s` is accepted and, like glibc, keeps error messages. `//TRANSLIT` uses a built-in Latin/punctuation table, unknown characters become `?` | `iconv.rs` tests | +| L-ICONV-001 | iconv | Charsets: UTF-8, ASCII, Latin-1, UTF-16 (BOM, LE default), UTF-16LE, UTF-16BE, plus the WHATWG Encoding Standard set (windows-874/1250-1258, iso-8859-2..16, koi8-r/u, macintosh, ibm866, Shift_JIS, EUC-JP, ISO-2022-JP, GBK, GB18030, Big5, EUC-KR) under the default `iconv_charsets` feature. No cp437/cp850, EBCDIC or UTF-32. WHATWG tables differ from glibc's in corners: windows-1252 decodes 0x81/0x8D/0x8F/0x90/0x9D to C1 controls (glibc rejects them), Shift_JIS/Big5/EUC-KR follow the browser mappings. `-c`/`//IGNORE` exit 1 when anything was dropped (POSIX, GNU libiconv); glibc 2.39 exits 0 when only unconvertible characters were dropped. `-c` also drops a sequence truncated at end of input, where glibc still errors. `-c -o FILE` writes the converted rest (dropping was requested); without `-c`, `-o` never writes after an error. `-s` is accepted and, like glibc, keeps error messages. `//TRANSLIT` uses a built-in Latin/punctuation table, unknown characters become `?` | `iconv.rs` tests | | L-MAKE-001 | make | `$(eval)` and `$(file)` stop make with `function '...' is not supported (L-MAKE-001)` | Both write makefile state or files mid-expansion; expansion restarts on a `$(shell)`/`$(wildcard)` miss, so side-effecting functions would run more than once | `l_make_001_eval_and_file_unsupported` | | L-MAKE-002 | make | No built-in implicit rules (as `make -r`), pattern rules do not chain through intermediate files, and `vpath`/`VPATH` are not searched | The sandbox has no compiler for built-in rules to call; chaining and directory search are the next steps if real makefiles need them | `l_make_002_no_builtin_or_chained_rules` | | L-MAKE-003 | make | Recipes always run in the sandbox shell one at a time: `SHELL` is ignored, `-j` is accepted but sequential, and `$(MAKE)` fails at MAKELEVEL 4 (`recursive make depth exceeds 4`; GNU has no cap) | Recipes must stay inside the interpreter; each nested make runs on the caller's stack (TM-DOS-126) | `l_make_003_sequential_sandbox_shell` | diff --git a/knowledge/runtimes/browser-package.md b/knowledge/runtimes/browser-package.md index d3551ed0d..197e6568d 100644 --- a/knowledge/runtimes/browser-package.md +++ b/knowledge/runtimes/browser-package.md @@ -94,7 +94,9 @@ Absent (need sockets, threads, or a host FS the browser sandbox lacks): mounts, and native `interop`. Reach the network from a custom builtin that calls the app's own `fetch` instead. -Absent for size rather than capability: `tzdata`. chrono-tz's compiled IANA +Absent for size rather than capability: `tzdata` and `iconv_charsets` (the +`iconv` code page tables; `iconv` then supports UTF-8, ASCII, Latin-1 and +UTF-16 only and refuses other charsets with exit 1). chrono-tz's compiled IANA database is the largest single artifact in the dependency tree (911 KB of this package's binary), so this package omits it. `date` then **fails loudly** on a named `TZ=` zone — a diagnostic on stderr and exit 1 — instead of formatting in diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 7befb21bf..597d8a712 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -1309,7 +1309,7 @@ command count, timeout, `catch_unwind`). | `base64` | Encode/decode base64 | Pure byte transformation; output bounded by input size | | `md5sum`, `sha1sum`, `sha256sum` | Compute checksums | Hash computation on VFS file data; O(n) CPU, bounded by `max_file_size` | | `verify` | Compute/verify file hashes | Same as checksum builtins; reads VFS files only | -| `iconv` | Encoding conversion | Pure byte transformation; output growth (up to 2x for UTF-16) charged to the shared execution budget; `-o` writes through the VFS only after the whole input converted | +| `iconv` | Encoding conversion | Pure byte transformation (code pages via `encoding_rs` static tables, malformed input reported, never panics: exhaustive byte tests); output growth (up to 2x for UTF-16) charged to the shared execution budget; `-o` writes through the VFS only after the whole input converted | | `hextools` (`od`, `xxd`, `hexdump`) | Byte-level inspection | Format VFS file bytes as hex/octal; output bounded by input size | | `semver` | Version string parsing | Pure string comparison; no recursion or resource access | | `strings` | Extract printable strings | Linear scan of byte data; output bounded by input |