llvm.org GIT mirror llvm / 9885a59
[Support] add decodeSLEB128() We already have routines to encode SLEB128 as well as encode/decode ULEB128. This last function fills out the matrix. I'll need this for some llvm-objdump work I am doing. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@217830 91177308-0d34-0410-b5e6-96231b3b80d8 Nick Kledzik 5 years ago
2 changed file(s) with 56 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
8989 return Value;
9090 }
9191
92 /// Utility function to decode a SLEB128 value.
93 inline int64_t decodeSLEB128(const uint8_t *p, unsigned *n = nullptr) {
94 const uint8_t *orig_p = p;
95 int64_t Value = 0;
96 unsigned Shift = 0;
97 uint8_t Byte;
98 do {
99 Byte = *p++;
100 Value |= ((Byte & 0x7f) << Shift);
101 Shift += 7;
102 } while (Byte >= 128);
103 // Sign extend negative numbers.
104 if (Byte & 0x40)
105 Value |= (-1LL) << Shift;
106 if (n)
107 *n = (unsigned)(p - orig_p);
108 return Value;
109 }
110
111
92112 /// Utility function to get the size of the ULEB128-encoded value.
93113 extern unsigned getULEB128Size(uint64_t Value);
94114
118118 #undef EXPECT_DECODE_ULEB128_EQ
119119 }
120120
121 TEST(LEB128Test, DecodeSLEB128) {
122 #define EXPECT_DECODE_SLEB128_EQ(EXPECTED, VALUE) \
123 do { \
124 unsigned ActualSize = 0; \
125 int64_t Actual = decodeSLEB128(reinterpret_cast(VALUE), \
126 &ActualSize); \
127 EXPECT_EQ(sizeof(VALUE) - 1, ActualSize); \
128 EXPECT_EQ(EXPECTED, Actual); \
129 } while (0)
130
131 // Decode SLEB128
132 EXPECT_DECODE_SLEB128_EQ(0L, "\x00");
133 EXPECT_DECODE_SLEB128_EQ(1L, "\x01");
134 EXPECT_DECODE_SLEB128_EQ(63L, "\x3f");
135 EXPECT_DECODE_SLEB128_EQ(-64L, "\x40");
136 EXPECT_DECODE_SLEB128_EQ(-63L, "\x41");
137 EXPECT_DECODE_SLEB128_EQ(-1L, "\x7f");
138 EXPECT_DECODE_SLEB128_EQ(128L, "\x80\x01");
139 EXPECT_DECODE_SLEB128_EQ(129L, "\x81\x01");
140 EXPECT_DECODE_SLEB128_EQ(-129L, "\xff\x7e");
141 EXPECT_DECODE_SLEB128_EQ(-128L, "\x80\x7f");
142 EXPECT_DECODE_SLEB128_EQ(-127L, "\x81\x7f");
143 EXPECT_DECODE_SLEB128_EQ(64L, "\xc0\x00");
144 EXPECT_DECODE_SLEB128_EQ(-12345L, "\xc7\x9f\x7f");
145
146 // Decode unnormalized SLEB128 with extra padding bytes.
147 EXPECT_DECODE_SLEB128_EQ(0L, "\x80\x00");
148 EXPECT_DECODE_SLEB128_EQ(0L, "\x80\x80\x00");
149 EXPECT_DECODE_SLEB128_EQ(0x7fL, "\xff\x00");
150 EXPECT_DECODE_SLEB128_EQ(0x7fL, "\xff\x80\x00");
151 EXPECT_DECODE_SLEB128_EQ(0x80L, "\x80\x81\x00");
152 EXPECT_DECODE_SLEB128_EQ(0x80L, "\x80\x81\x80\x00");
153
154 #undef EXPECT_DECODE_SLEB128_EQ
155 }
156
121157 TEST(LEB128Test, SLEB128Size) {
122158 // Positive Value Testing Plan:
123159 // (1) 128 ^ n - 1 ........ need (n+1) bytes