From 3c1bb4a3f889361888c6744216008ef36257b44a Mon Sep 17 00:00:00 2001 From: "Venevtsev, Igor" Date: Mon, 18 Mar 2019 12:24:24 +0100 Subject: [PATCH] ptrOffset and ptrDiff do not truncate uint64_t to uintptr_t Change-Id: I0dcaf058ae3244ca0168580d972a19f9e4692e05 Signed-off-by: Venevtsev, Igor --- runtime/helpers/ptr_math.h | 10 ++++++++++ unit_tests/helpers/ptr_math_tests.cpp | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/runtime/helpers/ptr_math.h b/runtime/helpers/ptr_math.h index b18b5d2664..b9fedde6d4 100644 --- a/runtime/helpers/ptr_math.h +++ b/runtime/helpers/ptr_math.h @@ -23,6 +23,11 @@ inline T ptrOffset(T ptrBefore, size_t offset) { return (T)addrAfter; } +template <> +inline uint64_t ptrOffset(uint64_t ptrBefore, size_t offset) { + return ptrBefore + offset; +} + template inline size_t ptrDiff(TA ptrAfter, TB ptrBefore) { auto addrBefore = (uintptr_t)ptrBefore; @@ -30,6 +35,11 @@ inline size_t ptrDiff(TA ptrAfter, TB ptrBefore) { return addrAfter - addrBefore; } +template +inline uint64_t ptrDiff(uint64_t ptrAfter, T ptrBefore) { + return ptrAfter - ptrBefore; +} + template inline void *addrToPtr(IntegerAddressType addr) { uintptr_t correctBitnessAddress = static_cast(addr); diff --git a/unit_tests/helpers/ptr_math_tests.cpp b/unit_tests/helpers/ptr_math_tests.cpp index 8657bee1a9..2e8104cc22 100644 --- a/unit_tests/helpers/ptr_math_tests.cpp +++ b/unit_tests/helpers/ptr_math_tests.cpp @@ -45,3 +45,23 @@ TEST(PtrMath, givenCastToUint64FunctionWhenItIsCalledThenProperValueIsReturned) auto uintAddress = castToUint64(addressWithTrailingBitSet); EXPECT_EQ(uintAddress, expectedUint64Address); } + +TEST(ptrOffset, preserve64Bit) { + uint64_t ptrBefore = 0x800000000; + size_t offset = 0x1234; + auto ptrAfter = ptrOffset(ptrBefore, offset); + EXPECT_EQ(0x800001234ull, ptrAfter); +} + +TEST(ptrDiff, preserve64Bit) { + auto ptrAfter = 0x800001234ull; + + auto ptrBefore = ptrDiff(ptrAfter, (size_t)0x1234); + EXPECT_EQ(0x800000000ull, ptrBefore); + + auto ptrBefore2 = ptrDiff(ptrAfter, 0x1234); + EXPECT_EQ(0x800000000ull, ptrBefore2); + + auto ptrBefore3 = ptrDiff(ptrAfter, 0x1234ull); + EXPECT_EQ(0x800000000ull, ptrBefore3); +}