Hash :
8a5e7aae
Author :
Date :
2017-05-22T12:53:44
varint: fix computation for remaining buffer space When encoding varints to a buffer, we want to remain sure that the required buffer space does not exceed what is actually available. Our current check does not do the right thing, though, in that it does not honor that our `pos` variable counts the position down instead of up. As such, we will require too much memory for small varints and not enough memory for big varints. Fix the issue by correctly calculating the required size as `(sizeof(varint) - pos)`. Add a test which failed before.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "varint.h"
uintmax_t git_decode_varint(const unsigned char *bufp, size_t *varint_len)
{
const unsigned char *buf = bufp;
unsigned char c = *buf++;
uintmax_t val = c & 127;
while (c & 128) {
val += 1;
if (!val || MSB(val, 7)) {
/* This is not a valid varint_len, so it signals
the error */
*varint_len = 0;
return 0; /* overflow */
}
c = *buf++;
val = (val << 7) + (c & 127);
}
*varint_len = buf - bufp;
return val;
}
int git_encode_varint(unsigned char *buf, size_t bufsize, uintmax_t value)
{
unsigned char varint[16];
unsigned pos = sizeof(varint) - 1;
varint[pos] = value & 127;
while (value >>= 7)
varint[--pos] = 128 | (--value & 127);
if (buf) {
if (bufsize < (sizeof(varint) - pos))
return -1;
memcpy(buf, varint + pos, sizeof(varint) - pos);
}
return sizeof(varint) - pos;
}