fix(parser): calculate array reference pitches without overflow

Use i64 coordinate differences and checked i32 pitches in both scans and full reads. Reject nonpositive counts, malformed coordinate records, and pitches that cannot fit the packed schema.
This commit is contained in:
Jan Petykiewicz 2026-11-14 14:39:01 -08:00
commit ae33c4948b

View file

@ -886,6 +886,9 @@ fn read_ref<'a>(
angle_rad = _angle_deg.to_radians();
},
records::RTAG_COLROW => {
if header.data_size != 4 {
return fail(input, "COLROW must contain two counts".to_string());
}
let mut _colrow;
(input, _colrow) = COLROW::read_data(input, header.data_size)?;
colrow = Some((_colrow.next().unwrap(), _colrow.next().unwrap()));
@ -899,6 +902,10 @@ fn read_ref<'a>(
(input, header) = RecordHeader::read(input)?;
}
let expected_xy_size = if is_aref { 24 } else { 8 };
if header.data_size != expected_xy_size {
return fail(input, format!("Expected {expected_xy_size} bytes of reference coordinates, got {}", header.data_size));
}
let (input, mut xy_iter) = XY::read_data(input, header.data_size)?;
let xx = xy_iter.next().unwrap();
let yy = xy_iter.next().unwrap();
@ -910,11 +917,20 @@ fn read_ref<'a>(
return fail(input, "AREF without COLROW before XY".to_string())
}
let (count0, count1) = colrow.unwrap();
if count0 <= 0 || count1 <= 0 {
return fail(input, "AREF column and row counts must be positive".to_string());
}
let x0a = (xy_iter.next().unwrap() - xx) / (count0 as i32);
let y0a = (xy_iter.next().unwrap() - yy) / (count0 as i32);
let x1a = (xy_iter.next().unwrap() - xx) / (count1 as i32);
let y1a = (xy_iter.next().unwrap() - yy) / (count1 as i32);
let pitch = |end: i32, origin: i32, count: i16| {
let value = (i64::from(end) - i64::from(origin)) / i64::from(count);
i32::try_from(value).map_err(|_| (input, crate::basic::ErrType::Failed(
"AREF pitch exceeds signed 32-bit coordinate range".to_string()
)))
};
let x0a = pitch(xy_iter.next().unwrap(), xx, count0)?;
let y0a = pitch(xy_iter.next().unwrap(), yy, count0)?;
let x1a = pitch(xy_iter.next().unwrap(), xx, count1)?;
let y1a = pitch(xy_iter.next().unwrap(), yy, count1)?;
let xy0a = ((x0a as u32 as u64) << 32) | (y0a as u32 as u64);
let xy1a = ((x1a as u32 as u64) << 32) | (y1a as u32 as u64);