Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gccrs: add checks for division by zero and left shift overflow #3279

Merged
merged 1 commit into from
Dec 2, 2024
Merged
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
8 changes: 5 additions & 3 deletions gcc/rust/backend/rust-constexpr.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2929,8 +2929,13 @@ eval_store_expression (const constexpr_ctx *ctx, tree t, bool lval,
}
}

if (*non_constant_p)
return t;

/* Don't share a CONSTRUCTOR that might be changed later. */
init = unshare_constructor (init);
if (init == NULL_TREE)
return t;

if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
&& TREE_CODE (init) == CONSTRUCTOR)
Expand Down Expand Up @@ -3585,9 +3590,6 @@ eval_call_expression (const constexpr_ctx *ctx, tree t, bool lval,
result = *ctx->global->values.get (res);
if (result == NULL_TREE && !*non_constant_p)
{
if (!ctx->quiet)
error ("%<constexpr%> call flows off the end "
"of the function");
*non_constant_p = true;
}
}
Expand Down
11 changes: 11 additions & 0 deletions gcc/rust/rust-gcc.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,17 @@ arithmetic_or_logical_expression (ArithmeticOrLogicalOperator op, tree left,
if (floating_point && extended_type != NULL_TREE)
ret = convert (original_type, ret);

if (op == ArithmeticOrLogicalOperator::DIVIDE
&& (integer_zerop (right) || fixed_zerop (right)))
{
rust_error_at (location, "division by zero");
}
else if (op == ArithmeticOrLogicalOperator::LEFT_SHIFT
&& (compare_tree_int (right, TYPE_PRECISION (TREE_TYPE (ret))) >= 0))
{
rust_error_at (location, "left shift count >= width of type");
}

return ret;
}

Expand Down
14 changes: 14 additions & 0 deletions gcc/testsuite/rust/compile/issue-2394.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const A: i32 = (1 / 0);
// { dg-error "division by zero" "" { target *-*-* } .-1 }

fn main() {
let a = 1 / 0;
// { dg-error "division by zero" "" { target *-*-* } .-1 }

let b = 3;
let c = b / 0;
// { dg-error "division by zero" "" { target *-*-* } .-1 }

let a = 1 << 500;
// { dg-error "left shift count >= width of type" "" { target *-*-* } .-1 }
}
Loading