Просмотр исходного кода

Explorer: Fuzzer issue around divide-by-zero (#2735)

fail with a runtime error, preventing the divide-by-zero from actually running.

Issue #2731
Amr Hesham 3 лет назад
Родитель
Сommit
29cdeb0d6b

+ 16 - 6
explorer/interpreter/interpreter.cpp

@@ -218,12 +218,22 @@ auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> /*static_type*/,
     case Operator::Mul:
       return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
                                    cast<IntValue>(*args[1]).value());
-    case Operator::Div:
-      return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() /
-                                   cast<IntValue>(*args[1]).value());
-    case Operator::Mod:
-      return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() %
-                                   cast<IntValue>(*args[1]).value());
+    case Operator::Div: {
+      const auto& lhs = cast<IntValue>(*args[0]).value();
+      const auto& rhs = cast<IntValue>(*args[1]).value();
+      if (rhs == 0) {
+        return ProgramError(source_loc) << "division by zero";
+      }
+      return arena_->New<IntValue>(lhs / rhs);
+    }
+    case Operator::Mod: {
+      const auto& lhs = cast<IntValue>(*args[0]).value();
+      const auto& rhs = cast<IntValue>(*args[1]).value();
+      if (rhs == 0) {
+        return ProgramError(source_loc) << "division by zero";
+      }
+      return arena_->New<IntValue>(lhs % rhs);
+    }
     case Operator::Not:
       return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
     case Operator::And:

+ 15 - 0
explorer/testdata/operators/fail_div_by_zero.carbon

@@ -0,0 +1,15 @@
+// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+// Exceptions. See /LICENSE for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+// AUTOUPDATE
+// RUN: %{not} %{explorer-run}
+// RUN: %{not} %{explorer-run-trace}
+
+package ExplorerTest api;
+
+fn Main() -> i32 {
+  // CHECK:STDERR: RUNTIME ERROR: {{.*}}/explorer/testdata/operators/fail_div_by_zero.carbon:[[@LINE+1]]: division by zero
+  var a: auto = 5 / 0;
+  return 0;
+}

+ 15 - 0
explorer/testdata/operators/fail_mod_by_zero.carbon

@@ -0,0 +1,15 @@
+// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+// Exceptions. See /LICENSE for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+// AUTOUPDATE
+// RUN: %{not} %{explorer-run}
+// RUN: %{not} %{explorer-run-trace}
+
+package ExplorerTest api;
+
+fn Main() -> i32 {
+  // CHECK:STDERR: RUNTIME ERROR: {{.*}}/explorer/testdata/operators/fail_mod_by_zero.carbon:[[@LINE+1]]: division by zero
+  var a: auto = 5 % 0;
+  return 0;
+}