From d88fab8c004b3f2556714725bc1e9d48ec6c619f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miquel=20Sabat=C3=A9=20Sol=C3=A0?= Date: Fri, 20 Dec 2024 16:20:12 +0100 Subject: [PATCH] Prevent a division by zero MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes: 8b5feeed96b3 ("assembler: Implement and add tests for operators") Signed-off-by: Miquel Sabaté Solà --- lib/xixanta/src/assembler.rs | 51 ++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/lib/xixanta/src/assembler.rs b/lib/xixanta/src/assembler.rs index 4fd8d92..e6f3396 100644 --- a/lib/xixanta/src/assembler.rs +++ b/lib/xixanta/src/assembler.rs @@ -641,6 +641,13 @@ impl Assembler { lval * rval } OperationType::Div => { + if rval == 0 { + return Err(EvalError { + line: node.value.line, + global: false, + message: "attempting to divide by zero".to_string(), + }); + } let lval = self.evaluate_node(node.left.as_ref().unwrap())?.value(); lval / rval } @@ -1994,6 +2001,50 @@ ldx #+Value assert_eq!(pos.bytes[2], 0x00); } + #[test] + fn divide_by_zero() { + let mut asm = Assembler::new(EMPTY.to_vec()); + asm.mappings[0].segments[0].bundles = minimal_header(); + asm.mappings[0].offset = 6; + asm.current_mapping = 1; + let res = &asm + .assemble( + std::env::current_dir().unwrap().to_path_buf(), + r#"Value = 0 +ldx #(2 / Value) +"# + .as_bytes(), + ) + .unwrap_err(); + + assert_eq!( + res.first().unwrap().to_string(), + "attempting to divide by zero (line 2)" + ); + } + + #[test] + fn bad_shift() { + let mut asm = Assembler::new(EMPTY.to_vec()); + asm.mappings[0].segments[0].bundles = minimal_header(); + asm.mappings[0].offset = 6; + asm.current_mapping = 1; + let res = &asm + .assemble( + std::env::current_dir().unwrap().to_path_buf(), + r#"Value = #$11 +ldx #(2 << Value) +"# + .as_bytes(), + ) + .unwrap_err(); + + assert_eq!( + res.first().unwrap().to_string(), + "shift operator too big (line 2)" + ); + } + // Regular instructions #[test]