Skip to content

Commit

Permalink
Prevent SafeInt from throwing exceptions on bitshift overflows.
Browse files Browse the repository at this point in the history
Closes #1829.
  • Loading branch information
bbannier committed Oct 17, 2024
1 parent d9ccbdf commit 2ebe473
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
17 changes: 16 additions & 1 deletion hilti/runtime/include/safe-int.h
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
// Copyright (c) 2020-2023 by the Zeek Project. See LICENSE for details.

#pragma once
#include <algorithm>

#include <hilti/rt/exception.h>

#define SAFEINT_DISABLE_ADDRESS_OPERATOR

// Workaround for https://github.com/zeek/spicy/issues/1829 while is waiting to be merged.

namespace hilti::rt::debug {
// Forward-declare since `hilti/rt/logging.h` includes this header.
const char* location();
} // namespace hilti::rt::debug

#define SAFEINT_REMOVE_NOTHROW
#define SAFEINT_ASSERT(x) \
throw ::hilti::rt::Overflow("overflow detected", \
std::max(hilti::rt::debug::location(), static_cast<const char*>("<no location>")))

#include <hilti/rt/3rdparty/SafeInt/SafeInt.hpp>
#include <hilti/rt/exception.h>

namespace hilti::rt::integer {

Expand Down
2 changes: 2 additions & 0 deletions tests/Baseline/hilti.types.integer.shift-overflow/output
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
### BTest baseline data generated by btest-diff. Do not edit. Use "btest -U/-u" to update. Requires BTest >= 0.63.
uncaught exception hilti::rt::Overflow: overflow detected (<...>/shift-overflow.hlt:12:1-12:33)
21 changes: 21 additions & 0 deletions tests/hilti/types/integer/shift-overflow.hlt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# @TEST-DOC: Checks that overflows on bitshifts cause exceptions, regression test for #1829.
#
# TODO: Revisit this once https://github.com/dcleblanc/SafeInt/pull/64 moved forward.
#
# @TEST-EXEC-FAIL: hiltic -dj %INPUT >output 2>&1
# @TEST-EXEC: btest-diff output

module overflow {

import hilti;

hilti::print(uint8(0) << 8, True);
hilti::print(uint16(0) << 16, True);
hilti::print(uint32(0) << 32, True);
hilti::print(0 << 64, True);
hilti::print(uint8(0) << 8, True);
hilti::print(uint16(0) << 16, True);
hilti::print(uint32(0) << 32, True);
hilti::print(0 << 64, True);

}

0 comments on commit 2ebe473

Please sign in to comment.