Skip to content

Commit

Permalink
vlc_bits: fix integer overflow in signed ExpGolomb code
Browse files Browse the repository at this point in the history
When bs_read_ue() returned 2^32-1, computing (val + 1) as 'int'
overflowed. With this patch, the conversion from unsigned to signed is
performed after the division by two, so that the absolute value range
is always within limits of the signed 32-bits integer type.

Also use fast types since the function are meant to be inlined.
  • Loading branch information
Rémi Denis-Courmont committed Nov 13, 2016
1 parent 3cb2a49 commit 61eb088
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions include/vlc_bits.h
Original file line number Diff line number Diff line change
Expand Up @@ -231,22 +231,23 @@ static inline void bs_align_1( bs_t *s )
}

/* Read unsigned Exp-Golomb code */
static inline uint32_t bs_read_ue( bs_t * bs )
static inline uint_fast32_t bs_read_ue( bs_t * bs )
{
int32_t i = 0;
unsigned i = 0;

while( bs_read1( bs ) == 0 && bs->p < bs->p_end && i < 31 )
i++;

return ((uint32_t)1 << i) - 1 + bs_read( bs, i );
return (1U << i) - 1 + bs_read( bs, i );
}

/* Read signed Exp-Golomb code */
static inline int32_t bs_read_se( bs_t *s )
static inline int_fast32_t bs_read_se( bs_t *s )
{
int val = bs_read_ue( s );
uint_fast32_t val = bs_read_ue( s );

return val&0x01 ? (val+1)/2 : -(val/2);
return (val & 0x01) ? (int_fast32_t)((val + 1) / 2)
: -(int_fast32_t)(val / 2);
}

#undef bs_forward
Expand Down

0 comments on commit 61eb088

Please sign in to comment.