Skip to content

Commit 66cde0b

Browse files
committed
Fixed: Possible out of bounds read in lzp_decode_block. Mark exit branches as unlikely.
1 parent 5174b4e commit 66cde0b

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/libbz3.c

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,18 @@
1818
*/
1919

2020
#include "libbz3.h"
21-
2221
#include <stdlib.h>
2322
#include <string.h>
24-
2523
#include "libsais.h"
2624

25+
#if defined(__GNUC__) || defined(__clang__)
26+
#define LIKELY(x) __builtin_expect(!!(x), 1)
27+
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
28+
#else
29+
#define LIKELY(x) (x)
30+
#define UNLIKELY(x) (x)
31+
#endif
32+
2733
/* CRC32 implementation. Since CRC32 generally takes less than 1% of the runtime on real-world data (e.g. the
2834
Silesia corpus), I decided against using hardware CRC32. This implementation is simple, fast, fool-proof and
2935
good enough to be used with bzip3. */
@@ -201,21 +207,23 @@ static s32 lzp_decode_block(const u8 * RESTRICT in, const u8 * in_end, s32 * RES
201207

202208
while (in < in_end && out < out_end) {
203209
u32 idx = (ctx >> 15 ^ ctx ^ ctx >> 3) & ((s32)(1 << LZP_DICTIONARY) - 1);
204-
s32 val = lut[idx];
210+
s32 val = lut[idx]; // SAFETY: guaranteed to be in-bounds by & mask.
205211
lut[idx] = (s32)(out - outs);
206212
if (*in == MATCH && val > 0) {
207213
in++;
214+
// SAFETY: 'in' is advanced here, but it may have been at last index in the case of untrusted bad data.
215+
if (UNLIKELY(in == in_end)) return -1;
208216
if (*in != 255) {
209217
s32 len = LZP_MIN_MATCH;
210218
while (1) {
211-
if (in == in_end) return -1;
219+
if (UNLIKELY(in == in_end)) return -1;
212220
len += *in;
213221
if (*in++ != 254) break;
214222
}
215223

216224
const u8 * ref = outs + val;
217225
const u8 * oe = out + len;
218-
if (oe > out_end) oe = out_end;
226+
if (UNLIKELY(oe > out_end)) oe = out_end;
219227

220228
while (out < oe) *out++ = *ref++;
221229

0 commit comments

Comments
 (0)