1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "leb128.h"
18
19 #include <inttypes.h>
20 #include <limits.h>
21
22 #include <berberis/base/checks.h>
23
24 namespace nogrod {
25
Leb128Decoder(const uint8_t * buffer,size_t size)26 Leb128Decoder::Leb128Decoder(const uint8_t* buffer, size_t size) : buffer_(buffer), size_(size) {}
27
28 // Returns number of bytes it took do decode the value, 0 if decode has failed.
Decode(size_t offset,uint64_t * result) const29 size_t Leb128Decoder::Decode(size_t offset, uint64_t* result) const {
30 return DecodeLeb128(buffer_ + offset, size_ - offset, result);
31 }
32
DecodeLeb128(const uint8_t * buf,uint64_t buf_size,uint64_t * result)33 size_t DecodeLeb128(const uint8_t* buf, uint64_t buf_size, uint64_t* result) {
34 uint64_t value = 0;
35 size_t shift = 0;
36 size_t size = 0;
37
38 uint8_t byte;
39
40 do {
41 if (size >= buf_size) {
42 FATAL("leb128: ran out of bounds while reading value at offset=%zd (buf_size=%" PRId64 ")",
43 size,
44 buf_size);
45 }
46
47 if (shift >= CHAR_BIT * sizeof(uint64_t)) {
48 FATAL("leb128: the value at offset %zd is too big (does not fit into uint64_t), shift=%zd",
49 size,
50 shift);
51 }
52
53 byte = buf[size++];
54
55 value += static_cast<uint64_t>(byte & 0x7f) << shift;
56
57 shift += 7;
58 } while ((byte & 0x80) != 0);
59
60 *result = value;
61 return size;
62 }
63
DecodeSleb128(const uint8_t * buf,uint64_t buf_size,int64_t * result)64 size_t DecodeSleb128(const uint8_t* buf, uint64_t buf_size, int64_t* result) {
65 uint64_t value = 0;
66 size_t shift = 0;
67 size_t size = 0;
68
69 uint8_t byte;
70
71 do {
72 if (size >= buf_size) {
73 FATAL("sleb128: ran out of bounds while reading value at offset=%zd (buf_size=%" PRId64 ")",
74 size,
75 buf_size);
76 }
77
78 if (shift >= CHAR_BIT * sizeof(uint64_t)) {
79 FATAL("sleb128: the value at offset %zd is too big (does not fit into uint64_t), shift=%zd",
80 size,
81 shift);
82 }
83
84 byte = buf[size++];
85
86 value += static_cast<uint64_t>(byte & 0x7f) << shift;
87
88 shift += 7;
89 } while ((byte & 0x80) != 0);
90
91 // sign extent is not applicable if shift is out of bounds of uint64_t
92 if (shift < (sizeof(uint64_t) * CHAR_BIT) && (byte & 0x40) != 0) {
93 value |= -(static_cast<uint64_t>(1) << shift);
94 }
95
96 memcpy(result, &value, sizeof(*result));
97 return size;
98 }
99
100 } // namespace nogrod
101