Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions crates/core/src/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,27 @@ pub fn letters_to_col(s: &str) -> Option<u32> {

/// A rectangular block of cells, inclusive on both ends. Always normalised (`start <= end`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(from = "RangeRefFields")]
pub struct RangeRef {
pub start: CellRef,
pub end: CellRef,
}

/// A range as stored (`{start, end}`). A file may hold any numbers there, so loading puts the
/// corners in order and on the sheet: `height()` and `width()` subtract them unchecked (#2160).
#[derive(Deserialize)]
struct RangeRefFields {
start: CellRef,
end: CellRef,
}

impl From<RangeRefFields> for RangeRef {
fn from(r: RangeRefFields) -> Self {
let on_sheet = |c: CellRef| CellRef::new(c.row.min(MAX_ROWS - 1), c.col.min(MAX_COLS - 1));
RangeRef::new(on_sheet(r.start), on_sheet(r.end))
}
}

impl RangeRef {
pub fn new(a: CellRef, b: CellRef) -> Self {
RangeRef { start: CellRef::new(a.row.min(b.row), a.col.min(b.col)), end: CellRef::new(a.row.max(b.row), a.col.max(b.col)) }
Expand Down Expand Up @@ -330,6 +346,19 @@ mod tests {
assert_eq!(split_areas(""), [""]);
}

#[test]
fn a_loaded_range_is_ordered_and_on_the_sheet() {
// #2160: a file can hold any corners; `height()` subtracts them unchecked.
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":4000000000,"col":5},"end":{"row":2,"col":1}}"#).unwrap();
assert_eq!(r, RangeRef::new(CellRef::new(2, 1), CellRef::new(MAX_ROWS - 1, 5)));
assert_eq!((r.height(), r.width()), (MAX_ROWS - 2, 5));
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":9,"col":99999},"end":{"row":3,"col":0}}"#).unwrap();
assert_eq!(r, RangeRef::new(CellRef::new(3, 0), CellRef::new(9, MAX_COLS - 1)));
// What is saved loads back unchanged.
let ok = RangeRef::new(CellRef::new(1, 2), CellRef::new(7, 3));
assert_eq!(serde_json::from_str::<RangeRef>(&serde_json::to_string(&ok).unwrap()).unwrap(), ok);
}

#[test]
fn range_parse_rejects_signed_rows() -> Result<(), std::io::Error> {
assert!(RangeRef::parse("+1:+3").is_none());
Expand Down
42 changes: 42 additions & 0 deletions crates/core/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ impl fmt::Display for CellError {
}

/// A 2-D array of values (row-major). Always at least 1×1.
///
/// Indexing assumes `data` holds `rows × cols` values. Loading doesn't check that (the fields are
/// public, so a file can say anything): whoever loads values from a file checks them with
/// [`Value::is_well_formed`] and repairs what fails (#2160).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Array {
pub rows: usize,
Expand Down Expand Up @@ -208,6 +212,23 @@ impl From<Array> for Value {
}

impl Value {
/// Whether every array in this value, including arrays nested in another array's values, is
/// at least 1×1 and holds exactly `rows × cols` values, as indexing assumes. Values built in
/// code always are; values loaded from a file may not be (#2160). Walks without recursion,
/// so a deeply nested value can't overflow the stack.
pub fn is_well_formed(&self) -> bool {
let mut pending = vec![self];
while let Some(v) = pending.pop() {
if let Value::Array(a) = v {
if a.rows == 0 || a.cols == 0 || a.rows.checked_mul(a.cols) != Some(a.data.len()) {
return false;
}
pending.extend(a.data.iter().filter(|x| matches!(x, Value::Array(_))));
}
}
true
}

/// A number, or `#NUM!` when it is NaN or infinite (Excel never stores those).
pub fn number(v: f64) -> Value {
if v.is_finite() { Value::Number(if v == 0.0 { 0.0 } else { v }) } else { Value::Error(CellError::Num) }
Expand Down Expand Up @@ -488,6 +509,27 @@ pub fn sci_text(n: f64, sig: usize) -> String {
mod tests {
use super::*;

#[test]
fn a_loaded_array_is_checked_by_is_well_formed() {
// #2160: indexing assumes `data.len() == rows * cols`. A file can say otherwise; loading
// keeps what it says and `is_well_formed` tells the loader to repair it.
let number = |n: f64| Value::Number(n);
let loaded = |json: &str| serde_json::from_str::<Value>(json).unwrap();
for bad in [
r#"{"t":"Array","v":{"rows":3,"cols":2,"data":[{"t":"Number","v":1.0}]}}"#,
r#"{"t":"Array","v":{"rows":0,"cols":1,"data":[]}}"#,
r#"{"t":"Array","v":{"rows":18446744073709551615,"cols":2,"data":[]}}"#,
// Nested in a well-formed array.
r#"{"t":"Array","v":{"rows":1,"cols":2,"data":[{"t":"Number","v":1.0},{"t":"Array","v":{"rows":2,"cols":2,"data":[]}}]}}"#,
] {
assert!(!loaded(bad).is_well_formed(), "{bad}");
}
let ok = Value::from(Array::new(1, 2, vec![number(1.0), Value::from(Array::scalar(number(2.0)))]).unwrap());
let back = loaded(&serde_json::to_string(&ok).unwrap());
assert_eq!(back, ok, "what is saved loads back unchanged");
assert!(back.is_well_formed() && number(1.0).is_well_formed() && Value::Empty.is_well_formed());
}

#[test]
fn number_text() {
assert_eq!(number_to_text(1.0), "1");
Expand Down
47 changes: 41 additions & 6 deletions crates/engine/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,14 +249,48 @@ pub fn enforce_python_limits(wb: &mut Workbook) -> Vec<String> {
/// A Python result a file may hold: a scalar, or an array whose size matches its data and has at
/// most [`gridcraft_model::python::MAX_RESULT_CELLS`] cells.
fn sane_python_output(v: &gridcraft_core::Value) -> bool {
match v {
gridcraft_core::Value::Array(a) => {
a.rows >= 1
&& a.cols >= 1
&& a.rows.checked_mul(a.cols).is_some_and(|n| n == a.data.len() && n <= gridcraft_model::python::MAX_RESULT_CELLS)
v.is_well_formed()
&& match v {
gridcraft_core::Value::Array(a) => a.data.len() <= gridcraft_model::python::MAX_RESULT_CELLS,
_ => true,
}
}

/// A JSON workbook keeps cell values as written, and an array in one may not hold the
/// `rows × cols` values that indexing assumes (#2160). Like Excel repairing a damaged file, the
/// open goes on: such a value is dropped, so the cell is empty until its formula, if it has one,
/// calculates again (opening recalculates). Python results are checked by
/// [`enforce_python_limits`]. Runs before anything reads the cells. Returns the warnings.
fn drop_damaged_values(wb: &mut Workbook) -> Vec<String> {
let mut damaged = Vec::new();
let mut with_formula = 0usize;
for si in 0..wb.sheets.len() {
let Some(sh) = wb.sheets.get(si) else { continue };
let cells: Vec<CellRef> = sh.cells.iter().filter(|(_, cell)| !cell.value.is_well_formed()).map(|(c, _)| c).collect();
if cells.is_empty() {
continue;
}
let name = sh.name.clone();
let Some(sh) = wb.sheet_mut(si) else { continue };
for c in cells {
if let Some(cell) = sh.cells.get_mut(c) {
cell.value = gridcraft_core::Value::Empty;
if cell.formula.is_some() {
with_formula += 1;
}
}
damaged.push(format!("{name}!{}", c.a1()));
}
_ => true,
}
let Some(first) = damaged.first() else { return vec![] };
let more = if damaged.len() > 1 { format!(" (and {} more)", damaged.len() - 1) } else { String::new() };
// Only a cell with a formula gets its value back; a constant's value is gone.
let tail = match with_formula {
0 => "",
n if n == damaged.len() => "; a formula there calculates it again",
_ => "; the cells with a formula calculate theirs again",
};
vec![format!("The value saved in {first}{more} was damaged, so it was dropped{tail}.")]
}

/// Parses bytes that aren't encrypted, as they are.
Expand Down Expand Up @@ -317,6 +351,7 @@ fn read_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
if dropped > 0 {
warnings.push(format!("{name}: {dropped} cells outside the 1,048,576 × 16,384 grid were dropped"));
}
warnings.extend(drop_damaged_values(&mut wb));
Ok((wb, warnings))
}
Some(FileKind::Sylk) => {
Expand Down
47 changes: 47 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4167,6 +4167,53 @@ fn json_import_rebuilds_cell_store_bands_and_counts() {
assert_eq!(cells.len(), 0);
}

#[test]
fn json_import_orders_ranges_and_repairs_arrays() {
// #2160: ranges and arrays were taken from a JSON workbook as written. A merge with its
// corners swapped (or off the sheet) wrapped `height()` to about 4.29e9 in release, and an
// array shorter than rows x cols was indexed past its end. Like Excel with a damaged file,
// the open goes on: ranges are put in order on the sheet, damaged values are dropped.
let mut s = s();
s.execute("home.mergeCells", json!({"range": "B2:C3"})).unwrap();
s.execute("cell.set", json!({"cell": "A5", "input": "keep"})).unwrap();
s.execute("cell.set", json!({"cell": "B5", "input": "=LEN(A5)"})).unwrap();
s.execute("cell.set", json!({"cell": "C5", "input": "7"})).unwrap();
let wb = &s.doc().unwrap().wb;
let good: serde_json::Value = serde_json::to_value(&**wb).unwrap();

let mut file = good.clone();
file["sheets"][0]["merges"][0] = json!({"start": {"row": 4_000_000_000u32, "col": 5}, "end": {"row": 2, "col": 1}});
let (back, _) = crate::io::open_bytes("book.json", &serde_json::to_vec(&file).unwrap()).unwrap();
let merge = back.active().unwrap().merges[0];
assert_eq!(merge, gridcraft_core::RangeRef::parse("B3:F1048576").unwrap());
assert_eq!(merge.height(), 1_048_574);

// B5 (a formula) caches an array that claims a million values and holds none; C5 (a
// constant) holds a well-formed array with a damaged one nested in it.
let mut file = good;
let band = file["sheets"][0]["cells"]["bands"].as_object_mut().unwrap().values_mut().next().unwrap();
band["rows"]["4"]["1"]["value"] = json!({"t": "Array", "v": {"rows": 1000, "cols": 1000, "data": []}});
let nested = json!({"t": "Array", "v": {"rows": 2, "cols": 2, "data": [{"t": "Number", "v": 1.0}]}});
band["rows"]["4"]["2"]["value"] = json!({"t": "Array", "v": {"rows": 1, "cols": 2, "data": [{"t": "Number", "v": 1.0}, nested]}});
let bytes = serde_json::to_vec(&file).unwrap();
let (back, warnings) = crate::io::open_bytes("book.json", &bytes).unwrap();
let sh = back.active().unwrap();
let value = |a: &str| sh.cell(CellRef::parse(a).unwrap()).map(|c| c.value.clone());
assert_eq!(value("B5"), Some(Value::Empty), "the damaged cached result is dropped");
assert_eq!(value("C5"), Some(Value::Empty), "a damaged array nested in another is found");
assert_eq!(value("A5"), Some(Value::text("keep")), "the rest of the sheet loads");
assert!(sh.cell(CellRef::parse("B5").unwrap()).unwrap().formula.is_some(), "the formula stays");
assert_eq!(
warnings.iter().filter(|w| w.contains("was damaged")).collect::<Vec<_>>(),
[&"The value saved in Sheet1!B5 (and 1 more) was damaged, so it was dropped; the cells with a formula calculate theirs again.".to_string()]
);

// Opened in the session, the formula calculates its value again.
s.execute("file.open", json!({"name": "book.json", "base64": crate::io::base64_encode(&bytes)})).unwrap();
assert_eq!(v(&s, "B5"), Value::Number(4.0));
assert_eq!(v(&s, "C5"), Value::Empty);
}

#[test]
fn notes_comments_and_links_survive_a_json_save() {
let mut s = s();
Expand Down
18 changes: 18 additions & 0 deletions crates/engine/src/tests/python_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,24 @@ fn rebuilt_results_have_a_budget_across_the_workbook() {
assert!(warnings.iter().any(|w| w.contains("Python")), "{warnings:?}");
}

#[test]
fn a_python_result_with_a_damaged_nested_array_is_dropped() {
// #2160: the result is 1×2 as it says, but its second value is an array that claims four
// values and holds one. Indexing that would read past its end, so the result is dropped, as
// a result of the wrong shape is.
let (mut s, _) = build();
let bytes = save(&mut s, "json");
let mut wb: Workbook = serde_json::from_slice(&bytes).unwrap();
let sh = wb.sheet_mut(0).unwrap();
let c1 = sh.cells.get_mut(CellRef::parse("C1").unwrap()).unwrap();
let out = Arc::make_mut(c1.py.as_mut().unwrap()).output.as_mut().unwrap();
let damaged = Value::Array(Arc::new(Array { rows: 2, cols: 2, data: vec![Value::Number(1.0)] }));
out.value = Value::Array(Arc::new(Array { rows: 1, cols: 2, data: vec![Value::Number(1.0), damaged] }));
let (wb, _) = crate::io::open_bytes("evil.json", &serde_json::to_vec(&wb).unwrap()).unwrap();
let c1 = wb.sheet(0).unwrap().cell(CellRef::parse("C1").unwrap()).unwrap();
assert!(c1.py.as_ref().unwrap().output.is_none(), "the damaged result is dropped");
}

#[test]
fn hostile_python_content_in_files_is_capped() {
let (mut s, _) = build();
Expand Down
Loading