1 //===-- sanitizer_leb128.cpp ------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
8 #include "sanitizer_common/sanitizer_leb128.h"
10 #include <type_traits>
12 #include "gtest/gtest.h"
13 #include "sanitizer_common/sanitizer_common.h"
14 #include "sanitizer_internal_defs.h"
16 namespace __sanitizer
{
19 class Leb128Test
: public ::testing::Test
{};
21 using Leb128TestTypes
= ::testing::Types
<u8
, u16
, u32
, u64
>;
22 TYPED_TEST_SUITE(Leb128Test
, Leb128TestTypes
, );
24 static uptr
BitsNeeded(u64 v
) {
28 if (sizeof(uptr
) != sizeof(u64
)) {
29 uptr uptr_bits
= 8 * sizeof(uptr
);
30 while (v
>> uptr_bits
) {
35 return r
+ MostSignificantSetBitIndex(v
) + 1;
38 TYPED_TEST(Leb128Test
, SignedOverflow
) {
39 using T
= typename
std::make_signed
<TypeParam
>::type
;
40 u8 buffer
[16] = {255};
42 EXPECT_EQ(buffer
+ 1, EncodeSLEB128(v
, buffer
, buffer
+ 1));
43 EXPECT_EQ(buffer
+ 1, DecodeSLEB128(buffer
, buffer
+ 1, &v
));
46 TYPED_TEST(Leb128Test
, Signed
) {
47 using T
= typename
std::make_signed
<TypeParam
>::type
;
49 for (int i
= 0; i
< 100; ++i
) {
51 u8
* p
= EncodeSLEB128(v
, std::begin(buffer
), std::end(buffer
));
52 EXPECT_EQ(int(BitsNeeded(v
< 0 ? (-v
- 1) : v
) + 6 + 1) / 7, p
- buffer
)
55 u8
* p2
= DecodeSLEB128(std::begin(buffer
), std::end(buffer
), &v2
);
58 v
= -TypeParam(v
) * 3u + 1u;
62 TYPED_TEST(Leb128Test
, UnsignedOverflow
) {
64 u8 buffer
[16] = {255};
66 EXPECT_EQ(buffer
+ 1, EncodeULEB128(v
, buffer
, buffer
+ 1));
67 EXPECT_EQ(buffer
+ 1, DecodeULEB128(buffer
, buffer
+ 1, &v
));
70 TYPED_TEST(Leb128Test
, Unsigned
) {
73 for (int i
= 0; i
< 100; ++i
) {
75 u8
* p
= EncodeULEB128(v
, std::begin(buffer
), std::end(buffer
));
76 EXPECT_EQ(int(BitsNeeded(v
) + 6) / 7, p
- buffer
);
78 u8
* p2
= DecodeULEB128(std::begin(buffer
), std::end(buffer
), &v2
);
85 } // namespace __sanitizer