Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
avoid out-of-bound write (#49)
  • Loading branch information
eblanca authored and njh committed Apr 4, 2017
1 parent 0f6fc9c commit 5588681
Showing 1 changed file with 35 additions and 26 deletions.
61 changes: 35 additions & 26 deletions libtwolame/bitbuffer_inline.h
Expand Up @@ -24,20 +24,24 @@
/* write 1 bit from the bit stream */
static inline void buffer_put1bit(bit_stream * bs, int bit)
{
bs->totbit++;
if (bs->buf_byte_idx < bs->buf_size) {
bs->totbit++;

bs->buf[bs->buf_byte_idx] |= (bit & 0x1) << (bs->buf_bit_idx - 1);
bs->buf_bit_idx--;
if (!bs->buf_bit_idx) {
bs->buf_bit_idx = 8;
bs->buf_byte_idx++;
if (bs->buf_byte_idx >= bs->buf_size) {
// empty_buffer (bs, minimum);
fprintf(stderr, "buffer_put1bit: error. bit_stream buffer needs to be bigger\n");
return;
bs->buf[bs->buf_byte_idx] |= (bit & 0x1) << (bs->buf_bit_idx - 1);
bs->buf_bit_idx--;
if (!bs->buf_bit_idx) {
bs->buf_bit_idx = 8;
bs->buf_byte_idx++;
if (bs->buf_byte_idx < bs->buf_size) {
bs->buf[bs->buf_byte_idx] = 0;
}
else {
fprintf(stderr, "buffer_put1bit: error. bit_stream buffer full\n");
}
}
bs->buf[bs->buf_byte_idx] = 0;
}
else
fprintf(stderr, "buffer_put1bit: error. bit_stream buffer needs to be bigger\n");
}

/* write N bits into the bit stream */
Expand All @@ -47,24 +51,29 @@ static inline void buffer_putbits(bit_stream * bs, unsigned int val, int N)
register int j = N;
register int k, tmp;

bs->totbit += N;
while (j > 0) {
k = MIN(j, bs->buf_bit_idx);
tmp = val >> (j - k);
bs->buf[bs->buf_byte_idx] |= (tmp & putmask[k]) << (bs->buf_bit_idx - k);
bs->buf_bit_idx -= k;
if (!bs->buf_bit_idx) {
bs->buf_bit_idx = 8;
bs->buf_byte_idx++;
if (bs->buf_byte_idx >= bs->buf_size) {
// empty_buffer (bs, minimum);
fprintf(stderr, "buffer_putbits: error. bit_stream buffer needs to be bigger\n");
return;
if (bs->buf_byte_idx < bs->buf_size) {
while (j > 0) {
k = MIN(j, bs->buf_bit_idx);
tmp = val >> (j - k);
bs->buf[bs->buf_byte_idx] |= (tmp & putmask[k]) << (bs->buf_bit_idx - k);
bs->buf_bit_idx -= k;
bs->totbit += k;
if (!bs->buf_bit_idx) {
bs->buf_bit_idx = 8;
bs->buf_byte_idx++;
if (bs->buf_byte_idx < bs->buf_size) {
bs->buf[bs->buf_byte_idx] = 0;
}
else {
fprintf(stderr, "buffer_putbits: error. bit_stream buffer full\n");
break;
}
}
bs->buf[bs->buf_byte_idx] = 0;
j -= k;
}
j -= k;
}
else
fprintf(stderr, "buffer_putbits: error. bit_stream buffer needs to be bigger\n");
}

// vim:ts=4:sw=4:nowrap:

0 comments on commit 5588681

Please sign in to comment.