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 uptr uptr_bits
= 8 * sizeof(uptr
);
29 while (v
>> uptr_bits
) {
33 return r
+ MostSignificantSetBitIndex(v
) + 1;
36 TYPED_TEST(Leb128Test
, SignedOverflow
) {
37 using T
= typename
std::make_signed
<TypeParam
>::type
;
38 u8 buffer
[16] = {255};
40 EXPECT_EQ(buffer
+ 1, EncodeSLEB128(v
, buffer
, buffer
+ 1));
41 EXPECT_EQ(buffer
+ 1, DecodeSLEB128(buffer
, buffer
+ 1, &v
));
44 TYPED_TEST(Leb128Test
, Signed
) {
45 using T
= typename
std::make_signed
<TypeParam
>::type
;
47 for (int i
= 0; i
< 100; ++i
) {
49 u8
* p
= EncodeSLEB128(v
, std::begin(buffer
), std::end(buffer
));
50 EXPECT_EQ(int(BitsNeeded(v
< 0 ? (-v
- 1) : v
) + 6 + 1) / 7, p
- buffer
)
53 u8
* p2
= DecodeSLEB128(std::begin(buffer
), std::end(buffer
), &v2
);
56 v
= -TypeParam(v
) * 3u + 1u;
60 TYPED_TEST(Leb128Test
, UnsignedOverflow
) {
62 u8 buffer
[16] = {255};
64 EXPECT_EQ(buffer
+ 1, EncodeULEB128(v
, buffer
, buffer
+ 1));
65 EXPECT_EQ(buffer
+ 1, DecodeULEB128(buffer
, buffer
+ 1, &v
));
68 TYPED_TEST(Leb128Test
, Unsigned
) {
71 for (int i
= 0; i
< 100; ++i
) {
73 u8
* p
= EncodeULEB128(v
, std::begin(buffer
), std::end(buffer
));
74 EXPECT_EQ(int(BitsNeeded(v
) + 6) / 7, p
- buffer
);
76 u8
* p2
= DecodeULEB128(std::begin(buffer
), std::end(buffer
), &v2
);
83 } // namespace __sanitizer