From f32854c809ab261c07f09f5f27435daadccc2728 Mon Sep 17 00:00:00 2001 From: Fabian Giesen Date: Tue, 6 Sep 2016 11:58:00 -0700 Subject: [PATCH] stb_vorbis: Fix handling of negative numbers in ilog. For negative n, the original code went down the "n < (1<<4)" path and performed an out-of-bounds array access. Fix the code to agree with section 9.2.1 of the Vorbis spec. (Verified by exhaustive testing of all 32-bit ints.) Fixes issue #355. --- stb_vorbis.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/stb_vorbis.c b/stb_vorbis.c index c4f24d5..cb71767 100644 --- a/stb_vorbis.c +++ b/stb_vorbis.c @@ -986,17 +986,18 @@ static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; + if (n < 0) return 0; // signed n returns 0 + // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) - if (n < (1 << 4)) return 0 + log2_4[n ]; - else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; + if (n < (1 << 4)) return 0 + log2_4[n ]; + else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) - if (n < (1 << 19)) return 15 + log2_4[n >> 15]; + if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; - else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; - else if (n < (1 << 31)) return 30 + log2_4[n >> 30]; - else return 0; // signed n returns 0 + else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; + else return 30 + log2_4[n >> 30]; } #ifndef M_PI