Merge upstream main into review-2070

This commit is contained in:
Dylan M. Taylor committed 2026-11-17 16:14:19 -05:00
commit 6cf64e21b4
21 files changed
+3353 -7

No files matched your search

+4
View File
@@ -143,6 +143,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
`crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported.
## Java class inspection
`crates/java-class` extracts Craft Anything `java_class.rs` and `java_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0), preserving separate primary-author source-history ports by Brandon Thomas, BFlat, Afloat and RRFZ. The checked byte-reader, modified UTF-8 unit decoder, descriptor display helper and synthetic class fixtures come from the same source snapshot. Seven regression files retain their source authors. Neutral error wiring and shared crate integration are subsequent changes. No JAR archive, application I/O or bytecode execution is imported.
## WebAssembly inspection
`crates/wasm` extracts Craft Anything `crates/formats/src/wasm.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2`, with its checked byte-reader subset and original synthetic WASM/testkit fixtures (MIT OR Apache-2.0). Eight core-history ports preserve Brandon Thomas, Afloat and RRFZ as primary authors; component, repeated-custom-section and referenced-string regression imports retain source authors and commit references. Fixtures come from `crates/testkit/src/formats.rs` and deterministic mutation helpers from `crates/testkit/src/lib.rs`; no third-party binaries. Shared error naming and workspace wiring are subsequent changes. Existing inspection limits and report behavior are unchanged; this crate validates/inspects/renders, never executes modules.
Generated
+8
View File
@@ -2302,6 +2302,14 @@ dependencies = [
"widestring",
]
[[package]]
name = "craft-java-class"
version = "0.1.0"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-jmap"
version = "0.1.0"
+1
View File
@@ -12,6 +12,7 @@ repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-evm = { path = "crates/evm" }
craft-java-class = { path = "crates/java-class" }
craft-sourcemap = { path = "crates/sourcemap" }
craft-pcap = { path = "crates/pcap" }
craft-har = { path = "crates/har" }
+442
View File
@@ -1,5 +1,7 @@
//! Header-only BMP dimensions and pixel-data coverage, without allocating a canvas.
use crate::error::CodecError;
/// Recognize a BMP file header with a supported DIB header kind.
///
/// This is a format-routing check, not full validation: dimensions and pixel data may still
@@ -13,6 +15,115 @@ pub fn is_supported_header(b: &[u8]) -> bool {
false
}
/// Wrap a DIB (a BMP without its 14-byte `BITMAPFILEHEADER`, as the Windows clipboard holds one
/// for `CF_DIB` and `CF_DIBV5`) as a BMP file the decoders here read. The pixel offset is computed
/// from the header with saturating arithmetic, so a hostile header cannot overflow; whether the
/// pixel data exists is left to the decoder. Apply [`dib_layout`] first for clipboard DIBs.
///
/// # Errors
///
/// Returns [`CodecError::LimitExceeded`] when the output (`dib.len() + 14` bytes) cannot be allocated.
pub fn dib_to_bmp(dib: &[u8]) -> Result<Vec<u8>, CodecError> {
let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
let bi_size = u32_at(0).unwrap_or(40);
let offset = if bi_size == 12 {
let bpp = u16_at(10).unwrap_or(24);
let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 };
14 + bi_size + palette
} else {
let bpp = u16_at(14).unwrap_or(24);
let compression = u32_at(16).unwrap_or(0);
let clr_used = u32_at(32).unwrap_or(0);
let palette_entries = if clr_used != 0 {
clr_used
} else if bpp <= 8 {
1u32 << bpp
} else {
0
};
// The masks of a 52- or 56-byte (V2/V3) header are inside the header; only the other
// header kinds carry them as 12 further bytes before the pixels.
let masks = if compression == 3 && bi_size >= 40 && !matches!(bi_size, 52 | 56) { 12 } else { 0 };
14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4))
};
let total = dib.len().saturating_add(14);
let file_size = u32::try_from(total).unwrap_or(u32::MAX);
let mut bmp = Vec::new();
bmp.try_reserve_exact(total).map_err(|_| CodecError::LimitExceeded(format!("a {total}-byte BMP")))?;
bmp.extend_from_slice(b"BM");
bmp.extend_from_slice(&file_size.to_le_bytes());
bmp.extend_from_slice(&[0u8; 4]);
bmp.extend_from_slice(&offset.to_le_bytes());
bmp.extend_from_slice(dib);
Ok(bmp)
}
/// Put a clipboard DIB with a V4 or V5 header (108 bytes or more) in the layout the decoder reads.
/// A 32-bit one whose alpha mask is set but whose compression says `BI_RGB` is marked
/// `BI_BITFIELDS` (with the usual colour masks when it gives none), so its alpha is kept as
/// Windows programs mean it; arboard makes the same change. Bit fields then need the colour masks
/// after the header too, where Windows puts a copy and the decoder skips them; a DIB without that
/// copy gets it. Any other DIB comes back unchanged, as does one whose 12 extra bytes cannot be
/// allocated.
pub fn dib_layout(mut dib: Vec<u8>) -> Vec<u8> {
let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib };
let put = |d: &mut Vec<u8>, at: usize, v: u32| {
if let Some(b) = d.get_mut(at..at + 4) {
b.copy_from_slice(&v.to_le_bytes());
}
};
// Decide everything first and mutate only after the 12-byte reservation succeeded, so a failed
// allocation returns the DIB unchanged.
let promote = dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000);
let default_masks = promote && (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0));
let mut masks = dib.get(40..52).and_then(|b| <[u8; 12]>::try_from(b).ok());
if default_masks {
let mut m = [0u8; 12];
m[0..4].copy_from_slice(&0x00FF_0000u32.to_le_bytes());
m[4..8].copy_from_slice(&0x0000_FF00u32.to_le_bytes());
m[8..12].copy_from_slice(&0x0000_00FFu32.to_le_bytes());
masks = Some(m);
}
let bitfields = promote || u32_at(&dib, 16) == Some(3);
// Bytes equal to the masks right after the header are a copy only when more bytes follow than
// the pixels need; otherwise they are the pixels (e.g. a 3x1 V5 DIB with pixels equal to the masks).
let has_copy = |m: &[u8; 12]| {
dib.get(size..size.saturating_add(12)) == Some(m.as_slice()) && pixel_bytes(&dib).is_none_or(|need| dib.len().saturating_sub(size) > need)
};
let insert = match masks {
Some(m) if bitfields && size <= dib.len() && !has_copy(&m) => Some(m),
_ => None,
};
if insert.is_some() && dib.try_reserve(12).is_err() {
return dib;
}
if promote {
put(&mut dib, 16, 3);
if default_masks {
put(&mut dib, 40, 0x00FF_0000);
put(&mut dib, 44, 0x0000_FF00);
put(&mut dib, 48, 0x0000_00FF);
}
}
if let Some(m) = insert {
dib.splice(size..size, m);
}
dib
}
/// Bytes of pixel rows (4-byte aligned stride) the info-header dimensions of `dib` call for, or
/// `None` when width, height or bit count cannot be read.
fn pixel_bytes(dib: &[u8]) -> Option<usize> {
let i32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes);
let w = u64::try_from(i32_at(4)?).ok()?;
let h = u64::from(i32_at(8)?.unsigned_abs());
let bpp = u64::from(u16::from_le_bytes(dib.get(14..16)?.try_into().ok()?));
let stride = w.checked_mul(bpp)?.div_ceil(32).checked_mul(4)?;
usize::try_from(stride.checked_mul(h)?).ok()
}
/// Coverage of the declared pixel array. Row byte counts include row padding; RLE coverage
/// counts the pixels drawn by commands and may be smaller than the canvas.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -174,4 +285,335 @@ mod tests {
b[0] = b'X';
assert!(!is_supported_header(&b));
}
// The WordCraft originals, kept verbatim as the oracle.
fn oracle_dib_to_bmp(dib: &[u8]) -> Vec<u8> {
let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
let bi_size = u32_at(0).unwrap_or(40);
let offset = if bi_size == 12 {
let bpp = u16_at(10).unwrap_or(24);
let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 };
14 + bi_size + palette
} else {
let bpp = u16_at(14).unwrap_or(24);
let compression = u32_at(16).unwrap_or(0);
let clr_used = u32_at(32).unwrap_or(0);
let palette_entries = if clr_used != 0 {
clr_used
} else if bpp <= 8 {
1u32 << bpp
} else {
0
};
let masks = if compression == 3 && bi_size >= 40 { 12 } else { 0 };
14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4))
};
let file_size = u32::try_from(14 + dib.len()).unwrap_or(u32::MAX);
let mut bmp = Vec::with_capacity(14 + dib.len());
bmp.extend_from_slice(b"BM");
bmp.extend_from_slice(&file_size.to_le_bytes());
bmp.extend_from_slice(&[0u8; 4]);
bmp.extend_from_slice(&offset.to_le_bytes());
bmp.extend_from_slice(dib);
bmp
}
fn oracle_dib_layout(mut dib: Vec<u8>) -> Vec<u8> {
let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib };
let put = |d: &mut Vec<u8>, at: usize, v: u32| {
if let Some(b) = d.get_mut(at..at + 4) {
b.copy_from_slice(&v.to_le_bytes());
}
};
if dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000) {
put(&mut dib, 16, 3);
if (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0)) {
put(&mut dib, 40, 0x00FF_0000);
put(&mut dib, 44, 0x0000_FF00);
put(&mut dib, 48, 0x0000_00FF);
}
}
if u32_at(&dib, 16) == Some(3)
&& size <= dib.len()
&& let Some(masks) = dib.get(40..52).map(<[u8]>::to_vec)
&& dib.get(size..size + 12) != Some(masks.as_slice())
{
dib.splice(size..size, masks);
}
dib
}
fn core(bpp: u16) -> Vec<u8> {
let mut d = Vec::new();
d.extend_from_slice(&12u32.to_le_bytes());
d.extend_from_slice(&2u16.to_le_bytes());
d.extend_from_slice(&2u16.to_le_bytes());
d.extend_from_slice(&1u16.to_le_bytes());
d.extend_from_slice(&bpp.to_le_bytes());
d.resize(12 + 64, 7);
d
}
#[allow(clippy::too_many_arguments)]
fn info(size: u32, bpp: u16, comp: u32, clr_used: u32, masks: [u32; 4], tail: usize) -> Vec<u8> {
let mut d = vec![0u8; size.clamp(40, 124) as usize];
d[0..4].copy_from_slice(&size.to_le_bytes());
d[4..8].copy_from_slice(&2i32.to_le_bytes());
d[8..12].copy_from_slice(&2i32.to_le_bytes());
d[12..14].copy_from_slice(&1u16.to_le_bytes());
d[14..16].copy_from_slice(&bpp.to_le_bytes());
d[16..20].copy_from_slice(&comp.to_le_bytes());
d[32..36].copy_from_slice(&clr_used.to_le_bytes());
for (i, m) in masks.iter().enumerate() {
if let Some(b) = d.get_mut(40 + 4 * i..44 + 4 * i) {
b.copy_from_slice(&m.to_le_bytes());
}
}
d.extend((0..tail).map(|i| (i * 31 + 5) as u8));
d
}
fn corpus() -> Vec<Vec<u8>> {
let mut v = Vec::new();
for bpp in [1, 4, 8, 24, 0, 99] {
v.push(core(bpp));
}
for bpp in [1u16, 4, 8, 16, 24, 32, 0, 255] {
for clr in [0u32, 1, 5, 256, u32::MAX] {
v.push(info(40, bpp, 0, clr, [0; 4], 40));
}
}
for (size, comp, masks) in [
(40, 3, [0xFF0000, 0xFF00, 0xFF, 0]),
(40, 3, [0; 4]),
(52, 3, [0xFF0000, 0xFF00, 0xFF, 0]),
(108, 3, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]),
(108, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]),
(108, 0, [0, 0, 0, 0xFF00_0000]),
(108, 0, [0; 4]),
(124, 3, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]),
(124, 0, [0, 0, 0, 0xFF00_0000]),
(124, 0, [1, 0, 0, 0xFF00_0000]),
(124, 0, [0xFF0000, 0xFF00, 0xFF, 0]),
(124, 1, [0, 0, 0, 0xFF00_0000]),
(124, 3, [1, 2, 3, 4]),
(0, 0, [0; 4]),
(12, 0, [0; 4]),
(u32::MAX, 3, [0; 4]),
(u32::MAX, 0, [0; 4]),
(200, 3, [9; 4]),
] {
for bpp in [8u16, 16, 32] {
for clr in [0u32, 2, u32::MAX] {
v.push(info(size, bpp, comp, clr, masks, 48));
}
}
}
// 52/56-byte bitfields headers with and without a pixel tail, and 3x1 V5 DIBs.
for size in [52, 56] {
v.push(info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 4));
v.push(info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 0));
}
v.push(v5_3x1(false));
v.push(v5_3x1(true));
v
}
/// 3x1 32-bit V5 BI_BITFIELDS whose three pixels equal the colour masks; with `copy` the DIB
/// also holds the real 12-byte mask copy before the pixels.
fn v5_3x1(copy: bool) -> Vec<u8> {
let masks = [0x00FF_0000u32, 0x0000_FF00, 0x0000_00FF];
let mut d = info(124, 32, 3, 0, [masks[0], masks[1], masks[2], 0xFF00_0000], 0);
d[4..8].copy_from_slice(&3i32.to_le_bytes());
d[8..12].copy_from_slice(&1i32.to_le_bytes());
for _ in 0..usize::from(copy) + 1 {
for m in masks {
d.extend_from_slice(&m.to_le_bytes());
}
}
d
}
fn dib_u32(d: &[u8], at: usize) -> Option<u32> {
d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
}
/// Fixed case 1: a 52- or 56-byte BI_BITFIELDS header holds its masks itself, so `dib_to_bmp`
/// no longer adds the 12 appended-mask bytes the WordCraft original added to the pixel offset.
fn bmp_offset_fixed(dib: &[u8]) -> bool {
matches!(dib_u32(dib, 0).unwrap_or(40), 52 | 56) && dib_u32(dib, 16) == Some(3)
}
/// Fixed case 2: the original read 12 pixel bytes equal to the masks (exact-length payload) as a
/// mask copy and inserted nothing. Returns the corrected output when `cut` is such a case.
fn exact_length_fixed(cut: &[u8]) -> Option<Vec<u8>> {
let o = oracle_dib_layout(cut.to_vec());
let size = usize::try_from(dib_u32(&o, 0).filter(|&s| s >= 108)?).ok()?;
let need = pixel_bytes(&o)?;
let same = o.len() == cut.len()
&& dib_u32(&o, 16) == Some(3)
&& size <= o.len()
&& o.get(size..size + 12).is_some()
&& o.get(size..size + 12) == o.get(40..52)
&& o.len() - size <= need;
if !same {
return None;
}
let mut want = o.clone();
want.splice(size..size, o[40..52].to_vec());
Some(want)
}
#[test]
fn dib_helpers_match_the_wordcraft_originals_byte_for_byte() {
let (mut total, mut offset_cases, mut exact_cases) = (0usize, 0usize, 0usize);
for dib in corpus() {
for n in 0..=dib.len() {
let cut = &dib[..n];
total += 1;
let fixed_layout = exact_length_fixed(cut);
match &fixed_layout {
Some(want) => {
exact_cases += 1;
assert_eq!(&dib_layout(cut.to_vec()), want, "exact-length layout len {n}");
}
None => assert_eq!(dib_layout(cut.to_vec()), oracle_dib_layout(cut.to_vec()), "layout len {n}"),
}
if bmp_offset_fixed(cut) {
offset_cases += 1;
let (new, old) = (dib_to_bmp(cut).unwrap(), oracle_dib_to_bmp(cut));
assert_eq!(new[..10], old[..10]);
assert_eq!(new[14..], old[14..]);
let (a, b) = (dib_u32(&new, 10).unwrap(), dib_u32(&old, 10).unwrap());
assert_eq!(a.saturating_add(12), b, "offset len {n}");
} else {
assert_eq!(dib_to_bmp(cut).unwrap(), oracle_dib_to_bmp(cut), "bmp len {n}");
}
let both = dib_layout(cut.to_vec());
let old_both = oracle_dib_layout(cut.to_vec());
if fixed_layout.is_none() && !bmp_offset_fixed(&both) {
assert_eq!(dib_to_bmp(&both).unwrap(), oracle_dib_to_bmp(&old_both));
}
}
}
eprintln!("corpus cases {total}: 52/56-byte bitfields offset {offset_cases}, exact-length payload {exact_cases}");
assert!(offset_cases > 0 && exact_cases > 0);
}
#[test]
fn dib_helpers_survive_pseudo_random_bytes() {
let mut x = 0x9E37_79B9_7F4A_7C15u64;
for len in 0..300usize {
let d: Vec<u8> = (0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x as u8
})
.collect();
let laid = dib_layout(d.clone());
if exact_length_fixed(&d).is_none() && !bmp_offset_fixed(&laid) {
assert_eq!(dib_to_bmp(&laid).unwrap(), oracle_dib_to_bmp(&oracle_dib_layout(d)));
}
}
}
#[test]
fn huge_palette_count_saturates_the_offset() {
let b = dib_to_bmp(&info(40, 8, 0, u32::MAX, [0; 4], 8)).unwrap();
assert_eq!(u32::from_le_bytes([b[10], b[11], b[12], b[13]]), u32::MAX);
let b = dib_to_bmp(&info(u32::MAX, 8, 3, u32::MAX, [0; 4], 8)).unwrap();
assert_eq!(u32::from_le_bytes([b[10], b[11], b[12], b[13]]), u32::MAX);
}
#[test]
fn wrapped_dibs_decode_and_keep_alpha() {
// 2x2 32-bit V5, BI_RGB with an alpha mask, bottom-up BGRA pixels.
let mut d = info(124, 32, 0, 0, [0, 0, 0, 0xFF00_0000], 0);
let px = [[1u8, 2, 3, 255], [4, 5, 6, 128], [7, 8, 9, 64], [10, 11, 12, 0]];
for p in px {
d.extend_from_slice(&p);
}
let bmp = dib_to_bmp(&dib_layout(d)).unwrap();
let img = crate::decode(&bmp).unwrap();
let alphas: Vec<u16> = img.to_rgba8().chunks(4).map(|p| u16::from(p[3])).collect();
assert_eq!(alphas, [64, 0, 255, 128]);
// 24-bit plain DIB and a 12-byte core 8-bit one open too.
let mut d = info(40, 24, 0, 0, [0; 4], 0);
d.extend_from_slice(&[0, 0, 255, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
assert!(crate::decode(&dib_to_bmp(&d).unwrap()).is_ok());
let mut c = core(8);
c.truncate(12);
c.extend((0..256 * 3).map(|i| i as u8));
c.extend_from_slice(&[0, 1, 0, 0, 2, 3, 0, 0]);
assert!(crate::decode(&dib_to_bmp(&c).unwrap()).is_ok());
}
/// 1x1 32-bit BI_BITFIELDS DIB, one pixel B=10 G=20 R=30 A=128, with the given header size.
fn one_pixel(size: u32) -> Vec<u8> {
let mut d = info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 0);
d[4..8].copy_from_slice(&1i32.to_le_bytes());
d[8..12].copy_from_slice(&1i32.to_le_bytes());
if size == 40 {
for m in [0xFF0000u32, 0xFF00, 0xFF] {
d.extend_from_slice(&m.to_le_bytes());
}
}
d.extend_from_slice(&[10, 20, 30, 128]);
d
}
#[test]
fn bitfields_pixel_offset_for_each_header_size_decodes() {
for size in [40u32, 52, 56] {
let bmp = dib_to_bmp(&one_pixel(size)).unwrap();
let off = 14 + size + if size == 40 { 12 } else { 0 };
assert_eq!(dib_u32(&bmp, 10), Some(off), "offset for {size}");
let img = crate::decode(&bmp).unwrap_or_else(|e| panic!("{size}-byte header: {e:?}"));
let rgba = img.to_rgba8();
assert_eq!(&rgba[..3], &[30, 20, 10], "size {size}");
if size == 56 {
assert_eq!(rgba[3], 128);
}
}
// V5: the header's masks, a copy inserted by `dib_layout`, then the pixel.
let bmp = dib_to_bmp(&dib_layout(one_pixel(124))).unwrap();
assert_eq!(&crate::decode(&bmp).unwrap().to_rgba8()[..4], &[30, 20, 10, 128]);
}
#[test]
fn exact_length_pixels_equal_to_the_masks_are_not_a_mask_copy() {
let d = v5_3x1(false);
let laid = dib_layout(d.clone());
assert_eq!(laid.len(), d.len() + 12);
assert_eq!(laid[124..136], d[40..52]);
assert_eq!(oracle_dib_layout(d).len(), laid.len() - 12, "the original skipped the insertion");
let img = crate::decode(&dib_to_bmp(&laid).unwrap()).unwrap().to_rgba8();
assert_eq!(img.len(), 12);
// pixel 0 is 0x00FF0000 (blue 0, green 0, red 255 under the masks).
assert_eq!(&img[..3], &[255, 0, 0]);
// A real copy followed by the pixels is left alone.
let real = v5_3x1(true);
assert_eq!(dib_layout(real.clone()), real);
assert!(crate::decode(&dib_to_bmp(&real).unwrap()).is_ok());
}
#[test]
fn layout_decides_before_it_mutates() {
// BI_RGB V5 with an alpha mask and no colour masks: promoted and given a copy together.
let mut d = info(124, 32, 0, 0, [0, 0, 0, 0xFF00_0000], 16);
d[4..8].copy_from_slice(&2i32.to_le_bytes());
let laid = dib_layout(d.clone());
assert_eq!(laid.len(), d.len() + 12);
assert_eq!(dib_u32(&laid, 16), Some(3));
// Unreadable dimensions keep the byte-equality rule.
let mut odd = info(108, 32, 3, 0, [1, 2, 3, 0], 0);
odd[4..8].copy_from_slice(&(-1i32).to_le_bytes());
let copy = odd[40..52].to_vec();
odd.extend_from_slice(&copy);
assert_eq!(dib_layout(odd.clone()), odd);
}
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name="craft-java-class"
description="Java class-file inspection and JVM bytecode decoding with retained bounds and partial reports"
version.workspace=true
edition.workspace=true
license.workspace=true
rust-version.workspace=true
repository.workspace=true
[lints]
workspace=true
[dependencies]
serde={workspace=true}
thiserror={workspace=true}
+51
View File
@@ -0,0 +1,51 @@
//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range.
#[derive(Debug, Clone, Copy)]
pub struct Reader<'a> {
data: &'a [u8],
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Reader { data }
}
pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> {
let end = off.checked_add(len)?;
self.data.get(off..end)
}
pub fn u8(&self, off: usize) -> Option<u8> {
self.data.get(off).copied()
}
fn arr<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
self.slice(off, N)?.try_into().ok()
}
pub fn u16_be(&self, off: usize) -> Option<u16> {
self.arr(off).map(u16::from_be_bytes)
}
pub fn u32_be(&self, off: usize) -> Option<u32> {
self.arr(off).map(u32::from_be_bytes)
}
pub fn u64_be(&self, off: usize) -> Option<u64> {
self.arr(off).map(u64::from_be_bytes)
}
}
/// Decode one modified UTF-8 code unit. Invalid bytes consume only themselves,
/// so a damaged sequence cannot hide valid text or borrow missing bytes.
pub(crate) fn mutf8_unit(bytes: &[u8]) -> (u16, usize) {
match bytes {
[a @ 0x00..=0x7f, ..] => (u16::from(*a), 1),
[0xc0, 0x80, ..] => (0, 2),
[a @ 0xc2..=0xdf, b @ 0x80..=0xbf, ..] => ((u16::from(*a & 0x1f) << 6) | u16::from(*b & 0x3f), 2),
[a @ 0xe0..=0xef, b @ 0x80..=0xbf, c @ 0x80..=0xbf, ..] if *a != 0xe0 || *b >= 0xa0 => {
((u16::from(*a & 0x0f) << 12) | (u16::from(*b & 0x3f) << 6) | u16::from(*c & 0x3f), 3)
}
_ => (0xfffd, 1),
}
}
+19
View File
@@ -0,0 +1,19 @@
// Descriptor display helper retained from the source DEX reader.
pub fn java_name(desc: &str) -> String {
let dims = desc.chars().take_while(|&c| c == '[').count();
let base = desc.get(dims..).unwrap_or("");
let name = match base {
"V" => "void".to_string(),
"Z" => "boolean".to_string(),
"B" => "byte".to_string(),
"S" => "short".to_string(),
"C" => "char".to_string(),
"I" => "int".to_string(),
"J" => "long".to_string(),
"F" => "float".to_string(),
"D" => "double".to_string(),
b if b.starts_with('L') && b.ends_with(';') => b.get(1..b.len() - 1).unwrap_or("").replace('/', "."),
b => b.to_string(),
};
format!("{name}{}", "[]".repeat(dims.min(255)))
}
File diff suppressed because it is too large. Load diff
+711
View File
@@ -0,0 +1,711 @@
//! JVM bytecode: the opcode table (every defined opcode plus the `wide`, `tableswitch` and
//! `lookupswitch` variable-length forms) and a decoder for each instruction. Pure decoding;
//! constant-pool index operands are resolved by the caller (see [`crate::java_class`]).
use serde::Serialize;
/// The shape of an opcode's operands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Operands {
/// No operands.
None,
/// One signed byte immediate (`bipush`).
Byte,
/// One signed short immediate (`sipush`).
Short,
/// A one-byte local-variable index.
Local,
/// `iinc`: a one-byte local index and a signed byte increment.
LocalConst,
/// A two-byte signed branch offset.
Branch2,
/// A four-byte signed branch offset (`goto_w`, `jsr_w`).
Branch4,
/// A one-byte constant-pool index (`ldc`).
Cp1,
/// A two-byte constant-pool index.
Cp2,
/// `newarray`: a one-byte primitive array type.
NewArray,
/// `invokeinterface`: a two-byte index, a count byte and a zero byte.
InvokeInterface,
/// `invokedynamic`: a two-byte index and two zero bytes.
InvokeDynamic,
/// `multianewarray`: a two-byte class index and a dimension byte.
MultiANewArray,
/// `tableswitch` (variable length, 4-byte aligned).
TableSwitch,
/// `lookupswitch` (variable length, 4-byte aligned).
LookupSwitch,
/// `wide`: a prefix that widens the following load/store/ret/iinc.
Wide,
/// A reserved or unknown opcode.
Reserved,
}
/// One opcode slot.
#[derive(Debug, Clone, Copy)]
pub struct Op {
pub name: &'static str,
pub operands: Operands,
}
const fn op(name: &'static str, operands: Operands) -> Op {
Op { name, operands }
}
/// The opcode table entry for `b`.
pub fn opcode(b: u8) -> Op {
use Operands as O;
match b {
0x00 => op("nop", O::None),
0x01 => op("aconst_null", O::None),
0x02 => op("iconst_m1", O::None),
0x03 => op("iconst_0", O::None),
0x04 => op("iconst_1", O::None),
0x05 => op("iconst_2", O::None),
0x06 => op("iconst_3", O::None),
0x07 => op("iconst_4", O::None),
0x08 => op("iconst_5", O::None),
0x09 => op("lconst_0", O::None),
0x0a => op("lconst_1", O::None),
0x0b => op("fconst_0", O::None),
0x0c => op("fconst_1", O::None),
0x0d => op("fconst_2", O::None),
0x0e => op("dconst_0", O::None),
0x0f => op("dconst_1", O::None),
0x10 => op("bipush", O::Byte),
0x11 => op("sipush", O::Short),
0x12 => op("ldc", O::Cp1),
0x13 => op("ldc_w", O::Cp2),
0x14 => op("ldc2_w", O::Cp2),
0x15 => op("iload", O::Local),
0x16 => op("lload", O::Local),
0x17 => op("fload", O::Local),
0x18 => op("dload", O::Local),
0x19 => op("aload", O::Local),
0x1a => op("iload_0", O::None),
0x1b => op("iload_1", O::None),
0x1c => op("iload_2", O::None),
0x1d => op("iload_3", O::None),
0x1e => op("lload_0", O::None),
0x1f => op("lload_1", O::None),
0x20 => op("lload_2", O::None),
0x21 => op("lload_3", O::None),
0x22 => op("fload_0", O::None),
0x23 => op("fload_1", O::None),
0x24 => op("fload_2", O::None),
0x25 => op("fload_3", O::None),
0x26 => op("dload_0", O::None),
0x27 => op("dload_1", O::None),
0x28 => op("dload_2", O::None),
0x29 => op("dload_3", O::None),
0x2a => op("aload_0", O::None),
0x2b => op("aload_1", O::None),
0x2c => op("aload_2", O::None),
0x2d => op("aload_3", O::None),
0x2e => op("iaload", O::None),
0x2f => op("laload", O::None),
0x30 => op("faload", O::None),
0x31 => op("daload", O::None),
0x32 => op("aaload", O::None),
0x33 => op("baload", O::None),
0x34 => op("caload", O::None),
0x35 => op("saload", O::None),
0x36 => op("istore", O::Local),
0x37 => op("lstore", O::Local),
0x38 => op("fstore", O::Local),
0x39 => op("dstore", O::Local),
0x3a => op("astore", O::Local),
0x3b => op("istore_0", O::None),
0x3c => op("istore_1", O::None),
0x3d => op("istore_2", O::None),
0x3e => op("istore_3", O::None),
0x3f => op("lstore_0", O::None),
0x40 => op("lstore_1", O::None),
0x41 => op("lstore_2", O::None),
0x42 => op("lstore_3", O::None),
0x43 => op("fstore_0", O::None),
0x44 => op("fstore_1", O::None),
0x45 => op("fstore_2", O::None),
0x46 => op("fstore_3", O::None),
0x47 => op("dstore_0", O::None),
0x48 => op("dstore_1", O::None),
0x49 => op("dstore_2", O::None),
0x4a => op("dstore_3", O::None),
0x4b => op("astore_0", O::None),
0x4c => op("astore_1", O::None),
0x4d => op("astore_2", O::None),
0x4e => op("astore_3", O::None),
0x4f => op("iastore", O::None),
0x50 => op("lastore", O::None),
0x51 => op("fastore", O::None),
0x52 => op("dastore", O::None),
0x53 => op("aastore", O::None),
0x54 => op("bastore", O::None),
0x55 => op("castore", O::None),
0x56 => op("sastore", O::None),
0x57 => op("pop", O::None),
0x58 => op("pop2", O::None),
0x59 => op("dup", O::None),
0x5a => op("dup_x1", O::None),
0x5b => op("dup_x2", O::None),
0x5c => op("dup2", O::None),
0x5d => op("dup2_x1", O::None),
0x5e => op("dup2_x2", O::None),
0x5f => op("swap", O::None),
0x60 => op("iadd", O::None),
0x61 => op("ladd", O::None),
0x62 => op("fadd", O::None),
0x63 => op("dadd", O::None),
0x64 => op("isub", O::None),
0x65 => op("lsub", O::None),
0x66 => op("fsub", O::None),
0x67 => op("dsub", O::None),
0x68 => op("imul", O::None),
0x69 => op("lmul", O::None),
0x6a => op("fmul", O::None),
0x6b => op("dmul", O::None),
0x6c => op("idiv", O::None),
0x6d => op("ldiv", O::None),
0x6e => op("fdiv", O::None),
0x6f => op("ddiv", O::None),
0x70 => op("irem", O::None),
0x71 => op("lrem", O::None),
0x72 => op("frem", O::None),
0x73 => op("drem", O::None),
0x74 => op("ineg", O::None),
0x75 => op("lneg", O::None),
0x76 => op("fneg", O::None),
0x77 => op("dneg", O::None),
0x78 => op("ishl", O::None),
0x79 => op("lshl", O::None),
0x7a => op("ishr", O::None),
0x7b => op("lshr", O::None),
0x7c => op("iushr", O::None),
0x7d => op("lushr", O::None),
0x7e => op("iand", O::None),
0x7f => op("land", O::None),
0x80 => op("ior", O::None),
0x81 => op("lor", O::None),
0x82 => op("ixor", O::None),
0x83 => op("lxor", O::None),
0x84 => op("iinc", O::LocalConst),
0x85 => op("i2l", O::None),
0x86 => op("i2f", O::None),
0x87 => op("i2d", O::None),
0x88 => op("l2i", O::None),
0x89 => op("l2f", O::None),
0x8a => op("l2d", O::None),
0x8b => op("f2i", O::None),
0x8c => op("f2l", O::None),
0x8d => op("f2d", O::None),
0x8e => op("d2i", O::None),
0x8f => op("d2l", O::None),
0x90 => op("d2f", O::None),
0x91 => op("i2b", O::None),
0x92 => op("i2c", O::None),
0x93 => op("i2s", O::None),
0x94 => op("lcmp", O::None),
0x95 => op("fcmpl", O::None),
0x96 => op("fcmpg", O::None),
0x97 => op("dcmpl", O::None),
0x98 => op("dcmpg", O::None),
0x99 => op("ifeq", O::Branch2),
0x9a => op("ifne", O::Branch2),
0x9b => op("iflt", O::Branch2),
0x9c => op("ifge", O::Branch2),
0x9d => op("ifgt", O::Branch2),
0x9e => op("ifle", O::Branch2),
0x9f => op("if_icmpeq", O::Branch2),
0xa0 => op("if_icmpne", O::Branch2),
0xa1 => op("if_icmplt", O::Branch2),
0xa2 => op("if_icmpge", O::Branch2),
0xa3 => op("if_icmpgt", O::Branch2),
0xa4 => op("if_icmple", O::Branch2),
0xa5 => op("if_acmpeq", O::Branch2),
0xa6 => op("if_acmpne", O::Branch2),
0xa7 => op("goto", O::Branch2),
0xa8 => op("jsr", O::Branch2),
0xa9 => op("ret", O::Local),
0xaa => op("tableswitch", O::TableSwitch),
0xab => op("lookupswitch", O::LookupSwitch),
0xac => op("ireturn", O::None),
0xad => op("lreturn", O::None),
0xae => op("freturn", O::None),
0xaf => op("dreturn", O::None),
0xb0 => op("areturn", O::None),
0xb1 => op("return", O::None),
0xb2 => op("getstatic", O::Cp2),
0xb3 => op("putstatic", O::Cp2),
0xb4 => op("getfield", O::Cp2),
0xb5 => op("putfield", O::Cp2),
0xb6 => op("invokevirtual", O::Cp2),
0xb7 => op("invokespecial", O::Cp2),
0xb8 => op("invokestatic", O::Cp2),
0xb9 => op("invokeinterface", O::InvokeInterface),
0xba => op("invokedynamic", O::InvokeDynamic),
0xbb => op("new", O::Cp2),
0xbc => op("newarray", O::NewArray),
0xbd => op("anewarray", O::Cp2),
0xbe => op("arraylength", O::None),
0xbf => op("athrow", O::None),
0xc0 => op("checkcast", O::Cp2),
0xc1 => op("instanceof", O::Cp2),
0xc2 => op("monitorenter", O::None),
0xc3 => op("monitorexit", O::None),
0xc4 => op("wide", O::Wide),
0xc5 => op("multianewarray", O::MultiANewArray),
0xc6 => op("ifnull", O::Branch2),
0xc7 => op("ifnonnull", O::Branch2),
0xc8 => op("goto_w", O::Branch4),
0xc9 => op("jsr_w", O::Branch4),
0xca => op("breakpoint", O::None),
0xfe => op("impdep1", O::None),
0xff => op("impdep2", O::None),
_ => op("unknown", O::Reserved),
}
}
/// The primitive array type for a `newarray` atype operand.
pub fn array_type(atype: i32) -> &'static str {
match atype {
4 => "boolean",
5 => "char",
6 => "float",
7 => "double",
8 => "byte",
9 => "short",
10 => "int",
11 => "long",
_ => "?",
}
}
/// A decoded `tableswitch`/`lookupswitch`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Switch {
/// Absolute byte offset of the default branch.
pub default: i64,
/// `(key, absolute target)` pairs in listing order.
pub pairs: Vec<(i32, i64)>,
}
/// One decoded instruction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Insn {
/// Byte offset from the start of the method's code.
pub pc: u32,
pub opcode: u8,
pub name: &'static str,
/// Total length in bytes, including operands.
pub len: u32,
/// Local-variable index operand (load/store/ret/iinc).
#[serde(skip_serializing_if = "Option::is_none")]
pub local: Option<u16>,
/// Integer immediate (`bipush`/`sipush`/`iinc` increment/`newarray` type/`multianewarray` dims).
#[serde(skip_serializing_if = "Option::is_none")]
pub int: Option<i32>,
/// Constant-pool index operand (resolved by the caller).
#[serde(skip_serializing_if = "Option::is_none")]
pub cp_index: Option<u16>,
/// Absolute byte offset of a branch target.
#[serde(skip_serializing_if = "Option::is_none")]
pub branch: Option<i64>,
/// A switch table when the opcode is `tableswitch`/`lookupswitch`.
#[serde(skip_serializing_if = "Option::is_none")]
pub switch: Option<Switch>,
/// True when this instruction was prefixed by `wide`.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub wide: bool,
}
/// Most entries decoded from one switch table.
const MAX_SWITCH: usize = 1 << 20;
fn s8(code: &[u8], at: usize) -> Option<i32> {
code.get(at).map(|&b| i32::from(b as i8))
}
fn u16b(code: &[u8], at: usize) -> Option<u16> {
Some(u16::from(*code.get(at)?) << 8 | u16::from(*code.get(at + 1)?))
}
fn s16(code: &[u8], at: usize) -> Option<i32> {
u16b(code, at).map(|v| i32::from(v as i16))
}
fn s32(code: &[u8], at: usize) -> Option<i32> {
Some(i32::from(*code.get(at)?) << 24 | i32::from(*code.get(at + 1)?) << 16 | i32::from(*code.get(at + 2)?) << 8 | i32::from(*code.get(at + 3)?))
}
fn base(pc: usize, opcode: u8, name: &'static str) -> Insn {
Insn { pc: pc as u32, opcode, name, len: 1, local: None, int: None, cp_index: None, branch: None, switch: None, wide: false }
}
/// Decode one instruction at `pc`, or `None` for invalid or incomplete operands.
pub fn decode_one(code: &[u8], pc: usize) -> Option<Insn> {
let b = *code.get(pc)?;
let o = opcode(b);
let mut insn = base(pc, b, o.name);
let rel = |d: i32| pc as i64 + i64::from(d);
match o.operands {
Operands::None | Operands::Reserved => {}
Operands::Byte => {
insn.int = Some(s8(code, pc + 1)?);
insn.len = 2;
}
Operands::Short => {
insn.int = Some(s16(code, pc + 1)?);
insn.len = 3;
}
Operands::Local => {
insn.local = Some(u16::from(*code.get(pc + 1)?));
insn.len = 2;
}
Operands::LocalConst => {
insn.local = Some(u16::from(*code.get(pc + 1)?));
insn.int = Some(s8(code, pc + 2)?);
insn.len = 3;
}
Operands::Branch2 => {
insn.branch = Some(rel(s16(code, pc + 1)?));
insn.len = 3;
}
Operands::Branch4 => {
insn.branch = Some(rel(s32(code, pc + 1)?));
insn.len = 5;
}
Operands::Cp1 => {
insn.cp_index = Some(u16::from(*code.get(pc + 1)?));
insn.len = 2;
}
Operands::Cp2 => {
insn.cp_index = Some(u16b(code, pc + 1)?);
insn.len = 3;
}
Operands::NewArray => {
let atype = *code.get(pc + 1)?;
if !(4..=11).contains(&atype) {
return None;
}
insn.int = Some(i32::from(atype));
insn.len = 2;
}
Operands::InvokeInterface => {
insn.cp_index = Some(u16b(code, pc + 1)?);
if *code.get(pc + 3)? == 0 || *code.get(pc + 4)? != 0 {
return None;
}
insn.len = 5;
}
Operands::InvokeDynamic => {
insn.cp_index = Some(u16b(code, pc + 1)?);
if *code.get(pc + 3)? != 0 || *code.get(pc + 4)? != 0 {
return None;
}
insn.len = 5;
}
Operands::MultiANewArray => {
insn.cp_index = Some(u16b(code, pc + 1)?);
let dimensions = *code.get(pc + 3)?;
if dimensions == 0 {
return None;
}
insn.int = Some(i32::from(dimensions));
insn.len = 4;
}
Operands::Wide => return decode_wide(code, pc),
Operands::TableSwitch => return decode_tableswitch(code, pc),
Operands::LookupSwitch => return decode_lookupswitch(code, pc),
}
if pc.checked_add(insn.len as usize)? > code.len() {
return None;
}
Some(insn)
}
fn decode_wide(code: &[u8], pc: usize) -> Option<Insn> {
let real = *code.get(pc + 1)?;
if !matches!(real, 0x15..=0x19 | 0x36..=0x3a | 0x84 | 0xa9) {
return None;
}
let o = opcode(real);
let mut insn = base(pc, real, o.name);
insn.wide = true;
if real == 0x84 {
// wide iinc: 2-byte local, 2-byte signed const
insn.local = Some(u16b(code, pc + 2)?);
insn.int = Some(s16(code, pc + 4)?);
insn.len = 6;
} else {
// wide load/store/ret: 2-byte local
insn.local = Some(u16b(code, pc + 2)?);
insn.len = 4;
}
if pc.checked_add(insn.len as usize)? > code.len() {
return None;
}
Some(insn)
}
/// Padding so the operand word after a switch opcode is 4-byte aligned from the code start.
fn switch_pad(pc: usize) -> usize {
(4 - ((pc + 1) % 4)) % 4
}
fn decode_tableswitch(code: &[u8], pc: usize) -> Option<Insn> {
let mut at = pc + 1 + switch_pad(pc);
let default = rel_i64(pc, s32(code, at)?);
let low = s32(code, at + 4)?;
let high = s32(code, at + 8)?;
at += 12;
if high < low {
return None;
}
let count = usize::try_from(i64::from(high) - i64::from(low) + 1).ok()?;
if count > MAX_SWITCH {
return None;
}
let end = at.checked_add(count.checked_mul(4)?)?;
code.get(at..end)?;
let mut pairs = Vec::with_capacity(count);
for i in 0..count {
let off = s32(code, at + i * 4)?;
pairs.push((low.wrapping_add(i as i32), rel_i64(pc, off)));
}
let mut insn = base(pc, 0xaa, "tableswitch");
insn.switch = Some(Switch { default, pairs });
insn.len = (end - pc) as u32;
Some(insn)
}
fn decode_lookupswitch(code: &[u8], pc: usize) -> Option<Insn> {
let mut at = pc + 1 + switch_pad(pc);
let default = rel_i64(pc, s32(code, at)?);
let npairs = s32(code, at + 4)?;
at += 8;
if npairs < 0 {
return None;
}
let count = npairs as usize;
if count > MAX_SWITCH {
return None;
}
let end = at.checked_add(count.checked_mul(8)?)?;
code.get(at..end)?;
let mut pairs = Vec::with_capacity(count);
let mut previous = None;
for i in 0..count {
let key = s32(code, at + i * 8)?;
if previous.is_some_and(|previous| key <= previous) {
return None;
}
previous = Some(key);
let off = s32(code, at + i * 8 + 4)?;
pairs.push((key, rel_i64(pc, off)));
}
let mut insn = base(pc, 0xab, "lookupswitch");
insn.switch = Some(Switch { default, pairs });
insn.len = (end - pc) as u32;
Some(insn)
}
fn rel_i64(pc: usize, off: i32) -> i64 {
pc as i64 + i64::from(off)
}
/// Decode a whole method body, stopping at `max` instructions. `complete` is false when a
/// instruction has invalid/incomplete operands or the cap was hit.
pub fn decode(code: &[u8], max: usize) -> (Vec<Insn>, bool) {
let mut out = Vec::new();
let mut pc = 0usize;
let mut complete = true;
while pc < code.len() {
if out.len() >= max {
complete = false;
break;
}
match decode_one(code, pc) {
Some(i) => {
pc += (i.len as usize).max(1);
out.push(i);
}
None => {
complete = false;
break;
}
}
}
(out, complete)
}
#[cfg(test)]
mod tests {
use super::*;
fn lookup(pc: usize, keys: &[i32]) -> Vec<u8> {
let mut code = vec![0; pc];
code.push(0xab);
while !code.len().is_multiple_of(4) {
code.push(0);
}
code.extend_from_slice(&0i32.to_be_bytes());
code.extend_from_slice(&(keys.len() as i32).to_be_bytes());
for key in keys {
code.extend_from_slice(&key.to_be_bytes());
code.extend_from_slice(&0i32.to_be_bytes());
}
code
}
#[test]
fn lookup_keys_must_increase_strictly() {
for keys in [&[1, 1][..], &[1, 0], &[0, -1], &[i32::MIN, i32::MAX, i32::MIN]] {
for pc in 0..4 {
let mut code = lookup(pc, keys);
code.push(0xb1);
assert!(decode_one(&code, pc).is_none(), "pc {pc}, keys {keys:?}");
let (decoded, complete) = decode(&code, 100);
assert!(!complete);
assert_eq!(decoded.len(), pc, "preserve preceding nops, stop before the bad switch");
}
}
}
#[test]
fn lookup_keys_use_signed_order_at_every_alignment() {
for keys in [&[][..], &[i32::MIN, -1, 0, i32::MAX]] {
for pc in 0..4 {
let code = lookup(pc, keys);
let insn = decode_one(&code, pc).unwrap();
assert_eq!(insn.len as usize, code.len() - pc);
let switch = insn.switch.unwrap();
assert_eq!(switch.default, pc as i64);
assert_eq!(switch.pairs, keys.iter().map(|&key| (key, pc as i64)).collect::<Vec<_>>());
assert!(decode(&code, 100).1);
}
}
}
#[test]
fn switch_payloads_must_be_complete() {
for pc in 0..4 {
let lookup = lookup(pc, &[-1, 1]);
let mut dense = vec![0; pc];
dense.push(0xaa);
while !dense.len().is_multiple_of(4) {
dense.push(0);
}
for word in [0i32, i32::MAX - 1, i32::MAX, 0, 0] {
dense.extend_from_slice(&word.to_be_bytes());
}
for code in [lookup, dense] {
assert!(decode_one(&code, pc).is_some());
for end in pc + 1..code.len() {
assert!(decode_one(&code[..end], pc).is_none(), "pc {pc}, end {end}");
}
}
}
}
#[test]
fn switch_counts_cannot_reserve_an_absent_table() {
let mut lookup = lookup(0, &[]);
lookup[8..12].copy_from_slice(&(MAX_SWITCH as i32).to_be_bytes());
assert!(decode_one(&lookup, 0).is_none());
for (low, high) in [(0i32, MAX_SWITCH as i32 - 1), (i32::MIN, i32::MAX)] {
let mut dense = vec![0xaa, 0, 0, 0];
for word in [0, low, high] {
dense.extend_from_slice(&word.to_be_bytes());
}
assert!(decode_one(&dense, 0).is_none());
}
}
#[test]
fn table_covers_defined_opcodes() {
let mut named = 0;
for b in 0..=255u8 {
if opcode(b).name != "unknown" {
named += 1;
}
}
// 0x00..=0xca is 203 opcodes, plus impdep1/impdep2.
assert_eq!(named, 203 + 2);
assert_eq!(opcode(0xb6).name, "invokevirtual");
assert_eq!(opcode(0x10).name, "bipush");
assert_eq!(opcode(0xc4).name, "wide");
}
#[test]
fn decodes_core_formats() {
// iconst_1; bipush 7; istore_1; goto +3 ; (pad to reach len) return
let code = [0x04, 0x10, 0x07, 0x3c, 0xa7, 0x00, 0x03, 0xb1];
let (ins, complete) = decode(&code, 100);
assert!(complete, "{ins:?}");
assert_eq!(ins[0].name, "iconst_1");
assert_eq!(ins[1].name, "bipush");
assert_eq!(ins[1].int, Some(7));
assert_eq!(ins[2].name, "istore_1");
assert_eq!(ins[3].name, "goto");
assert_eq!(ins[3].branch, Some(7)); // pc 4 + 3
assert_eq!(ins[4].name, "return");
}
#[test]
fn decodes_invoke_and_wide() {
// invokevirtual #5 ; invokeinterface #6 count 2 ; wide iload 300
let code = [0xb6, 0x00, 0x05, 0xb9, 0x00, 0x06, 0x02, 0x00, 0xc4, 0x15, 0x01, 0x2c];
let (ins, complete) = decode(&code, 100);
assert!(complete);
assert_eq!(ins[0].name, "invokevirtual");
assert_eq!(ins[0].cp_index, Some(5));
assert_eq!(ins[0].len, 3);
assert_eq!(ins[1].name, "invokeinterface");
assert_eq!(ins[1].cp_index, Some(6));
assert_eq!(ins[1].len, 5);
assert_eq!(ins[2].name, "iload");
assert!(ins[2].wide);
assert_eq!(ins[2].local, Some(300));
assert_eq!(ins[2].len, 4);
}
#[test]
fn decodes_switches() {
// tableswitch at pc 0: pad 3, default +40, low 1, high 2, offsets +10, +20
let mut code = vec![0xaa, 0, 0, 0];
code.extend_from_slice(&40i32.to_be_bytes());
code.extend_from_slice(&1i32.to_be_bytes());
code.extend_from_slice(&2i32.to_be_bytes());
code.extend_from_slice(&10i32.to_be_bytes());
code.extend_from_slice(&20i32.to_be_bytes());
let i = decode_one(&code, 0).unwrap();
assert_eq!(i.name, "tableswitch");
let sw = i.switch.unwrap();
assert_eq!(sw.default, 40);
assert_eq!(sw.pairs, vec![(1, 10), (2, 20)]);
assert_eq!(i.len as usize, code.len());
// lookupswitch at pc 0: pad 3, default +4, npairs 1, (key 99 -> +8)
let mut lk = vec![0xab, 0, 0, 0];
lk.extend_from_slice(&4i32.to_be_bytes());
lk.extend_from_slice(&1i32.to_be_bytes());
lk.extend_from_slice(&99i32.to_be_bytes());
lk.extend_from_slice(&8i32.to_be_bytes());
let l = decode_one(&lk, 0).unwrap();
let sw = l.switch.unwrap();
assert_eq!(sw.default, 4);
assert_eq!(sw.pairs, vec![(99, 8)]);
}
#[test]
fn hostile() {
for seed in 0..256 {
let n = crate::test_support::noise(seed, 512);
let _ = decode(&n, 10_000);
}
// truncated operands never panic
let _ = decode(&[0xb6, 0x00], 10);
let _ = decode(&[0xaa, 0, 0, 0, 0, 0, 0, 0], 10);
let _ = decode(&[0xab, 0, 0, 0, 0, 0, 0, 0, 0x7f, 0xff, 0xff, 0xff], 10);
let _ = decode(&[0xc4], 10);
}
}
+50
View File
@@ -0,0 +1,50 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! Java class-file inspection and JVM bytecode decoding. Never executes bytecode.
//! Retains source item, attribute and annotation-depth limits and partial reports.
mod bytes;
mod descriptor;
pub mod java_class;
pub mod java_ops;
pub use java_class::*;
#[cfg(test)]
mod test_support;
/// File admission errors; damaged optional structures retain partial-report warnings.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum JavaClassError {
#[error("the file ends early ({0})")]
Truncated(String),
#[error("the file is malformed ({0})")]
Malformed(String),
#[error("not supported: {0}")]
Unsupported(String),
}
use JavaClassError as FormatError;
#[cfg(test)]
#[path = "regressions/java_array_operands.rs"]
mod java_array_operands;
#[cfg(test)]
#[path = "regressions/java_attribute_names.rs"]
mod java_attribute_names;
#[cfg(test)]
#[path = "regressions/java_constant_pool_slots.rs"]
mod java_constant_pool_slots;
#[cfg(test)]
#[path = "regressions/java_invoke_operands.rs"]
mod java_invoke_operands;
#[cfg(test)]
#[path = "regressions/java_linkage_references.rs"]
mod java_linkage_references;
#[cfg(test)]
#[path = "regressions/java_truncated_attributes.rs"]
mod java_truncated_attributes;
#[cfg(test)]
#[path = "regressions/java_wide_opcodes.rs"]
mod java_wide_opcodes;
@@ -0,0 +1,48 @@
use crate::java_ops::{decode, decode_one};
#[test]
fn invalid_primitive_array_types_stop_before_the_allocation() {
for atype in (0..=u8::MAX).filter(|value| !(4..=11).contains(value)) {
assert!(decode_one(&[0xbc, atype], 0).is_none(), "atype {atype}");
let (instructions, complete) = decode(&[0, 0xbc, atype, 0xb1], 100);
assert!(!complete, "atype {atype}");
assert_eq!(instructions.len(), 1);
assert_eq!(instructions[0].name, "nop");
}
}
#[test]
fn zero_dimension_multidimensional_allocations_are_not_complete_bytecode() {
assert!(decode_one(&[0xc5, 0, 1, 0], 0).is_none());
let (instructions, complete) = decode(&[0, 0xc5, 0, 1, 0, 0xb1], 100);
assert!(!complete);
assert_eq!(instructions.len(), 1);
assert_eq!(instructions[0].name, "nop");
}
#[test]
fn every_defined_primitive_type_and_nonzero_dimension_remains_decodable() {
for atype in 4..=11 {
let (instructions, complete) = decode(&[0xbc, atype, 0xb1], 100);
assert!(complete);
assert_eq!(instructions.len(), 2);
assert_eq!(instructions[0].int, Some(i32::from(atype)));
assert_eq!(instructions[0].len, 2);
}
for dimensions in 1..=u8::MAX {
let instruction = decode_one(&[0, 0xc5, 0x12, 0x34, dimensions], 1).unwrap();
assert_eq!(instruction.pc, 1);
assert_eq!(instruction.cp_index, Some(0x1234));
assert_eq!(instruction.int, Some(i32::from(dimensions)));
assert_eq!(instruction.len, 4);
}
}
#[test]
fn incomplete_array_operands_remain_rejected() {
for instruction in [&[0xbc, 10][..], &[0xc5, 0, 1, 2][..]] {
for end in 1..instruction.len() {
assert!(decode_one(&instruction[..end], 0).is_none());
}
}
}
@@ -0,0 +1,132 @@
use crate::java_class::{self, ClassFile, Const};
#[derive(Clone, Copy, Debug)]
enum Scope {
Class,
Field,
Method,
Code,
}
fn u16b(out: &mut Vec<u8>, n: u16) {
out.extend_from_slice(&n.to_be_bytes());
}
fn u32b(out: &mut Vec<u8>, n: u32) {
out.extend_from_slice(&n.to_be_bytes());
}
fn utf8(out: &mut Vec<u8>, text: &str) {
out.push(1);
u16b(out, text.len() as u16);
out.extend_from_slice(text.as_bytes());
}
fn attr(name: u16, info: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
u16b(&mut out, name);
u32b(&mut out, info.len() as u32);
out.extend_from_slice(info);
out
}
fn attributes(out: &mut Vec<u8>, repeated: u16, known: &[Vec<u8>]) {
u16b(out, repeated + known.len() as u16);
for _ in 0..repeated {
out.extend_from_slice(&attr(5, &[]));
}
for bytes in known {
out.extend_from_slice(bytes);
}
}
// A valid shared CONSTANT_Utf8 is named by every unknown attribute. Known
// attributes follow it, so avoiding name copies must not discard their facts.
fn fixture(scope: Scope, repeated: u16) -> Vec<u8> {
let mut out = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52];
u16b(&mut out, 17);
utf8(&mut out, "AttributeFixture"); // 1
out.push(7);
u16b(&mut out, 1); // 2: this class
utf8(&mut out, "java/lang/Object"); // 3
out.push(7);
u16b(&mut out, 3); // 4: superclass
utf8(&mut out, &format!("org.example.{}", "A".repeat(usize::from(u16::MAX) - 12))); // 5
for text in ["SourceFile", "AttributeFixture.java", "field", "I"] {
utf8(&mut out, text); // 6..9
}
out.push(3);
u32b(&mut out, 42); // 10
for text in ["ConstantValue", "run", "()V", "Code", "LineNumberTable", "Deprecated"] {
utf8(&mut out, text); // 11..16
}
for word in [0x0021, 2, 4, 0, 1, 0x0019, 8, 9] {
u16b(&mut out, word);
}
attributes(&mut out, if matches!(scope, Scope::Field) { repeated } else { 0 }, &[attr(11, &10u16.to_be_bytes()), attr(16, &[])]);
for word in [1, 0x0009, 12, 13] {
u16b(&mut out, word);
}
let mut code = vec![0, 0, 0, 0, 0, 0, 0, 1, 0xb1, 0, 0];
attributes(&mut code, if matches!(scope, Scope::Code) { repeated } else { 0 }, &[attr(15, &[0, 1, 0, 0, 0, 7])]);
attributes(&mut out, if matches!(scope, Scope::Method) { repeated } else { 0 }, &[attr(14, &code)]);
attributes(&mut out, if matches!(scope, Scope::Class) { repeated } else { 0 }, &[attr(6, &7u16.to_be_bytes())]);
out
}
fn check_facts(parsed: &ClassFile) {
assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
assert_eq!(parsed.this_class, "AttributeFixture");
assert_eq!(parsed.super_class.as_deref(), Some("java/lang/Object"));
assert_eq!(parsed.source_file.as_deref(), Some("AttributeFixture.java"));
assert_eq!(parsed.fields.len(), 1);
assert_eq!(parsed.fields[0].name, "field");
assert_eq!(parsed.fields[0].constant_value.as_deref(), Some("42"));
assert!(parsed.fields[0].deprecated);
assert_eq!(parsed.methods.len(), 1);
assert_eq!(parsed.methods[0].name, "run");
let code = parsed.methods[0].code.as_ref().unwrap();
assert_eq!(code.bytecode, [0xb1]);
assert_eq!(code.line_numbers, [(0, 7)]);
assert!(matches!(&parsed.pool[5], Const::Utf8(name) if name.len() == usize::from(u16::MAX)));
}
#[test]
fn known_attributes_survive_repeated_unknown_names_at_every_scope() {
for scope in [Scope::Class, Scope::Field, Scope::Method, Scope::Code] {
check_facts(&java_class::parse(&fixture(scope, 64)).unwrap());
}
}
fn memory_case(scope: Scope) {
let bytes = fixture(scope, 4096);
assert!(bytes.len() < 100_000);
check_facts(&java_class::parse(&bytes).unwrap());
}
// Run each ignored case separately with a 128 MiB process address-space limit.
// The original parser copies 256 MiB of one attribute name; the fixture itself
// is under 100 KiB. These checks deliberately make no timing assertion.
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_class_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Class);
}
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_field_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Field);
}
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_method_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Method);
}
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_code_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Code);
}
@@ -0,0 +1,53 @@
use crate::{FormatError, java_class};
fn class_with_pool(count: u16, pool: &[u8]) -> Vec<u8> {
let mut bytes = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52];
bytes.extend_from_slice(&count.to_be_bytes());
bytes.extend_from_slice(pool);
bytes.extend_from_slice(&[0; 14]);
bytes
}
#[test]
fn a_wide_constant_needs_its_reserved_slot() {
for tag in [5, 6] {
let mut pool = vec![tag];
pool.extend_from_slice(&[0; 8]);
let bytes = class_with_pool(2, &pool);
assert!(matches!(java_class::parse(&bytes), Err(FormatError::Malformed(message)) if message.contains("second slot")));
}
}
#[test]
fn the_largest_pool_cannot_overflow_on_a_trailing_wide_constant() {
for tag in [5, 6] {
let mut pool = [3, 0, 0, 0, 0].repeat(usize::from(u16::MAX) - 2);
pool.push(tag);
pool.extend_from_slice(&[0; 8]);
let bytes = class_with_pool(u16::MAX, &pool);
assert!(matches!(java_class::parse(&bytes), Err(FormatError::Malformed(message)) if message.contains("second slot")));
}
}
#[test]
fn a_wide_constant_with_two_remaining_slots_is_retained() {
for tag in [5, 6] {
for count in [3, u16::MAX] {
let mut pool = [3, 0, 0, 0, 0].repeat(usize::from(count) - 3);
pool.push(tag);
pool.extend_from_slice(&[0; 8]);
let parsed = java_class::parse(&class_with_pool(count, &pool)).unwrap();
assert_eq!(parsed.pool.len(), usize::from(count));
assert!(matches!(parsed.pool.last(), Some(java_class::Const::Unusable)));
assert!(matches!(parsed.pool[usize::from(count) - 2], java_class::Const::Long(_) | java_class::Const::Double(_)));
}
}
}
#[test]
fn ordinary_final_constants_and_existing_classes_still_parse() {
let parsed = java_class::parse(&class_with_pool(2, &[3, 0, 0, 0, 7])).unwrap();
assert_eq!(parsed.pool, vec![java_class::Const::Unusable, java_class::Const::Integer(7)]);
let parsed = java_class::parse(&crate::test_support::java::hello_class()).unwrap();
assert!(!parsed.methods.is_empty());
}
@@ -0,0 +1,76 @@
use crate::java_class;
use crate::java_ops::{decode, decode_one};
#[test]
fn invokeinterface_requires_a_count_and_zero_reserved_byte() {
for code in [[0xb9, 0, 1, 0, 0], [0xb9, 0, 1, 1, 1], [0xb9, 0, 1, 255, 255]] {
assert!(decode_one(&code, 0).is_none(), "{code:?}");
assert!(!decode(&code, 16).1);
}
}
#[test]
fn invokedynamic_requires_both_reserved_bytes_to_be_zero() {
for code in [[0xba, 0, 1, 1, 0], [0xba, 0, 1, 0, 1], [0xba, 0, 1, 255, 255]] {
assert!(decode_one(&code, 0).is_none(), "{code:?}");
assert!(!decode(&code, 16).1);
}
}
#[test]
fn valid_and_truncated_invocations_keep_their_boundaries() {
for count in [1, 2, 255] {
let instruction = decode_one(&[0xb9, 0x12, 0x34, count, 0], 0).unwrap();
assert_eq!(instruction.cp_index, Some(0x1234));
assert_eq!(instruction.len, 5);
}
let instruction = decode_one(&[0xba, 0x12, 0x34, 0, 0], 0).unwrap();
assert_eq!(instruction.cp_index, Some(0x1234));
for code in [[0xb9, 0, 1, 1, 0], [0xba, 0, 1, 0, 0]] {
for len in 1..5 {
assert!(decode_one(&code[..len], 0).is_none());
}
}
let (instructions, complete) = decode(&[0xb9, 0, 1, 1, 0, 0xba, 0, 2, 0, 0, 0xb1], 16);
assert!(complete);
assert_eq!(instructions.len(), 3);
assert_eq!(instructions[2].pc, 10);
}
fn reference_class() -> java_class::ClassFile {
let mut class = java_class::parse(&crate::test_support::java::hello_class()).unwrap();
class.methods.retain(|method| method.name == "run");
class
}
#[test]
fn malformed_invocations_mark_reference_scans_incomplete() {
let valid = reference_class();
let (expected, incomplete) = java_class::references(&valid, "java/io/PrintStream", None, 10);
assert!(!incomplete);
assert_eq!(expected.len(), 1);
for invalid in [[0xb9, 0, 1, 0, 0], [0xb9, 0, 1, 1, 1], [0xba, 0, 1, 1, 0], [0xba, 0, 1, 0, 1]] {
let mut class = valid.clone();
let code = &mut class.methods[0].code.as_mut().unwrap().bytecode;
let later_reference = code.clone();
*code = invalid.to_vec();
code.extend_from_slice(&later_reference);
let (found, incomplete) = java_class::references(&class, "java/io/PrintStream", None, 10);
assert!(found.is_empty());
assert!(incomplete, "invalid invocation must not hide an unfinished reference scan: {invalid:?}");
}
}
#[test]
fn incomplete_scans_keep_earlier_references_and_scan_other_methods() {
let mut class = reference_class();
let mut later_method = class.methods[0].clone();
later_method.name = "later".into();
class.methods[0].code.as_mut().unwrap().bytecode.extend_from_slice(&[0xba, 0, 1, 1, 0]);
class.methods.push(later_method);
let (found, incomplete) = java_class::references(&class, "java/io/PrintStream", None, 10);
assert!(incomplete);
assert_eq!(found.len(), 2);
assert!(found[0].caller.contains(".run:("));
assert!(found[1].caller.contains(".later:("));
}
@@ -0,0 +1,97 @@
use crate::java_class::{parse, references};
/// A method with a chosen load or call, plus a dynamic call site and a dynamic constant with distinct bootstrap signatures.
fn class(code: &[u8]) -> Vec<u8> {
fn utf(s: &str) -> Vec<u8> {
let mut b = vec![1];
b.extend((s.len() as u16).to_be_bytes());
b.extend(s.bytes());
b
}
let pool = [
utf("Uses"),
vec![7, 0, 1],
utf("java/lang/Object"),
vec![7, 0, 3],
utf("run"),
utf("()V"),
utf("Code"),
utf("BootstrapMethods"),
utf("Target"),
vec![7, 0, 9],
utf("apply"),
vec![12, 0, 11, 0, 6],
vec![10, 0, 10, 0, 12],
vec![15, 6, 0, 13],
utf("Factory"),
vec![7, 0, 15],
utf("boot"),
vec![12, 0, 17, 0, 28],
vec![10, 0, 16, 0, 18],
vec![15, 6, 0, 19],
utf("([LTarget;)V"),
vec![16, 0, 21],
vec![18, 0, 0, 0, 12],
utf("value"),
utf("I"),
vec![12, 0, 24, 0, 25],
vec![17, 0, 1, 0, 26],
utf(
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;)Ljava/lang/invoke/CallSite;",
),
utf("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)I"),
vec![12, 0, 17, 0, 29],
vec![10, 0, 16, 0, 30],
vec![15, 6, 0, 31],
];
let mut bytes = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 55];
bytes.extend((pool.len() as u16 + 1).to_be_bytes());
for e in pool {
bytes.extend(e);
}
bytes.extend([0, 0x21, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0, 9, 0, 5, 0, 6, 0, 1, 0, 7]);
bytes.extend(((12 + code.len()) as u32).to_be_bytes());
bytes.extend([0, 3, 0, 0]);
bytes.extend((code.len() as u32).to_be_bytes());
bytes.extend(code);
bytes.extend([0, 0, 0, 0]);
let boots = [0, 2, 0, 20, 0, 1, 0, 14, 0, 32, 0, 0];
bytes.extend([0, 1, 0, 8]);
bytes.extend((boots.len() as u32).to_be_bytes());
bytes.extend(boots);
bytes
}
fn kinds(code: &[u8], owner: &str, method: Option<&str>) -> Vec<&'static str> {
let cf = parse(&class(code)).unwrap();
let (hits, partial) = references(&cf, owner, method, 10);
assert!(!partial);
hits.into_iter().map(|r| r.kind).collect()
}
#[test]
fn class_literal_has_a_use_site() {
assert_eq!(kinds(&[0x12, 10, 0x57, 0xb1], "Target", None), ["type"]);
}
#[test]
fn literal_method_handle_finds_its_member() {
assert_eq!(kinds(&[0x12, 14, 0x57, 0xb1], "Target", Some("apply")), ["method-handle"]);
}
#[test]
fn method_type_mentions_object_array_components() {
assert_eq!(kinds(&[0x12, 22, 0x57, 0xb1], "Target", None), ["method-type"]);
}
#[test]
fn dynamic_call_exposes_factory_dependency() {
assert_eq!(kinds(&[0xba, 0, 23, 0, 0, 0xb1], "Factory", Some("boot")), ["bootstrap-method"]);
}
#[test]
fn dynamic_call_exposes_static_method_handle_argument() {
assert_eq!(kinds(&[0xba, 0, 23, 0, 0, 0xb1], "Target", Some("apply")), ["method-handle"]);
}
#[test]
fn dynamic_constant_exposes_bootstrap_dependency() {
assert_eq!(kinds(&[0x12, 27, 0x57, 0xb1], "Factory", Some("boot")), ["bootstrap-method"]);
}
#[test]
fn unused_bootstrap_does_not_introduce_a_reference() {
assert!(kinds(&[0xb1], "Factory", None).is_empty());
}
@@ -0,0 +1,46 @@
use crate::java_class::parse;
use crate::test_support::java::hello_class;
/// The fixture ends in a class attribute count and a single two-byte SourceFile attribute.
const ATTRIBUTE_TABLE_BYTES: usize = 10;
/// Every cut of the attribute count, header or body leaves a partial class report.
#[test]
fn incomplete_class_attribute_table_reports_a_warning() {
let data = hello_class();
let start = data.len() - ATTRIBUTE_TABLE_BYTES;
for end in start..data.len() {
let class = parse(&data[..end]).unwrap();
assert_eq!(class.methods.len(), 4);
assert!(class.source_file.is_none());
assert!(class.warnings.iter().any(|warning| warning.contains("class attribute table")), "cut at {}", end - start);
}
}
/// A complete attribute stays available when a subsequent attribute is cut short.
#[test]
fn completed_class_attributes_survive_a_truncated_record() {
let mut data = hello_class();
let start = data.len() - ATTRIBUTE_TABLE_BYTES;
data[start..start + 2].copy_from_slice(&2u16.to_be_bytes());
data.extend_from_slice(&[0, 1, 0, 0, 0, 2, 0]);
let class = parse(&data).unwrap();
assert_eq!(class.source_file.as_deref(), Some("Hello.java"));
assert!(class.warnings.iter().any(|warning| warning.contains("class attribute table")));
}
/// Complete, empty and unknown class attributes do not trigger a truncation warning.
#[test]
fn complete_class_attribute_tables_are_accepted() {
let mut data = hello_class();
let start = data.len() - ATTRIBUTE_TABLE_BYTES;
let original = parse(&data).unwrap();
assert_eq!(original.source_file.as_deref(), Some("Hello.java"));
assert!(original.warnings.is_empty());
data[start..start + 2].copy_from_slice(&2u16.to_be_bytes());
data.extend_from_slice(&[0, 1, 0, 0, 0, 1, 0]);
assert!(parse(&data).unwrap().warnings.is_empty());
data.truncate(start + 2);
data[start..].fill(0);
assert!(parse(&data).unwrap().warnings.is_empty());
}
@@ -0,0 +1,33 @@
use crate::java_ops::{decode, decode_one};
#[test]
fn only_defined_wide_opcodes_are_accepted() {
for op in 0..=255u8 {
let valid = matches!(op, 0x15..=0x19 | 0x36..=0x3a | 0x84 | 0xa9);
let code = [0xc4, op, 0x01, 0x2c, 0xff, 0xfe];
assert_eq!(decode_one(&code, 0).is_some(), valid, "opcode {op:#x}");
}
}
#[test]
fn invalid_wide_does_not_invent_a_method_body() {
let (instructions, complete) = decode(&[0x00, 0xc4, 0xb1, 0, 1, 0xb1], 32);
assert!(!complete);
assert_eq!(instructions.len(), 1);
assert_eq!(instructions[0].name, "nop");
}
#[test]
fn wide_locals_and_signed_increments_are_preserved() {
for op in [0x15, 0x16, 0x17, 0x18, 0x19, 0x36, 0x37, 0x38, 0x39, 0x3a, 0xa9] {
let instruction = decode_one(&[0xc4, op, 0xff, 0xff], 0).unwrap();
assert_eq!(instruction.local, Some(u16::MAX));
assert_eq!(instruction.len, 4);
assert!(instruction.wide);
}
let instruction = decode_one(&[0xc4, 0x84, 0x01, 0x2c, 0xff, 0xfe], 0).unwrap();
assert_eq!(instruction.local, Some(300));
assert_eq!(instruction.int, Some(-2));
assert_eq!(instruction.len, 6);
assert!(decode_one(&[0xc4, 0x84, 0x00, 1], 0).is_none());
}
+316
View File
@@ -0,0 +1,316 @@
/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops.
pub fn noise(seed: u64, len: usize) -> Vec<u8> {
let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;
(0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x as u8
})
.collect()
}
/// Every way to damage a sample used by robustness tests: truncations at many lengths and
/// single-byte corruptions spread across the file.
pub fn mutations(sample: &[u8]) -> Vec<Vec<u8>> {
let mut out = Vec::new();
let n = sample.len();
let step = (n / 64).max(1);
let mut len = 0;
while len < n {
out.push(sample[..len].to_vec());
len += step;
}
for (i, seed) in (0..n).step_by(step).zip(1u64..) {
let mut m = sample.to_vec();
let noise = noise(seed, 8);
for (j, v) in noise.iter().enumerate() {
if let Some(b) = m.get_mut(i + j) {
*b = *v;
}
}
out.push(m);
let mut m = sample.to_vec();
if let Some(b) = m.get_mut(i) {
*b = 0xff;
}
out.push(m);
}
out
}
pub mod java {
use std::collections::HashMap;
/// A constant-pool builder that interns entries and tracks the double slot after `Long`/`Double`.
#[derive(Default)]
struct Pool {
items: Vec<Vec<u8>>,
/// Next free index (1-based; accounts for long/double taking two slots).
count: u16,
cache: HashMap<String, u16>,
}
impl Pool {
fn new() -> Self {
Pool { items: Vec::new(), count: 1, cache: HashMap::new() }
}
fn add(&mut self, bytes: Vec<u8>, slots: u16) -> u16 {
let idx = self.count;
self.items.push(bytes);
self.count += slots;
idx
}
fn utf8(&mut self, s: &str) -> u16 {
let key = format!("u:{s}");
if let Some(&i) = self.cache.get(&key) {
return i;
}
let mut b = vec![1u8];
b.extend_from_slice(&(s.len() as u16).to_be_bytes());
b.extend_from_slice(s.as_bytes());
let i = self.add(b, 1);
self.cache.insert(key, i);
i
}
fn class(&mut self, name: &str) -> u16 {
let n = self.utf8(name);
let key = format!("c:{name}");
if let Some(&i) = self.cache.get(&key) {
return i;
}
let mut b = vec![7u8];
b.extend_from_slice(&n.to_be_bytes());
let i = self.add(b, 1);
self.cache.insert(key, i);
i
}
fn string(&mut self, s: &str) -> u16 {
let u = self.utf8(s);
let mut b = vec![8u8];
b.extend_from_slice(&u.to_be_bytes());
self.add(b, 1)
}
fn nat(&mut self, name: &str, desc: &str) -> u16 {
let n = self.utf8(name);
let d = self.utf8(desc);
let mut b = vec![12u8];
b.extend_from_slice(&n.to_be_bytes());
b.extend_from_slice(&d.to_be_bytes());
self.add(b, 1)
}
fn reff(&mut self, tag: u8, owner: &str, name: &str, desc: &str) -> u16 {
let c = self.class(owner);
let nt = self.nat(name, desc);
let mut b = vec![tag];
b.extend_from_slice(&c.to_be_bytes());
b.extend_from_slice(&nt.to_be_bytes());
self.add(b, 1)
}
fn long(&mut self, v: i64) -> u16 {
let mut b = vec![5u8];
b.extend_from_slice(&v.to_be_bytes());
self.add(b, 2)
}
/// The serialized constant pool and the count field.
fn finish(&self) -> (Vec<u8>, u16) {
(self.items.concat(), self.count)
}
}
fn u16b(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn u32b(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// Build an attribute: name_index, length, body.
fn attr(name_idx: u16, body: Vec<u8>) -> Vec<u8> {
let mut v = Vec::new();
u16b(&mut v, name_idx);
u32b(&mut v, body.len() as u32);
v.extend_from_slice(&body);
v
}
/// A method's `Code` attribute body (max_stack, max_locals, code, exception table, no nested attrs).
fn code_body(max_stack: u16, max_locals: u16, code: &[u8], exc: &[(u16, u16, u16, u16)]) -> Vec<u8> {
let mut v = Vec::new();
u16b(&mut v, max_stack);
u16b(&mut v, max_locals);
u32b(&mut v, code.len() as u32);
v.extend_from_slice(code);
u16b(&mut v, exc.len() as u16);
for (s, e, h, t) in exc {
u16b(&mut v, *s);
u16b(&mut v, *e);
u16b(&mut v, *h);
u16b(&mut v, *t);
}
u16b(&mut v, 0); // nested attributes count
v
}
/// A method_info: access, name, descriptor, and one already-built Code attribute.
fn method(p: &mut Pool, access: u16, name: &str, desc: &str, code_attribute: Vec<u8>) -> Vec<u8> {
let name_idx = p.utf8(name);
let desc_idx = p.utf8(desc);
let mut v = Vec::new();
u16b(&mut v, access);
u16b(&mut v, name_idx);
u16b(&mut v, desc_idx);
u16b(&mut v, 1); // one attribute
v.extend_from_slice(&code_attribute);
v
}
/// Assemble a whole class from its parts.
#[allow(clippy::too_many_arguments)]
fn assemble(
pool: &Pool,
access: u16,
this_c: u16,
super_c: u16,
interfaces: &[u16],
fields: &[Vec<u8>],
methods: &[Vec<u8>],
class_attrs: &[Vec<u8>],
) -> Vec<u8> {
let (cp, count) = pool.finish();
let mut v = Vec::new();
v.extend_from_slice(&[0xca, 0xfe, 0xba, 0xbe]);
u16b(&mut v, 0); // minor
u16b(&mut v, 52); // major (Java 8)
u16b(&mut v, count);
v.extend_from_slice(&cp);
u16b(&mut v, access);
u16b(&mut v, this_c);
u16b(&mut v, super_c);
u16b(&mut v, interfaces.len() as u16);
for i in interfaces {
u16b(&mut v, *i);
}
u16b(&mut v, fields.len() as u16);
for f in fields {
v.extend_from_slice(f);
}
u16b(&mut v, methods.len() as u16);
for m in methods {
v.extend_from_slice(m);
}
u16b(&mut v, class_attrs.len() as u16);
for a in class_attrs {
v.extend_from_slice(a);
}
v
}
pub const HELLO: &str = "Hello, Craft!";
/// `public class com.example.Hello implements Runnable` with a `count` field, a `BIG` long
/// constant, `<init>`, `run()` (System.out.println("Hello, Craft!")), `pick(int)` (a tableswitch)
/// and `guarded()` (a try/catch over the println call).
pub fn hello_class() -> Vec<u8> {
let mut p = Pool::new();
let this_c = p.class("com/example/Hello");
let obj_c = p.class("java/lang/Object");
let runnable_c = p.class("java/lang/Runnable");
let code_attr = p.utf8("Code");
// fields: int count; static final long BIG;
let count_name = p.utf8("count");
let i_desc = p.utf8("I");
let big_name = p.utf8("BIG");
let j_desc = p.utf8("J");
let constval_attr = p.utf8("ConstantValue");
let big_val = p.long(0x1122_3344_5566_7788);
// refs used by code
let obj_init = p.reff(10, "java/lang/Object", "<init>", "()V");
let sysout = p.reff(9, "java/lang/System", "out", "Ljava/io/PrintStream;");
let hello = p.string(HELLO);
let println = p.reff(10, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
let rt_exc = p.class("java/lang/RuntimeException");
// <init>(): aload_0; invokespecial Object.<init>; return
let mut init = vec![0x2a, 0xb7];
init.extend_from_slice(&obj_init.to_be_bytes());
init.push(0xb1);
let init_m = method(&mut p, 0x0001, "<init>", "()V", attr(code_attr, code_body(1, 1, &init, &[])));
// run(): getstatic System.out; ldc "Hello"; invokevirtual println; return
let mut run = vec![0xb2];
run.extend_from_slice(&sysout.to_be_bytes());
run.push(0x12);
run.push(hello as u8); // ldc (1-byte index; pool is small)
run.push(0xb6);
run.extend_from_slice(&println.to_be_bytes());
run.push(0xb1);
let run_m = method(&mut p, 0x0001, "run", "()V", attr(code_attr, code_body(2, 1, &run, &[])));
// pick(int): iload_0; tableswitch{0->L0,1->L1,default->Ldef}; L0: bipush 10; ireturn; L1: bipush 20; ireturn; Ldef: iconst_m1; ireturn
// offsets: iload_1@0; tableswitch@1 (pad 2) ends @24; L0@24; L1@27; Ldef@30
let mut pick = vec![0x1b, 0xaa, 0x00, 0x00];
u32b(&mut pick, 29); // default -> 1+29 = 30
u32b(&mut pick, 0); // low
u32b(&mut pick, 1); // high
u32b(&mut pick, 23); // case 0 -> 1+23 = 24
u32b(&mut pick, 26); // case 1 -> 1+26 = 27
debug_assert_eq!(pick.len(), 24);
pick.extend_from_slice(&[0x10, 10, 0xac]); // @24: bipush 10; ireturn
pick.extend_from_slice(&[0x10, 20, 0xac]); // @27: bipush 20; ireturn
pick.extend_from_slice(&[0x02, 0xac]); // @30: iconst_m1; ireturn
let pick_m = method(&mut p, 0x0001, "pick", "(I)I", attr(code_attr, code_body(1, 1, &pick, &[])));
// guarded(): try { System.out.println("Hello"); } catch (RuntimeException e) {} (then return)
// 0: getstatic(3) ; 3: ldc(2) ; 5: invokevirtual(3) ; 8: goto +5 ->13 ; 11: astore_1 ; 12: return ; 13: return
let mut g = vec![0xb2];
g.extend_from_slice(&sysout.to_be_bytes());
g.push(0x12);
g.push(hello as u8);
g.push(0xb6);
g.extend_from_slice(&println.to_be_bytes());
g.extend_from_slice(&[0xa7, 0x00, 0x05]); // @8 goto -> 13
g.push(0x4c); // @11 astore_1
g.push(0xb1); // @12 return
g.push(0xb1); // @13 return
let guarded_m = method(&mut p, 0x0001, "guarded", "()V", attr(code_attr, code_body(2, 2, &g, &[(0, 8, 11, rt_exc)])));
// field infos
let field = |p: &mut Pool, access: u16, name_idx: u16, desc_idx: u16, attrs: &[Vec<u8>]| -> Vec<u8> {
let _ = p;
let mut v = Vec::new();
u16b(&mut v, access);
u16b(&mut v, name_idx);
u16b(&mut v, desc_idx);
u16b(&mut v, attrs.len() as u16);
for a in attrs {
v.extend_from_slice(a);
}
v
};
let count_f = field(&mut p, 0x0002, count_name, i_desc, &[]); // private int count
let mut cv = Vec::new();
u16b(&mut cv, big_val);
let big_f = field(&mut p, 0x0019, big_name, j_desc, &[attr(constval_attr, cv)]); // public static final long BIG
let source_attr = p.utf8("SourceFile");
let source_val = p.utf8("Hello.java");
let mut sf = Vec::new();
u16b(&mut sf, source_val);
let source = attr(source_attr, sf);
assemble(
&p,
0x0021, // public super
this_c,
obj_c,
&[runnable_c],
&[count_f, big_f],
&[init_m, run_m, pick_m, guarded_m],
&[source],
)
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ mod server;
pub use content::{Contents, base64, image_result, text_result};
pub use schema::{Effect, check_arguments, object, string, tool};
pub use server::{Incoming, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response};
pub use server::{Incoming, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response};
#[cfg(test)]
mod tests;
+40 -5
View File
@@ -4,7 +4,7 @@ use std::io::{BufRead, Write};
use serde_json::{Value, json};
use crate::content::Contents;
use crate::content::{Contents, text_result};
use crate::schema::{check_arguments, check_prompt_arguments};
/// The newest protocol revision we speak; offered when the client asks for one we don't know.
@@ -88,9 +88,25 @@ pub struct Info {
pub max_line: usize,
}
/// Opt-in behaviour for apps with their own conventions; `Options::default()` is what [`Server::new`]
/// does. Set with [`Server::with_options`].
#[derive(Clone, Debug, Default)]
pub struct Options {
/// Sent as `serverInfo.websiteUrl` at `initialize` (MCP 2025-06-18) when set.
pub website_url: Option<String>,
/// Report a `tools/call` whose arguments fail the check against the tool's schema, or whose
/// tool is unknown, as a tool result with `isError: true` and the message as text, not as a
/// JSON-RPC -32602 error. For apps whose clients read every tool failure from the result.
pub tool_errors_as_results: bool,
/// Refuse a request whose `id` is neither a string nor a number (JSON-RPC 2.0) with -32600 and
/// a null id, instead of echoing the id back.
pub strict_request_ids: bool,
}
/// An MCP server over the app's [`Tools`].
pub struct Server<T: Tools> {
info: Info,
options: Options,
tools: T,
initialized: bool,
}
@@ -157,7 +173,13 @@ pub fn response(id: Value, result: Value) -> Value {
impl<T: Tools> Server<T> {
pub fn new(info: Info, tools: T) -> Self {
Self { info, tools, initialized: false }
Self { info, options: Options::default(), tools, initialized: false }
}
/// This server with `options` ([`Options`]) in place of the defaults.
#[must_use]
pub fn with_options(mut self, options: Options) -> Self {
self.options = options;
self
}
pub fn tools(&mut self) -> &mut T {
&mut self.tools
@@ -215,7 +237,11 @@ impl<T: Tools> Server<T> {
if o.contains_key("result") || o.contains_key("error") {
return None;
}
return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`"));
let echoed = match id {
Some(id) if !self.options.strict_request_ids || id.is_string() || id.is_number() => id,
_ => Value::Null,
};
return Some(error(echoed, INVALID_REQUEST, "missing `method`"));
};
let params = o.get("params").cloned().unwrap_or(Value::Null);
let Some(id) = id else {
@@ -224,6 +250,9 @@ impl<T: Tools> Server<T> {
}
return None;
};
if self.options.strict_request_ids && !(id.is_string() || id.is_number()) {
return Some(error(Value::Null, INVALID_REQUEST, "`id` must be a string or number"));
}
Some(match self.request(method, &params) {
Ok(r) => response(id, r),
Err((code, m)) => error(id, code, m),
@@ -236,10 +265,14 @@ impl<T: Tools> Server<T> {
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION);
let version = if SUPPORTED_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSION };
let Info { name, title, version: server_version, .. } = self.info;
let mut server_info = json!({"name": name, "title": title, "version": server_version});
if let Some(url) = &self.options.website_url {
server_info["websiteUrl"] = json!(url);
}
Ok(json!({
"protocolVersion": version,
"capabilities": self.capabilities(),
"serverInfo": {"name": name, "title": title, "version": server_version},
"serverInfo": server_info,
"instructions": self.tools.instructions(),
}))
}
@@ -251,7 +284,9 @@ impl<T: Tools> Server<T> {
None | Some(Value::Null) => json!({}),
Some(a) => a.clone(),
};
check_arguments(&self.tools.list(), name, &args).map_err(|e| (INVALID_PARAMS, e))?;
if let Err(e) = check_arguments(&self.tools.list(), name, &args) {
return if self.options.tool_errors_as_results { Ok(text_result(e, true)) } else { Err((INVALID_PARAMS, e)) };
}
Ok(self.tools.call(name, &args))
}
"resources/list" => Ok(json!({"resources": self.tools.resources()})),
+130 -1
View File
@@ -1,7 +1,8 @@
use serde_json::{Value, json};
use crate::{
Contents, Effect, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result, tool,
Contents, Effect, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result,
tool,
};
/// One app's tools: `echo` and `level`, nothing behind them (no engine, no design). `log` records
@@ -366,3 +367,131 @@ fn every_call_runs_right_after_its_listing() {
reply(&mut s, &json!([call("level", json!({})), call("echo", json!({"text": "b"}))]));
assert_eq!(s.tools().log, ["list", "list", "call echo", "list", "list", "call level", "list", "call echo"]);
}
fn with(options: Options) -> Server<Echo> {
Server::new(info(), Echo::default()).with_options(options)
}
fn call_msg(id: u64, name: &str, args: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": args}})
}
/// `websiteUrl` is sent only when set.
#[test]
fn website_url_is_sent_only_when_set() {
let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}});
let off = reply(&mut with(Options::default()), &init).unwrap();
assert!(off["result"]["serverInfo"].get("websiteUrl").is_none(), "{off}");
let on = reply(&mut with(Options { website_url: Some("https://example.org/echo".into()), ..Options::default() }), &init).unwrap();
assert_eq!(on["result"]["serverInfo"]["websiteUrl"], "https://example.org/echo");
assert_eq!(on["result"]["serverInfo"]["name"], "echo");
}
/// With `tool_errors_as_results`, argument failures and unknown tools are `isError` results that
/// carry the message and never run the tool; other errors stay JSON-RPC errors.
#[test]
fn tool_errors_as_results_replaces_invalid_params() {
let mut s = with(Options { tool_errors_as_results: true, ..Options::default() });
let bad = [
call_msg(1, "echo", json!({})),
call_msg(2, "echo", json!({"text": 3})),
call_msg(3, "echo", json!({"text": "a", "loud": true})),
call_msg(4, "shout", json!({})),
call_msg(5, "echo", json!([])),
call_msg(6, "echo", json!("text")),
call_msg(7, "echo", json!(7)),
];
for msg in &bad {
let r = reply(&mut s, msg).unwrap();
assert!(r.get("error").is_none(), "{r}");
assert_eq!(r["result"]["isError"], true, "{r}");
assert!(r["result"]["content"][0]["text"].as_str().is_some_and(|t| !t.is_empty()), "{r}");
}
let r = reply(&mut s, &bad[0]).unwrap();
assert_eq!(r["result"]["content"][0]["text"], "echo: missing required argument `text`");
assert!(s.tools().calls.is_empty());
let ok = reply(&mut s, &call_msg(8, "echo", json!({"text": "hi"}))).unwrap();
assert_eq!(ok["result"], json!({"content": [{"type": "text", "text": "hi"}]}));
let nomethod = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 9, "method": "nope"})).unwrap();
assert_eq!(nomethod["error"]["code"], -32601);
let noname = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 10, "method": "tools/call", "params": {}})).unwrap();
assert_eq!(noname["error"]["code"], -32602);
// Unchanged with the option off.
let mut off = with(Options::default());
for msg in &bad {
assert_eq!(reply(&mut off, msg).unwrap()["error"]["code"], -32602);
}
}
/// With `strict_request_ids`, an id that is not a string or number is -32600 with a null id; the
/// tool never runs. Off, such ids are echoed as before. Notifications have no id and are unaffected.
#[test]
fn strict_request_ids_refuse_other_id_types() {
let odd = [json!(null), json!(true), json!({"a": 1}), json!([1])];
let mut on = with(Options { strict_request_ids: true, ..Options::default() });
let mut off = with(Options::default());
for id in &odd {
let msg = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "x"}}});
let r = reply(&mut on, &msg).unwrap();
assert_eq!(r["error"]["code"], -32600, "{id}: {r}");
assert_eq!(r["id"], Value::Null);
let r = reply(&mut off, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap();
assert_eq!(r["id"], *id);
assert_eq!(r["result"], json!({}));
}
assert!(on.tools().calls.is_empty());
for id in [json!("a"), json!(1), json!(1.5), json!(-3)] {
let r = reply(&mut on, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap();
assert_eq!(r["result"], json!({}), "{id}");
}
assert!(reply(&mut on, &notification()).is_none());
}
/// The missing-`method` error follows the same id rule: strict mode echoes only string and number
/// ids and answers with a null id for the rest; off, ids are echoed as before.
#[test]
fn strict_request_ids_apply_to_the_missing_method_error() {
let mut on = with(Options { strict_request_ids: true, ..Options::default() });
let mut off = with(Options::default());
for id in [json!(true), json!({"a": 1}), json!([1])] {
let msg = json!({"jsonrpc": "2.0", "id": id});
let r = reply(&mut on, &msg).unwrap();
assert_eq!((r["error"]["code"].clone(), r["id"].clone()), (json!(-32600), Value::Null), "{id}");
assert_eq!(reply(&mut off, &msg).unwrap()["id"], id);
}
for id in [json!("a"), json!(7)] {
assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0", "id": id})).unwrap()["id"], id);
}
assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0"})).unwrap()["id"], Value::Null);
}
/// Hostile input with every option on: oversized and non-UTF-8 lines, odd ids and wrongly typed
/// arguments are answered and serving goes on, and nothing panics.
#[test]
fn every_option_on_survives_hostile_input() {
let mut input = vec![b'x'; (1 << 16) + 10];
input.push(b'\n');
input.extend_from_slice(b"\xff\xfe\n");
for id in ["null", "true", "{}", "[]", "\"s\"", "1e999"] {
input.extend_from_slice(
format!(
"{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"tools/call\",\"params\":{{\"name\":\"echo\",\"arguments\":{{\"text\":{id}}}}}}}\n"
)
.as_bytes(),
);
}
for args in ["null", "1", "\"a\"", "[]", "{\"text\":[1]}", "{\"text\":{}}"] {
input.extend_from_slice(
format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"level\",\"arguments\":{args}}}}}\n").as_bytes(),
);
}
input.extend_from_slice(json!({"jsonrpc": "2.0", "id": 9, "method": "ping"}).to_string().as_bytes());
let mut output = Vec::new();
let options = Options { website_url: Some("https://example.org".into()), tool_errors_as_results: true, strict_request_ids: true };
with(options).serve(std::io::Cursor::new(input), &mut output).unwrap();
let replies: Vec<Value> = String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(replies.len(), 2 + 6 + 6 + 1, "{replies:?}");
assert_eq!(replies[0]["error"]["code"], -32600);
assert_eq!(replies[1]["error"]["code"], -32700);
assert_eq!(replies.last().map(|r| &r["result"]), Some(&json!({})));
}