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 <cstring>
20 #include <inttypes.h>
21 #include <limits.h>
22
23 #include <berberis/base/checks.h>
24
25 namespace nogrod {
26
Leb128Decoder(const uint8_t * buffer,size_t size)27 Leb128Decoder::Leb128Decoder(const uint8_t* buffer, size_t size) : buffer_(buffer), size_(size) {}
28
29 // Returns number of bytes it took do decode the value, 0 if decode has failed.
Decode(size_t offset,uint64_t * result) const30 size_t Leb128Decoder::Decode(size_t offset, uint64_t* result) const {
31 return DecodeLeb128(buffer_ + offset, size_ - offset, result);
32 }
33
DecodeLeb128(const uint8_t * buf,uint64_t buf_size,uint64_t * result)34 size_t DecodeLeb128(const uint8_t* buf, uint64_t buf_size, uint64_t* result) {
35 uint64_t value = 0;
36 size_t shift = 0;
37 size_t size = 0;
38
39 uint8_t byte;
40
41 do {
42 if (size >= buf_size) {
43 FATAL("leb128: ran out of bounds while reading value at offset=%zd (buf_size=%" PRId64 ")",
44 size,
45 buf_size);
46 }
47
48 if (shift >= CHAR_BIT * sizeof(uint64_t)) {
49 FATAL("leb128: the value at offset %zd is too big (does not fit into uint64_t), shift=%zd",
50 size,
51 shift);
52 }
53
54 byte = buf[size++];
55
56 value += static_cast<uint64_t>(byte & 0x7f) << shift;
57
58 shift += 7;
59 } while ((byte & 0x80) != 0);
60
61 *result = value;
62 return size;
63 }
64
DecodeSleb128(const uint8_t * buf,uint64_t buf_size,int64_t * result)65 size_t DecodeSleb128(const uint8_t* buf, uint64_t buf_size, int64_t* result) {
66 uint64_t value = 0;
67 size_t shift = 0;
68 size_t size = 0;
69
70 uint8_t byte;
71
72 do {
73 if (size >= buf_size) {
74 FATAL("sleb128: ran out of bounds while reading value at offset=%zd (buf_size=%" PRId64 ")",
75 size,
76 buf_size);
77 }
78
79 if (shift >= CHAR_BIT * sizeof(uint64_t)) {
80 FATAL("sleb128: the value at offset %zd is too big (does not fit into uint64_t), shift=%zd",
81 size,
82 shift);
83 }
84
85 byte = buf[size++];
86
87 value += static_cast<uint64_t>(byte & 0x7f) << shift;
88
89 shift += 7;
90 } while ((byte & 0x80) != 0);
91
92 // sign extent is not applicable if shift is out of bounds of uint64_t
93 if (shift < (sizeof(uint64_t) * CHAR_BIT) && (byte & 0x40) != 0) {
94 value |= -(static_cast<uint64_t>(1) << shift);
95 }
96
97 memcpy(result, &value, sizeof(*result));
98 return size;
99 }
100
101 } // namespace nogrod
102