mod fuzz;
use std::alloc::System;
use fuzz::{Campaign, Rng, mutate};
use microrti_encoding::*;
use stats_alloc::{INSTRUMENTED_SYSTEM, Region, StatsAlloc};
#[global_allocator]
static GLOBAL: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM;
fn allocated(run: impl FnOnce()) -> usize {
let region = Region::new(GLOBAL);
run();
region.change().bytes_allocated
}
type Decode = Box<dyn Fn(&[u8])>;
type Decoder = (&'static str, Decode);
macro_rules! typed {
($($t:ty),+ $(,)?) => {
vec![$((stringify!($t), Box::new(|bytes: &[u8]| {
let _ = decode_prefix::<$t>(bytes);
let _ = decode_from_slice_strict::<$t>(bytes);
}) as Decode)),+]
};
}
fn typed_decoders() -> Vec<Decoder> {
typed![
HLAoctet,
HLAbyte,
HLAboolean,
HLAASCIIchar,
HLAunicodeChar,
HLAoctetPairBE,
HLAoctetPairLE,
HLAinteger16BE,
HLAinteger16LE,
HLAinteger32BE,
HLAinteger32LE,
HLAinteger64BE,
HLAinteger64LE,
HLAunsignedInteger8,
HLAunsignedInteger16BE,
HLAunsignedInteger16LE,
HLAunsignedInteger32BE,
HLAunsignedInteger32LE,
HLAunsignedInteger64BE,
HLAunsignedInteger64LE,
HLAfloat32BE,
HLAfloat32LE,
HLAfloat64BE,
HLAfloat64LE,
HLAASCIIstring,
HLAunicodeString,
String,
HLAopaqueData,
HLAfederateHandle,
HLAobjectClassHandle,
HLAattributeHandle,
HLAinteractionClassHandle,
HLAparameterHandle,
HLAobjectInstanceHandle,
HLAdimensionHandle,
HLAregionHandle,
HLAtransportationTypeHandle,
HLAmessageRetractionHandle,
HLAlogicalTime,
HLAlogicalTimeInterval,
HLAtoken,
Vec<HLAtoken>,
Vec<HLAoctet>,
Vec<HLAinteger64BE>,
Vec<HLAfloat32LE>,
Vec<String>,
Vec<Vec<HLAinteger32BE>>,
Vec<Vec<Vec<HLAunicodeString>>>,
Vec<HLAopaqueData>,
[HLAinteger16BE; 3],
[Vec<HLAoctet>; 2],
[[HLAfloat64BE; 2]; 2],
Box<Vec<HLAASCIIstring>>,
]
}
fn dynamic_decoders() -> Vec<Decoder> {
let mut variant = HLAvariantRecord::new(HLAoctet(0));
variant.set_variant(HLAoctet(1), HLAvariableArray::new(HLAinteger64BE(0))).expect("a variant");
variant.set_variant(HLAoctet(2), HLAunicodeString::new("")).expect("a variant");
let mut extendable = HLAextendableVariantRecord::new(HLAinteger32BE(0));
extendable
.set_variant(HLAinteger32BE(1), HLAvariableArray::new(HLAopaqueData::default()))
.expect("a variant");
let record = HLAfixedRecord::new()
.with(HLAoctet(0))
.with(HLAvariableArray::new(HLAvariableArray::new(HLAinteger16BE(0))))
.with(variant.clone())
.with(extendable.clone());
let decoders: Vec<(&'static str, Box<dyn DataElement>)> = vec![
("HLAvariableArray of HLAinteger64BE", Box::new(HLAvariableArray::new(HLAinteger64BE(0)))),
("HLAvariableArray of HLAunicodeString", Box::new(HLAvariableArray::new(HLAunicodeString::new("")))),
(
"HLAfixedArray of HLAvariableArray",
Box::new(HLAfixedArray::new(HLAvariableArray::new(HLAbyte(0)), 3)),
),
("HLAvariantRecord", Box::new(variant)),
("HLAextendableVariantRecord", Box::new(extendable)),
("HLAfixedRecord", Box::new(record)),
];
decoders
.into_iter()
.map(|(name, prototype)| {
let decode: Decode = Box::new(move |bytes: &[u8]| {
let mut element = prototype.clone();
let _ = element.decode_slice(bytes);
});
(name, decode)
})
.collect()
}
#[cfg(feature = "fom")]
fn fom_decoders() -> Vec<Decoder> {
use microrti_encoding::fom::FomCodec;
use microrti_fom::{Fdd, parse_module};
let restaurant =
std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../fom/RestaurantFOMmodule-2025.xml"))
.expect("the Restaurant FOM");
let mut fdd = Fdd::with_standard_mim();
fdd.merge(&[parse_module("Restaurant.xml", &restaurant).expect("parses")]).expect("merges");
let codec = std::sync::Arc::new(FomCodec::new(&fdd).expect("a codec"));
let names: Vec<String> = codec.data_type_names().map(str::to_owned).collect();
names
.into_iter()
.map(|name| {
let codec = codec.clone();
let label: &'static str = Box::leak(name.clone().into_boxed_str());
let decode: Decode = Box::new(move |bytes: &[u8]| {
let _ = codec.decode_prefix(&name, bytes);
let _ = codec.decode(&name, bytes);
});
(label, decode)
})
.collect()
}
#[cfg(not(feature = "fom"))]
fn fom_decoders() -> Vec<Decoder> {
Vec::new()
}
fn hostile_counts() -> Vec<Vec<u8>> {
let mut inputs = Vec::new();
for count in [0x7fff_ffffu32, 0x7fff_fff0, 0x0100_0000, 0x0000_ffff, 0x8000_0000, 0xffff_ffff, 17] {
for prefix in [0usize, 1, 4, 8] {
for tail in [0usize, 3, 16, 64] {
let mut input = vec![0u8; prefix];
input.extend_from_slice(&count.to_be_bytes());
input.extend(std::iter::repeat_n(0x7f, tail));
inputs.push(input);
}
}
}
let mut nested = Vec::new();
for _ in 0..16 {
nested.extend_from_slice(&0x7fff_ffffu32.to_be_bytes());
}
inputs.push(nested);
inputs
}
fn allowance(len: usize) -> usize {
64 * 1024 + 128 * len
}
fn random_input(rng: &mut Rng) -> Vec<u8> {
let len = rng.size(512);
let mut input = rng.bytes(len);
for at in (0..input.len()).step_by(4) {
if rng.one_in(2) {
input[at] = 0;
if at + 3 < input.len() {
input[at + 1] = 0;
input[at + 2] = 0;
input[at + 3] = rng.below(5) as u8;
}
}
}
input
}
#[test]
fn decoding_allocates_in_proportion_to_the_input_not_to_its_counts() {
let mut decoders = typed_decoders();
decoders.extend(dynamic_decoders());
decoders.extend(fom_decoders());
let witness = allocated(|| drop(Vec::<u8>::with_capacity(1 << 31)));
assert!(witness > allowance(64), "the allocations are not counted: {witness}");
let mut most = 0;
for input in hostile_counts() {
for (name, decode) in &decoders {
let used = allocated(|| decode(&input));
assert!(
used <= allowance(input.len()),
"{name}: {used} octets for {} octets of input",
input.len()
);
most = most.max(used);
}
}
eprintln!("encoding-allocation: hostile counts cost at most {most} octets");
let mut drawer = Rng::new(0x0a11_0ca7_e5ee_d500);
let seeds: Vec<Vec<u8>> = (0..256).map(|_| random_input(&mut drawer)).collect();
let mut worst = (0usize, 0usize, "");
let report = Campaign::new("encoding-allocation", 20000).run(|rng: &mut Rng, _| {
let mut input = if rng.one_in(2) {
let mut input = rng.pick(&seeds).clone();
mutate(rng, &mut input);
input
} else {
random_input(rng)
};
if rng.one_in(8) && input.len() >= 4 {
let at = rng.below(input.len() - 3);
input[at..at + 4].copy_from_slice(&0x7fff_ffffu32.to_be_bytes());
}
let (name, decode) = &decoders[rng.below(decoders.len())];
let used = allocated(|| decode(&input));
assert!(used <= allowance(input.len()), "{name}: {used} octets for {} octets of input", input.len());
if used > worst.0 {
worst = (used, input.len(), name);
}
});
eprintln!(
"encoding-allocation: {} inputs over {} decoders; most allocated: {} octets for {} octets ({})",
report.cases,
decoders.len(),
worst.0,
worst.1,
worst.2
);
}