instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid= fs->cache.array[x].objectId.id;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count+=2;
}
}
return count;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid = fs->cache.array[x].objectId.id;
if (bufLen < 2)
break;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count += 2;
bufLen -= 2;
}
}
return count;
}
| 169,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
return ch;
}
Commit Message: Add a one-word sentinel value of 0x0 at the end of each buf_t chunk
This helps protect against bugs where any part of a buf_t's memory
is passed to a function that expects a NUL-terminated input.
It also closes TROVE-2016-10-001 (aka bug 20384).
CWE ID: CWE-119 | chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
CHUNK_SET_SENTINEL(ch, alloc);
return ch;
}
| 168,758 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int lz4_uncompress(const char *source, char *dest, int osize)
{
const BYTE *ip = (const BYTE *) source;
const BYTE *ref;
BYTE *op = (BYTE *) dest;
BYTE * const oend = op + osize;
BYTE *cpy;
unsigned token;
size_t length;
size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0};
#if LZ4_ARCH64
size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
#endif
while (1) {
/* get runlength */
token = *ip++;
length = (token >> ML_BITS);
if (length == RUN_MASK) {
size_t len;
len = *ip++;
for (; len == 255; length += 255)
len = *ip++;
length += len;
}
/* copy literals */
cpy = op + length;
if (unlikely(cpy > oend - COPYLENGTH)) {
/*
* Error: not enough place for another match
* (min 4) + 5 literals
*/
if (cpy != oend)
goto _output_error;
memcpy(op, ip, length);
ip += length;
break; /* EOF */
}
LZ4_WILDCOPY(ip, op, cpy);
ip -= (op - cpy);
op = cpy;
/* get offset */
LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip);
ip += 2;
/* Error: offset create reference outside destination buffer */
if (unlikely(ref < (BYTE *const) dest))
goto _output_error;
/* get matchlength */
length = token & ML_MASK;
if (length == ML_MASK) {
for (; *ip == 255; length += 255)
ip++;
length += *ip++;
}
/* copy repeated sequence */
if (unlikely((op - ref) < STEPSIZE)) {
#if LZ4_ARCH64
size_t dec64 = dec64table[op - ref];
#else
const int dec64 = 0;
#endif
op[0] = ref[0];
op[1] = ref[1];
op[2] = ref[2];
op[3] = ref[3];
op += 4;
ref += 4;
ref -= dec32table[op-ref];
PUT4(ref, op);
op += STEPSIZE - 4;
ref -= dec64;
} else {
LZ4_COPYSTEP(ref, op);
}
cpy = op + length - (STEPSIZE - 4);
if (cpy > (oend - COPYLENGTH)) {
/* Error: request to write beyond destination buffer */
if (cpy > oend)
goto _output_error;
LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH));
while (op < cpy)
*op++ = *ref++;
op = cpy;
/*
* Check EOF (should never happen, since last 5 bytes
* are supposed to be literals)
*/
if (op == oend)
goto _output_error;
continue;
}
LZ4_SECURECOPY(ref, op, cpy);
op = cpy; /* correction */
}
/* end of decoding */
return (int) (((char *)ip) - source);
/* write overflow error detected */
_output_error:
return (int) (-(((char *)ip) - source));
}
Commit Message: lz4: ensure length does not wrap
Given some pathologically compressed data, lz4 could possibly decide to
wrap a few internal variables, causing unknown things to happen. Catch
this before the wrapping happens and abort the decompression.
Reported-by: "Don A. Bailey" <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-20 | static int lz4_uncompress(const char *source, char *dest, int osize)
{
const BYTE *ip = (const BYTE *) source;
const BYTE *ref;
BYTE *op = (BYTE *) dest;
BYTE * const oend = op + osize;
BYTE *cpy;
unsigned token;
size_t length;
size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0};
#if LZ4_ARCH64
size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3};
#endif
while (1) {
/* get runlength */
token = *ip++;
length = (token >> ML_BITS);
if (length == RUN_MASK) {
size_t len;
len = *ip++;
for (; len == 255; length += 255)
len = *ip++;
if (unlikely(length > (size_t)(length + len)))
goto _output_error;
length += len;
}
/* copy literals */
cpy = op + length;
if (unlikely(cpy > oend - COPYLENGTH)) {
/*
* Error: not enough place for another match
* (min 4) + 5 literals
*/
if (cpy != oend)
goto _output_error;
memcpy(op, ip, length);
ip += length;
break; /* EOF */
}
LZ4_WILDCOPY(ip, op, cpy);
ip -= (op - cpy);
op = cpy;
/* get offset */
LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip);
ip += 2;
/* Error: offset create reference outside destination buffer */
if (unlikely(ref < (BYTE *const) dest))
goto _output_error;
/* get matchlength */
length = token & ML_MASK;
if (length == ML_MASK) {
for (; *ip == 255; length += 255)
ip++;
length += *ip++;
}
/* copy repeated sequence */
if (unlikely((op - ref) < STEPSIZE)) {
#if LZ4_ARCH64
size_t dec64 = dec64table[op - ref];
#else
const int dec64 = 0;
#endif
op[0] = ref[0];
op[1] = ref[1];
op[2] = ref[2];
op[3] = ref[3];
op += 4;
ref += 4;
ref -= dec32table[op-ref];
PUT4(ref, op);
op += STEPSIZE - 4;
ref -= dec64;
} else {
LZ4_COPYSTEP(ref, op);
}
cpy = op + length - (STEPSIZE - 4);
if (cpy > (oend - COPYLENGTH)) {
/* Error: request to write beyond destination buffer */
if (cpy > oend)
goto _output_error;
LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH));
while (op < cpy)
*op++ = *ref++;
op = cpy;
/*
* Check EOF (should never happen, since last 5 bytes
* are supposed to be literals)
*/
if (op == oend)
goto _output_error;
continue;
}
LZ4_SECURECOPY(ref, op, cpy);
op = cpy; /* correction */
}
/* end of decoding */
return (int) (((char *)ip) - source);
/* write overflow error detected */
_output_error:
return (int) (-(((char *)ip) - source));
}
| 166,301 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA,
PDFRectangle *box, PDFRectangle *cropBox,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gTrue;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(72, 72, box, 0, gFalse);
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
Commit Message:
CWE ID: CWE-20 | Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA,
PDFRectangle *box, PDFRectangle *cropBox,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gTrue;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
parser = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(72, 72, box, 0, gFalse);
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
| 164,905 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long SegmentInfo::Parse() {
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0AD7B1) { // Timecode Scale
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0489) { // Segment duration
const long status = UnserializeFloat(pReader, pos, size, m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0D80) { // MuxingApp
const long status =
UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
if (status)
return status;
} else if (id == 0x1741) { // WritingApp
const long status =
UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
if (status)
return status;
} else if (id == 0x3BA9) { // Title
const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long SegmentInfo::Parse() {
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0AD7B1) { // Timecode Scale
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0489) { // Segment duration
const long status = UnserializeFloat(pReader, pos, size, m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0D80) { // MuxingApp
const long status =
UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
if (status)
return status;
} else if (id == 0x1741) { // WritingApp
const long status =
UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
if (status)
return status;
} else if (id == 0x3BA9) { // Title
const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
const double rollover_check = m_duration * m_timecodeScale;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,842 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ContentBrowserClient::ShouldSwapProcessesForNavigation(
const GURL& current_url,
const GURL& new_url) {
return false;
}
Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances.
BUG=174943
TEST=Can't post message to CWS. See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12301013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ContentBrowserClient::ShouldSwapProcessesForNavigation(
SiteInstance* site_instance,
const GURL& current_url,
const GURL& new_url) {
return false;
}
| 171,438 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) {
cached_width_ = width;
cached_height_ = height;
gl_->ResizeCHROMIUM(width, height);
#ifdef FLIP_FRAMEBUFFER_VERTICALLY
scanline_.reset(new uint8[width * 4]);
#endif // FLIP_FRAMEBUFFER_VERTICALLY
}
Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip.
BUG=116637
TEST=manual test from bug report with ASAN
Review URL: https://chromiumcodereview.appspot.com/9617038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) {
cached_width_ = width;
cached_height_ = height;
gl_->ResizeCHROMIUM(width, height);
}
| 171,064 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
int atomic)
{
unsigned long copy;
while (len > 0) {
while (!iov->iov_len)
iov++;
copy = min_t(unsigned long, len, iov->iov_len);
if (atomic) {
if (__copy_to_user_inatomic(iov->iov_base, from, copy))
return -EFAULT;
} else {
if (copy_to_user(iov->iov_base, from, copy))
return -EFAULT;
}
from += copy;
len -= copy;
iov->iov_base += copy;
iov->iov_len -= copy;
}
return 0;
}
Commit Message: switch pipe_read() to copy_page_to_iter()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
| 169,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_entry_out outarg;
int err = -ENOMEM;
char *buf;
struct qstr name;
buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
if (!buf)
goto err;
err = -EINVAL;
if (size < sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
err = -ENAMETOOLONG;
if (outarg.namelen > FUSE_NAME_MAX)
goto err;
name.name = buf;
name.len = outarg.namelen;
err = fuse_copy_one(cs, buf, outarg.namelen + 1);
if (err)
goto err;
fuse_copy_finish(cs);
buf[outarg.namelen] = 0;
name.hash = full_name_hash(name.name, name.len);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb)
err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name);
up_read(&fc->killsb);
kfree(buf);
return err;
err:
kfree(buf);
fuse_copy_finish(cs);
return err;
}
Commit Message: fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message
FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the
message processing could overrun and result in a "kernel BUG at
fs/fuse/dev.c:629!"
Reported-by: Han-Wen Nienhuys <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
CC: [email protected]
CWE ID: CWE-119 | static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_entry_out outarg;
int err = -ENOMEM;
char *buf;
struct qstr name;
buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
if (!buf)
goto err;
err = -EINVAL;
if (size < sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
err = -ENAMETOOLONG;
if (outarg.namelen > FUSE_NAME_MAX)
goto err;
err = -EINVAL;
if (size != sizeof(outarg) + outarg.namelen + 1)
goto err;
name.name = buf;
name.len = outarg.namelen;
err = fuse_copy_one(cs, buf, outarg.namelen + 1);
if (err)
goto err;
fuse_copy_finish(cs);
buf[outarg.namelen] = 0;
name.hash = full_name_hash(name.name, name.len);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb)
err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name);
up_read(&fc->killsb);
kfree(buf);
return err;
err:
kfree(buf);
fuse_copy_finish(cs);
return err;
}
| 165,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(grapheme_strpos)
{
unsigned char *haystack, *needle;
int haystack_len, needle_len;
unsigned char *found;
long loffset = 0;
int32_t offset = 0;
int ret_pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"grapheme_strpos: unable to parse input param", 0 TSRMLS_CC );
RETURN_FALSE;
}
if ( OUTSIDE_STRING(loffset, haystack_len) ) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 TSRMLS_CC );
RETURN_FALSE;
}
/* we checked that it will fit: */
offset = (int32_t) loffset;
/* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 TSRMLS_CC );
RETURN_FALSE;
}
Commit Message:
CWE ID: | PHP_FUNCTION(grapheme_strpos)
{
unsigned char *haystack, *needle;
int haystack_len, needle_len;
unsigned char *found;
long loffset = 0;
int32_t offset = 0, noffset = 0;
int ret_pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"grapheme_strpos: unable to parse input param", 0 TSRMLS_CC );
RETURN_FALSE;
}
if ( OUTSIDE_STRING(loffset, haystack_len) ) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 TSRMLS_CC );
RETURN_FALSE;
}
/* we checked that it will fit: */
offset = (int32_t) loffset;
noffset = offset >= 0 ? offset : haystack_len + offset;
/* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 TSRMLS_CC );
RETURN_FALSE;
}
| 165,034 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int huft_build(const unsigned *b, const unsigned n,
const unsigned s, const unsigned short *d,
const unsigned char *e, huft_t **t, unsigned *m)
{
unsigned a; /* counter for codes of length k */
unsigned c[BMAX + 1]; /* bit length count table */
unsigned eob_len; /* length of end-of-block code (value 256) */
unsigned f; /* i repeats in table every f entries */
int g; /* maximum code length */
int htl; /* table level */
unsigned i; /* counter, current code */
unsigned j; /* counter */
int k; /* number of bits in current code */
unsigned *p; /* pointer into c[], b[], or v[] */
huft_t *q; /* points to current table */
huft_t r; /* table entry for structure assignment */
huft_t *u[BMAX]; /* table stack */
unsigned v[N_MAX]; /* values in order of bit length */
int ws[BMAX + 1]; /* bits decoded stack */
int w; /* bits decoded */
unsigned x[BMAX + 1]; /* bit offsets, then code stack */
int y; /* number of dummy codes added */
unsigned z; /* number of entries in current table */
/* Length of EOB code, if any */
eob_len = n > 256 ? b[256] : BMAX;
*t = NULL;
/* Generate counts for each bit length */
memset(c, 0, sizeof(c));
p = (unsigned *) b; /* cast allows us to reuse p for pointing to b */
i = n;
do {
c[*p]++; /* assume all entries <= BMAX */
} while (--i);
if (c[0] == n) { /* null input - all zero length codes */
*m = 0;
return 2;
}
/* Find minimum and maximum length, bound *m by those */
for (j = 1; (j <= BMAX) && (c[j] == 0); j++)
continue;
k = j; /* minimum code length */
for (i = BMAX; (c[i] == 0) && i; i--)
continue;
g = i; /* maximum code length */
*m = (*m < j) ? j : ((*m > i) ? i : *m);
/* Adjust last length count to fill out codes, if needed */
for (y = 1 << j; j < i; j++, y <<= 1) {
y -= c[j];
if (y < 0)
return 2; /* bad input: more codes than bits */
}
y -= c[i];
if (y < 0)
return 2;
c[i] += y;
/* Generate starting offsets into the value table for each length */
x[1] = j = 0;
p = c + 1;
xp = x + 2;
while (--i) { /* note that i == g from above */
j += *p++;
*xp++ = j;
}
}
Commit Message:
CWE ID: CWE-476 | static int huft_build(const unsigned *b, const unsigned n,
const unsigned s, const unsigned short *d,
const unsigned char *e, huft_t **t, unsigned *m)
{
unsigned a; /* counter for codes of length k */
unsigned c[BMAX + 1]; /* bit length count table */
unsigned eob_len; /* length of end-of-block code (value 256) */
unsigned f; /* i repeats in table every f entries */
int g; /* maximum code length */
int htl; /* table level */
unsigned i; /* counter, current code */
unsigned j; /* counter */
int k; /* number of bits in current code */
const unsigned *p; /* pointer into c[], b[], or v[] */
huft_t *q; /* points to current table */
huft_t r; /* table entry for structure assignment */
huft_t *u[BMAX]; /* table stack */
unsigned v[N_MAX]; /* values in order of bit length */
unsigned v_end;
int ws[BMAX + 1]; /* bits decoded stack */
int w; /* bits decoded */
unsigned x[BMAX + 1]; /* bit offsets, then code stack */
int y; /* number of dummy codes added */
unsigned z; /* number of entries in current table */
/* Length of EOB code, if any */
eob_len = n > 256 ? b[256] : BMAX;
*t = NULL;
/* Generate counts for each bit length */
memset(c, 0, sizeof(c));
p = b;
i = n;
do {
c[*p]++; /* assume all entries <= BMAX */
} while (--i);
if (c[0] == n) { /* null input - all zero length codes */
*m = 0;
return 2;
}
/* Find minimum and maximum length, bound *m by those */
for (j = 1; (j <= BMAX) && (c[j] == 0); j++)
continue;
k = j; /* minimum code length */
for (i = BMAX; (c[i] == 0) && i; i--)
continue;
g = i; /* maximum code length */
*m = (*m < j) ? j : ((*m > i) ? i : *m);
/* Adjust last length count to fill out codes, if needed */
for (y = 1 << j; j < i; j++, y <<= 1) {
y -= c[j];
if (y < 0)
return 2; /* bad input: more codes than bits */
}
y -= c[i];
if (y < 0)
return 2;
c[i] += y;
/* Generate starting offsets into the value table for each length */
x[1] = j = 0;
p = c + 1;
xp = x + 2;
while (--i) { /* note that i == g from above */
j += *p++;
*xp++ = j;
}
}
| 165,508 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void xen_netbk_tx_submit(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops;
struct sk_buff *skb;
while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) {
struct xen_netif_tx_request *txp;
struct xenvif *vif;
u16 pending_idx;
unsigned data_len;
pending_idx = *((u16 *)skb->data);
vif = netbk->pending_tx_info[pending_idx].vif;
txp = &netbk->pending_tx_info[pending_idx].req;
/* Check the remap error code. */
if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) {
netdev_dbg(vif->dev, "netback grant failed.\n");
skb_shinfo(skb)->nr_frags = 0;
kfree_skb(skb);
continue;
}
data_len = skb->len;
memcpy(skb->data,
(void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset),
data_len);
if (data_len < txp->size) {
/* Append the packet payload as a fragment. */
txp->offset += data_len;
txp->size -= data_len;
} else {
/* Schedule a response immediately. */
xen_netbk_idx_release(netbk, pending_idx);
}
if (txp->flags & XEN_NETTXF_csum_blank)
skb->ip_summed = CHECKSUM_PARTIAL;
else if (txp->flags & XEN_NETTXF_data_validated)
skb->ip_summed = CHECKSUM_UNNECESSARY;
xen_netbk_fill_frags(netbk, skb);
/*
* If the initial fragment was < PKT_PROT_LEN then
* pull through some bytes from the other fragments to
* increase the linear region to PKT_PROT_LEN bytes.
*/
if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) {
int target = min_t(int, skb->len, PKT_PROT_LEN);
__pskb_pull_tail(skb, target - skb_headlen(skb));
}
skb->dev = vif->dev;
skb->protocol = eth_type_trans(skb, skb->dev);
if (checksum_setup(vif, skb)) {
netdev_dbg(vif->dev,
"Can't setup checksum in net_tx_action\n");
kfree_skb(skb);
continue;
}
vif->dev->stats.rx_bytes += skb->len;
vif->dev->stats.rx_packets++;
xenvif_receive_skb(vif, skb);
}
}
Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop.
Signed-off-by: Matthew Daley <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Ian Campbell <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static void xen_netbk_tx_submit(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops;
struct sk_buff *skb;
while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) {
struct xen_netif_tx_request *txp;
struct xenvif *vif;
u16 pending_idx;
unsigned data_len;
pending_idx = *((u16 *)skb->data);
vif = netbk->pending_tx_info[pending_idx].vif;
txp = &netbk->pending_tx_info[pending_idx].req;
/* Check the remap error code. */
if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) {
netdev_dbg(vif->dev, "netback grant failed.\n");
skb_shinfo(skb)->nr_frags = 0;
kfree_skb(skb);
continue;
}
data_len = skb->len;
memcpy(skb->data,
(void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset),
data_len);
if (data_len < txp->size) {
/* Append the packet payload as a fragment. */
txp->offset += data_len;
txp->size -= data_len;
} else {
/* Schedule a response immediately. */
xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
}
if (txp->flags & XEN_NETTXF_csum_blank)
skb->ip_summed = CHECKSUM_PARTIAL;
else if (txp->flags & XEN_NETTXF_data_validated)
skb->ip_summed = CHECKSUM_UNNECESSARY;
xen_netbk_fill_frags(netbk, skb);
/*
* If the initial fragment was < PKT_PROT_LEN then
* pull through some bytes from the other fragments to
* increase the linear region to PKT_PROT_LEN bytes.
*/
if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) {
int target = min_t(int, skb->len, PKT_PROT_LEN);
__pskb_pull_tail(skb, target - skb_headlen(skb));
}
skb->dev = vif->dev;
skb->protocol = eth_type_trans(skb, skb->dev);
if (checksum_setup(vif, skb)) {
netdev_dbg(vif->dev,
"Can't setup checksum in net_tx_action\n");
kfree_skb(skb);
continue;
}
vif->dev->stats.rx_bytes += skb->len;
vif->dev->stats.rx_packets++;
xenvif_receive_skb(vif, skb);
}
}
| 166,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CastConfigDelegateChromeos::StopCasting(const std::string& activity_id) {
ExecuteJavaScript("backgroundSetup.stopCastMirroring('user-stop');");
}
Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods.
BUG=489445
Review URL: https://codereview.chromium.org/1145833003
Cr-Commit-Position: refs/heads/master@{#330663}
CWE ID: CWE-79 | void CastConfigDelegateChromeos::StopCasting(const std::string& activity_id) {
void CastConfigDelegateChromeos::StopCasting() {
ExecuteJavaScript("backgroundSetup.stopCastMirroring('user-stop');");
// TODO(jdufault): Remove this after stopCastMirroring is properly exported.
// The current beta/release versions of the cast extension do not export
// stopCastMirroring, so we will also try to call the minified version.
// See crbug.com/489929.
ExecuteJavaScript("backgroundSetup.Qu('user-stop');");
}
| 171,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool dstBufferSizeHasOverflow(ParsedOptions options) {
CheckedNumeric<size_t> totalBytes = options.cropRect.width();
totalBytes *= options.cropRect.height();
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
if (!options.shouldScaleInput)
return false;
totalBytes = options.resizeWidth;
totalBytes *= options.resizeHeight;
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
return false;
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | bool dstBufferSizeHasOverflow(ParsedOptions options) {
CheckedNumeric<unsigned> totalBytes = options.cropRect.width();
totalBytes *= options.cropRect.height();
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
if (!options.shouldScaleInput)
return false;
totalBytes = options.resizeWidth;
totalBytes *= options.resizeHeight;
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
return false;
}
| 172,501 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_tRNS_to_alpha_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
/* LIBPNG BUG: this always forces palette images to RGB. */
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
/* This effectively does an 'expand' only if there is some transparency to
* convert to an alpha channel.
*/
if (that->have_tRNS)
image_pixel_add_alpha(that, &display->this);
/* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
else
{
if (that->bit_depth < 8)
that->bit_depth =8;
if (that->sample_depth < 8)
that->sample_depth = 8;
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_tRNS_to_alpha_mod(PNG_CONST image_transform *this,
image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
#if PNG_LIBPNG_VER < 10700
/* LIBPNG BUG: this always forces palette images to RGB. */
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
#endif
/* This effectively does an 'expand' only if there is some transparency to
* convert to an alpha channel.
*/
if (that->have_tRNS)
# if PNG_LIBPNG_VER >= 10700
if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
(that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
# endif
image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
#if PNG_LIBPNG_VER < 10700
/* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
else
{
if (that->bit_depth < 8)
that->bit_depth =8;
if (that->sample_depth < 8)
that->sample_depth = 8;
}
#endif
this->next->mod(this->next, that, pp, display);
}
| 173,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
if (!name)
return ERR_PTR(-ENOENT);
mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
type &= mask;
alg = crypto_alg_lookup(name, type, mask);
if (!alg) {
request_module("%s", name);
if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
CRYPTO_ALG_NEED_FALLBACK))
request_module("%s-all", name);
alg = crypto_alg_lookup(name, type, mask);
}
if (alg)
return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg;
return crypto_larval_add(name, type, mask);
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264 | struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
if (!name)
return ERR_PTR(-ENOENT);
mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
type &= mask;
alg = crypto_alg_lookup(name, type, mask);
if (!alg) {
request_module("crypto-%s", name);
if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
CRYPTO_ALG_NEED_FALLBACK))
request_module("crypto-%s-all", name);
alg = crypto_alg_lookup(name, type, mask);
}
if (alg)
return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg;
return crypto_larval_add(name, type, mask);
}
| 166,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void gamma_transform_test(png_modifier *pm,
PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth,
PNG_CONST int palette_number,
PNG_CONST int interlace_type, PNG_CONST double file_gamma,
PNG_CONST double screen_gamma, PNG_CONST png_byte sbit,
PNG_CONST int use_input_precision, PNG_CONST int scale16)
{
size_t pos = 0;
char name[64];
if (sbit != bit_depth && sbit != 0)
{
pos = safecat(name, sizeof name, pos, "sbit(");
pos = safecatn(name, sizeof name, pos, sbit);
pos = safecat(name, sizeof name, pos, ") ");
}
else
pos = safecat(name, sizeof name, pos, "gamma ");
if (scale16)
pos = safecat(name, sizeof name, pos, "16to8 ");
pos = safecatd(name, sizeof name, pos, file_gamma, 3);
pos = safecat(name, sizeof name, pos, "->");
pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
scale16, pm->test_gamma_expand16, 0 , 0, 0);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void gamma_transform_test(png_modifier *pm,
const png_byte colour_type, const png_byte bit_depth,
const int palette_number,
const int interlace_type, const double file_gamma,
const double screen_gamma, const png_byte sbit,
const int use_input_precision, const int scale16)
{
size_t pos = 0;
char name[64];
if (sbit != bit_depth && sbit != 0)
{
pos = safecat(name, sizeof name, pos, "sbit(");
pos = safecatn(name, sizeof name, pos, sbit);
pos = safecat(name, sizeof name, pos, ") ");
}
else
pos = safecat(name, sizeof name, pos, "gamma ");
if (scale16)
pos = safecat(name, sizeof name, pos, "16to8 ");
pos = safecatd(name, sizeof name, pos, file_gamma, 3);
pos = safecat(name, sizeof name, pos, "->");
pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
scale16, pm->test_gamma_expand16, 0 , 0, 0);
}
| 173,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.
{
if (ms)
{
int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];
if (nestsize == 0 && ms->nest_level == 0)
nestsize = ms->buffer_size_longs;
if (size + 2 <= nestsize) return GPMF_OK;
}
return GPMF_ERROR_BAD_STRUCTURE;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.
{
if (ms)
{
uint32_t nestsize = (uint32_t)ms->nest_size[ms->nest_level];
if (nestsize == 0 && ms->nest_level == 0)
nestsize = ms->buffer_size_longs;
if (size + 2 <= nestsize) return GPMF_OK;
}
return GPMF_ERROR_BAD_STRUCTURE;
}
| 169,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_PLTE;
#endif
png_uint_32 i;
png_colorp pal_ptr;
png_byte buf[3];
png_debug(1, "in png_write_PLTE");
if ((
#ifdef PNG_MNG_FEATURES_SUPPORTED
!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
#endif
num_pal == 0) || num_pal > 256)
{
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
png_error(png_ptr, "Invalid number of colors in palette");
}
else
{
png_warning(png_ptr, "Invalid number of colors in palette");
return;
}
}
if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
{
png_warning(png_ptr,
"Ignoring request to write a PLTE chunk in grayscale PNG");
return;
}
png_ptr->num_palette = (png_uint_16)num_pal;
png_debug1(3, "num_palette = %d", png_ptr->num_palette);
png_write_chunk_start(png_ptr, (png_bytep)png_PLTE,
(png_uint_32)(num_pal * 3));
#ifdef PNG_POINTER_INDEXING_SUPPORTED
for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
{
buf[0] = pal_ptr->red;
buf[1] = pal_ptr->green;
buf[2] = pal_ptr->blue;
png_write_chunk_data(png_ptr, buf, (png_size_t)3);
}
#else
/* This is a little slower but some buggy compilers need to do this
* instead
*/
pal_ptr=palette;
for (i = 0; i < num_pal; i++)
{
buf[0] = pal_ptr[i].red;
buf[1] = pal_ptr[i].green;
buf[2] = pal_ptr[i].blue;
png_write_chunk_data(png_ptr, buf, (png_size_t)3);
}
#endif
png_write_chunk_end(png_ptr);
png_ptr->mode |= PNG_HAVE_PLTE;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_PLTE;
#endif
png_uint_32 max_palette_length, i;
png_colorp pal_ptr;
png_byte buf[3];
png_debug(1, "in png_write_PLTE");
max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
(1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
if ((
#ifdef PNG_MNG_FEATURES_SUPPORTED
!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
#endif
num_pal == 0) || num_pal > max_palette_length)
{
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
png_error(png_ptr, "Invalid number of colors in palette");
}
else
{
png_warning(png_ptr, "Invalid number of colors in palette");
return;
}
}
if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
{
png_warning(png_ptr,
"Ignoring request to write a PLTE chunk in grayscale PNG");
return;
}
png_ptr->num_palette = (png_uint_16)num_pal;
png_debug1(3, "num_palette = %d", png_ptr->num_palette);
png_write_chunk_start(png_ptr, (png_bytep)png_PLTE,
(png_uint_32)(num_pal * 3));
#ifdef PNG_POINTER_INDEXING_SUPPORTED
for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
{
buf[0] = pal_ptr->red;
buf[1] = pal_ptr->green;
buf[2] = pal_ptr->blue;
png_write_chunk_data(png_ptr, buf, (png_size_t)3);
}
#else
/* This is a little slower but some buggy compilers need to do this
* instead
*/
pal_ptr=palette;
for (i = 0; i < num_pal; i++)
{
buf[0] = pal_ptr[i].red;
buf[1] = pal_ptr[i].green;
buf[2] = pal_ptr[i].blue;
png_write_chunk_data(png_ptr, buf, (png_size_t)3);
}
#endif
png_write_chunk_end(png_ptr);
png_ptr->mode |= PNG_HAVE_PLTE;
}
| 172,193 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _asn1_ltostr (long v, char *str)
{
long d, r;
char temp[LTOSTR_MAX_SIZE];
int count, k, start;
if (v < 0)
{
str[0] = '-';
start = 1;
v = -v;
}
else
start = 0;
count = 0;
do
{
d = v / 10;
r = v - d * 10;
temp[start + count] = '0' + (char) r;
count++;
v = d;
}
while (v);
for (k = 0; k < count; k++)
str[k + start] = temp[start + count - k - 1];
str[count + start] = 0;
return str;
}
Commit Message:
CWE ID: CWE-119 | _asn1_ltostr (long v, char *str)
_asn1_ltostr (long v, char str[LTOSTR_MAX_SIZE])
{
long d, r;
char temp[LTOSTR_MAX_SIZE];
int count, k, start;
if (v < 0)
{
str[0] = '-';
start = 1;
v = -v;
}
else
start = 0;
count = 0;
do
{
d = v / 10;
r = v - d * 10;
temp[start + count] = '0' + (char) r;
count++;
v = d;
}
while (v && ((start+count) < LTOSTR_MAX_SIZE-1));
for (k = 0; k < count; k++)
str[k + start] = temp[start + count - k - 1];
str[count + start] = 0;
return str;
}
| 164,729 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuChannel::OnChannelConnected(int32 peer_pid) {
renderer_pid_ = peer_pid;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuChannel::OnChannelConnected(int32 peer_pid) {
| 170,932 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
return 0;
}
Commit Message:
CWE ID: CWE-20 | static int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
vmxnet3_validate_interrupts(s);
return 0;
}
| 165,354 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp)
{
BN_CTX *ctx;
BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;
BIGNUM l, m;
int ret = 0;
int q_bits;
if (!dsa->p || !dsa->q || !dsa->g) {
DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
return 0;
}
BN_init(&k);
BN_init(&kq);
BN_init(&l);
BN_init(&m);
if (ctx_in == NULL) {
if ((ctx = BN_CTX_new()) == NULL)
goto err;
} else
ctx = ctx_in;
if ((r = BN_new()) == NULL)
goto err;
/* Preallocate space */
q_bits = BN_num_bits(dsa->q);
if (!BN_set_bit(&k, q_bits)
|| !BN_set_bit(&l, q_bits)
|| !BN_set_bit(&m, q_bits))
goto err;
/* Get random k */
do
if (!BN_rand_range(&k, dsa->q))
goto err;
while (BN_is_zero(&k));
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
BN_set_flags(&k, BN_FLG_CONSTTIME);
}
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
CRYPTO_LOCK_DSA, dsa->p, ctx))
goto err;
}
/* Compute r = (g^k mod p) mod q */
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
/*
* We do not want timing information to leak the length of k, so we
* compute G^k using an equivalent scalar of fixed bit-length.
*
* We unconditionally perform both of these additions to prevent a
* small timing information leakage. We then choose the sum that is
* one bit longer than the modulus.
*
* TODO: revisit the BN_copy aiming for a memory access agnostic
* conditional copy.
*/
if (!BN_add(&l, &k, dsa->q)
|| !BN_add(&m, &l, dsa->q)
|| !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m))
goto err;
BN_set_flags(&kq, BN_FLG_CONSTTIME);
K = &kq;
} else {
K = &k;
}
DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,
dsa->method_mont_p);
if (!BN_mod(r, r, dsa->q, ctx))
goto err;
/* Compute part of 's = inv(k) (m + xr) mod q' */
if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL)
goto err;
if (*kinvp != NULL)
BN_clear_free(*kinvp);
*kinvp = kinv;
kinv = NULL;
if (*rp != NULL)
BN_clear_free(*rp);
*rp = r;
ret = 1;
err:
if (!ret) {
DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
if (r != NULL)
BN_clear_free(r);
}
if (ctx_in == NULL)
BN_CTX_free(ctx);
BN_clear_free(&k);
BN_clear_free(&kq);
BN_clear_free(&l);
BN_clear_free(&m);
return ret;
}
Commit Message:
CWE ID: CWE-320 | static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp)
{
BN_CTX *ctx;
BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;
BIGNUM l, m;
int ret = 0;
int q_bits;
if (!dsa->p || !dsa->q || !dsa->g) {
DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
return 0;
}
BN_init(&k);
BN_init(&kq);
BN_init(&l);
BN_init(&m);
if (ctx_in == NULL) {
if ((ctx = BN_CTX_new()) == NULL)
goto err;
} else
ctx = ctx_in;
if ((r = BN_new()) == NULL)
goto err;
/* Preallocate space */
q_bits = BN_num_bits(dsa->q) + sizeof(dsa->q->d[0]) * 16;
if (!BN_set_bit(&k, q_bits)
|| !BN_set_bit(&l, q_bits)
|| !BN_set_bit(&m, q_bits))
goto err;
/* Get random k */
do
if (!BN_rand_range(&k, dsa->q))
goto err;
while (BN_is_zero(&k));
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
BN_set_flags(&k, BN_FLG_CONSTTIME);
}
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
CRYPTO_LOCK_DSA, dsa->p, ctx))
goto err;
}
/* Compute r = (g^k mod p) mod q */
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
/*
* We do not want timing information to leak the length of k, so we
* compute G^k using an equivalent scalar of fixed bit-length.
*
* We unconditionally perform both of these additions to prevent a
* small timing information leakage. We then choose the sum that is
* one bit longer than the modulus.
*
* TODO: revisit the BN_copy aiming for a memory access agnostic
* conditional copy.
*/
if (!BN_add(&l, &k, dsa->q)
|| !BN_add(&m, &l, dsa->q)
|| !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m))
goto err;
BN_set_flags(&kq, BN_FLG_CONSTTIME);
K = &kq;
} else {
K = &k;
}
DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,
dsa->method_mont_p);
if (!BN_mod(r, r, dsa->q, ctx))
goto err;
/* Compute part of 's = inv(k) (m + xr) mod q' */
if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL)
goto err;
if (*kinvp != NULL)
BN_clear_free(*kinvp);
*kinvp = kinv;
kinv = NULL;
if (*rp != NULL)
BN_clear_free(*rp);
*rp = r;
ret = 1;
err:
if (!ret) {
DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
if (r != NULL)
BN_clear_free(r);
}
if (ctx_in == NULL)
BN_CTX_free(ctx);
BN_clear_free(&k);
BN_clear_free(&kq);
BN_clear_free(&l);
BN_clear_free(&m);
return ret;
}
| 165,331 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int pop_sync_mailbox(struct Context *ctx, int *index_hint)
{
int i, j, ret = 0;
char buf[LONG_STRING];
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = NULL;
#endif
pop_data->check_time = 0;
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
mutt_progress_init(&progress, _("Marking messages deleted..."),
MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);
#ifdef USE_HCACHE
hc = pop_hcache_open(pop_data, ctx->path);
#endif
for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)
{
if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)
{
j++;
if (!ctx->quiet)
mutt_progress_update(&progress, j, -1);
snprintf(buf, sizeof(buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
ret = pop_query(pop_data, buf, sizeof(buf));
if (ret == 0)
{
mutt_bcache_del(pop_data->bcache, ctx->hdrs[i]->data);
#ifdef USE_HCACHE
mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
#endif
}
}
#ifdef USE_HCACHE
if (ctx->hdrs[i]->changed)
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret == 0)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(pop_data, buf, sizeof(buf));
}
if (ret == 0)
{
pop_data->clear_cache = true;
pop_clear_cache(pop_data);
pop_data->status = POP_DISCONNECTED;
return 0;
}
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
}
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-22 | static int pop_sync_mailbox(struct Context *ctx, int *index_hint)
{
int i, j, ret = 0;
char buf[LONG_STRING];
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = NULL;
#endif
pop_data->check_time = 0;
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
mutt_progress_init(&progress, _("Marking messages deleted..."),
MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);
#ifdef USE_HCACHE
hc = pop_hcache_open(pop_data, ctx->path);
#endif
for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)
{
if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)
{
j++;
if (!ctx->quiet)
mutt_progress_update(&progress, j, -1);
snprintf(buf, sizeof(buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
ret = pop_query(pop_data, buf, sizeof(buf));
if (ret == 0)
{
mutt_bcache_del(pop_data->bcache, cache_id(ctx->hdrs[i]->data));
#ifdef USE_HCACHE
mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
#endif
}
}
#ifdef USE_HCACHE
if (ctx->hdrs[i]->changed)
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret == 0)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(pop_data, buf, sizeof(buf));
}
if (ret == 0)
{
pop_data->clear_cache = true;
pop_clear_cache(pop_data);
pop_data->status = POP_DISCONNECTED;
return 0;
}
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
}
}
| 169,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionNavigationThrottle::WillStartOrRedirectRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents = navigation_handle()->GetWebContents();
ExtensionRegistry* registry =
ExtensionRegistry::Get(web_contents->GetBrowserContext());
const GURL& url = navigation_handle()->GetURL();
bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme);
url::Origin target_origin = url::Origin::Create(url);
const Extension* target_extension = nullptr;
if (url_has_extension_scheme) {
target_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
} else if (target_origin.scheme() == kExtensionScheme) {
DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
target_extension =
registry->enabled_extensions().GetByID(target_origin.host());
} else {
return content::NavigationThrottle::PROCEED;
}
if (!target_extension) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
if (target_extension->is_hosted_app()) {
base::StringPiece resource_root_relative_path =
url.path_piece().empty() ? base::StringPiece()
: url.path_piece().substr(1);
if (!IconsInfo::GetIcons(target_extension)
.ContainsPath(resource_root_relative_path)) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
}
if (navigation_handle()->IsInMainFrame()) {
bool current_frame_is_extension_process =
!!registry->enabled_extensions().GetExtensionOrAppByURL(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL());
if (!url_has_extension_scheme && !current_frame_is_extension_process) {
if (target_origin.scheme() == kExtensionScheme &&
navigation_handle()->GetSuggestedFilename().has_value()) {
return content::NavigationThrottle::PROCEED;
}
bool has_webview_permission =
target_extension->permissions_data()->HasAPIPermission(
APIPermission::kWebView);
if (!has_webview_permission)
return content::NavigationThrottle::CANCEL;
}
guest_view::GuestViewBase* guest =
guest_view::GuestViewBase::FromWebContents(web_contents);
if (url_has_extension_scheme && guest) {
const std::string& owner_extension_id = guest->owner_host();
const Extension* owner_extension =
registry->enabled_extensions().GetByID(owner_extension_id);
std::string partition_domain;
std::string partition_id;
bool in_memory = false;
bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL(),
&partition_domain, &partition_id, &in_memory);
bool allowed = true;
url_request_util::AllowCrossRendererResourceLoadHelper(
is_guest, target_extension, owner_extension, partition_id, url.path(),
navigation_handle()->GetPageTransition(), &allowed);
if (!allowed)
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
content::RenderFrameHost* parent = navigation_handle()->GetParentFrame();
bool external_ancestor = false;
for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) {
if (ancestor->GetLastCommittedOrigin() == target_origin)
continue;
if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin)
continue;
if (ancestor->GetLastCommittedURL().SchemeIs(
content::kChromeDevToolsScheme))
continue;
external_ancestor = true;
break;
}
if (external_ancestor) {
if (!url_has_extension_scheme)
return content::NavigationThrottle::CANCEL;
if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension,
url.path()))
return content::NavigationThrottle::BLOCK_REQUEST;
if (target_extension->is_platform_app())
return content::NavigationThrottle::CANCEL;
const Extension* parent_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(
parent->GetSiteInstance()->GetSiteURL());
if (parent_extension && parent_extension->is_platform_app())
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames.
BUG=836858
Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2
Reviewed-on: https://chromium-review.googlesource.com/1028511
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nick Carter <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#553867}
CWE ID: CWE-20 | ExtensionNavigationThrottle::WillStartOrRedirectRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents = navigation_handle()->GetWebContents();
ExtensionRegistry* registry =
ExtensionRegistry::Get(web_contents->GetBrowserContext());
const GURL& url = navigation_handle()->GetURL();
bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme);
url::Origin target_origin = url::Origin::Create(url);
const Extension* target_extension = nullptr;
if (url_has_extension_scheme) {
target_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
} else if (target_origin.scheme() == kExtensionScheme) {
DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
target_extension =
registry->enabled_extensions().GetByID(target_origin.host());
} else {
return content::NavigationThrottle::PROCEED;
}
if (!target_extension) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
if (target_extension->is_hosted_app()) {
base::StringPiece resource_root_relative_path =
url.path_piece().empty() ? base::StringPiece()
: url.path_piece().substr(1);
if (!IconsInfo::GetIcons(target_extension)
.ContainsPath(resource_root_relative_path)) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
}
// Block all navigations to blob: or filesystem: URLs with extension
// origin from non-extension processes. See https://crbug.com/645028 and
// https://crbug.com/836858.
bool current_frame_is_extension_process =
!!registry->enabled_extensions().GetExtensionOrAppByURL(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL());
if (!url_has_extension_scheme && !current_frame_is_extension_process) {
// Relax this restriction for navigations that will result in downloads.
// See https://crbug.com/714373.
if (target_origin.scheme() == kExtensionScheme &&
navigation_handle()->GetSuggestedFilename().has_value()) {
return content::NavigationThrottle::PROCEED;
}
// Relax this restriction for apps that use <webview>. See
// https://crbug.com/652077.
bool has_webview_permission =
target_extension->permissions_data()->HasAPIPermission(
APIPermission::kWebView);
if (!has_webview_permission)
return content::NavigationThrottle::CANCEL;
}
if (navigation_handle()->IsInMainFrame()) {
guest_view::GuestViewBase* guest =
guest_view::GuestViewBase::FromWebContents(web_contents);
if (url_has_extension_scheme && guest) {
const std::string& owner_extension_id = guest->owner_host();
const Extension* owner_extension =
registry->enabled_extensions().GetByID(owner_extension_id);
std::string partition_domain;
std::string partition_id;
bool in_memory = false;
bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL(),
&partition_domain, &partition_id, &in_memory);
bool allowed = true;
url_request_util::AllowCrossRendererResourceLoadHelper(
is_guest, target_extension, owner_extension, partition_id, url.path(),
navigation_handle()->GetPageTransition(), &allowed);
if (!allowed)
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
content::RenderFrameHost* parent = navigation_handle()->GetParentFrame();
bool external_ancestor = false;
for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) {
if (ancestor->GetLastCommittedOrigin() == target_origin)
continue;
if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin)
continue;
if (ancestor->GetLastCommittedURL().SchemeIs(
content::kChromeDevToolsScheme))
continue;
external_ancestor = true;
break;
}
if (external_ancestor) {
if (!url_has_extension_scheme)
return content::NavigationThrottle::CANCEL;
if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension,
url.path()))
return content::NavigationThrottle::BLOCK_REQUEST;
if (target_extension->is_platform_app())
return content::NavigationThrottle::CANCEL;
const Extension* parent_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(
parent->GetSiteInstance()->GetSiteURL());
if (parent_extension && parent_extension->is_platform_app())
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
| 173,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *pktap_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint32 pkt_len, rectype, dlt;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP");
col_clear(pinfo->cinfo, COL_INFO);
pkt_len = tvb_get_letohl(tvb, offset);
col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len);
/* Dissect the packet */
ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA);
pktap_tree = proto_item_add_subtree(ti, ett_pktap);
proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
if (pkt_len < MIN_PKTAP_HDR_LEN) {
proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short,
tvb, offset, 4);
return;
}
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
rectype = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
dlt = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24,
ENC_ASCII|ENC_NA);
offset += 24;
proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
offset += 20;
proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
/*offset += 20;*/
if (rectype == PKT_REC_PACKET) {
next_tvb = tvb_new_subset_remaining(tvb, pkt_len);
dissector_try_uint(wtap_encap_dissector_table,
wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree);
}
}
Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.
We now require that. Make it so.
Bug: 12440
Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76
Reviewed-on: https://code.wireshark.org/review/15424
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *pktap_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint32 pkt_len, rectype, dlt;
int wtap_encap;
struct eth_phdr eth;
void *phdr;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP");
col_clear(pinfo->cinfo, COL_INFO);
pkt_len = tvb_get_letohl(tvb, offset);
col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len);
/* Dissect the packet */
ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA);
pktap_tree = proto_item_add_subtree(ti, ett_pktap);
proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
if (pkt_len < MIN_PKTAP_HDR_LEN) {
proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short,
tvb, offset, 4);
return;
}
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
rectype = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
dlt = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24,
ENC_ASCII|ENC_NA);
offset += 24;
proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
offset += 20;
proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
/*offset += 20;*/
if (rectype == PKT_REC_PACKET) {
next_tvb = tvb_new_subset_remaining(tvb, pkt_len);
wtap_encap = wtap_pcap_encap_to_wtap_encap(dlt);
switch (wtap_encap) {
case WTAP_ENCAP_ETHERNET:
eth.fcs_len = -1; /* Unknown whether we have an FCS */
phdr = ð
break;
default:
phdr = NULL;
break;
}
dissector_try_uint_new(wtap_encap_dissector_table,
wtap_encap, next_tvb, pinfo, tree, TRUE, phdr);
}
}
| 167,143 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::useGraphicBuffer2_l(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id *buffer) {
OMX_PARAM_PORTDEFINITIONTYPE def;
InitOMXParams(&def);
def.nPortIndex = portIndex;
OMX_ERRORTYPE err = OMX_GetParameter(mHandle, OMX_IndexParamPortDefinition, &def);
if (err != OMX_ErrorNone) {
OMX_INDEXTYPE index = OMX_IndexParamPortDefinition;
CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u",
asString(index), index, portString(portIndex), portIndex);
return UNKNOWN_ERROR;
}
BufferMeta *bufferMeta = new BufferMeta(graphicBuffer);
OMX_BUFFERHEADERTYPE *header = NULL;
OMX_U8* bufferHandle = const_cast<OMX_U8*>(
reinterpret_cast<const OMX_U8*>(graphicBuffer->handle));
err = OMX_UseBuffer(
mHandle,
&header,
portIndex,
bufferMeta,
def.nBufferSize,
bufferHandle);
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, BUFFER_FMT(portIndex, "%u@%p", def.nBufferSize, bufferHandle));
delete bufferMeta;
bufferMeta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pBuffer, bufferHandle);
CHECK_EQ(header->pAppPrivate, bufferMeta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
CLOG_BUFFER(useGraphicBuffer2, NEW_BUFFER_FMT(
*buffer, portIndex, "%u@%p", def.nBufferSize, bufferHandle));
return OK;
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::useGraphicBuffer2_l(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id *buffer) {
OMX_PARAM_PORTDEFINITIONTYPE def;
InitOMXParams(&def);
def.nPortIndex = portIndex;
OMX_ERRORTYPE err = OMX_GetParameter(mHandle, OMX_IndexParamPortDefinition, &def);
if (err != OMX_ErrorNone) {
OMX_INDEXTYPE index = OMX_IndexParamPortDefinition;
CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u",
asString(index), index, portString(portIndex), portIndex);
return UNKNOWN_ERROR;
}
BufferMeta *bufferMeta = new BufferMeta(graphicBuffer, portIndex);
OMX_BUFFERHEADERTYPE *header = NULL;
OMX_U8* bufferHandle = const_cast<OMX_U8*>(
reinterpret_cast<const OMX_U8*>(graphicBuffer->handle));
err = OMX_UseBuffer(
mHandle,
&header,
portIndex,
bufferMeta,
def.nBufferSize,
bufferHandle);
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, BUFFER_FMT(portIndex, "%u@%p", def.nBufferSize, bufferHandle));
delete bufferMeta;
bufferMeta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pBuffer, bufferHandle);
CHECK_EQ(header->pAppPrivate, bufferMeta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
CLOG_BUFFER(useGraphicBuffer2, NEW_BUFFER_FMT(
*buffer, portIndex, "%u@%p", def.nBufferSize, bufferHandle));
return OK;
}
| 173,535 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void usb_ehci_pci_exit(PCIDevice *dev)
{
EHCIPCIState *i = PCI_EHCI(dev);
static void usb_ehci_pci_reset(DeviceState *dev)
{
PCIDevice *pci_dev = PCI_DEVICE(dev);
EHCIPCIState *i = PCI_EHCI(pci_dev);
EHCIState *s = &i->ehci;
ehci_reset(s);
}
static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr,
uint32_t val, int l)
{
EHCIPCIState *i = PCI_EHCI(dev);
bool busmaster;
pci_default_write_config(dev, addr, val, l);
if (!range_covers_byte(addr, l, PCI_COMMAND)) {
return;
}
busmaster = pci_get_word(dev->config + PCI_COMMAND) & PCI_COMMAND_MASTER;
i->ehci.as = busmaster ? pci_get_address_space(dev) : &address_space_memory;
}
static Property ehci_pci_properties[] = {
DEFINE_PROP_UINT32("maxframes", EHCIPCIState, ehci.maxframes, 128),
DEFINE_PROP_END_OF_LIST(),
};
static const VMStateDescription vmstate_ehci_pci = {
.name = "ehci",
.version_id = 2,
.minimum_version_id = 1,
.fields = (VMStateField[]) {
VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState),
VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState),
VMSTATE_END_OF_LIST()
}
};
static void ehci_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
k->realize = usb_ehci_pci_realize;
k->exit = usb_ehci_pci_exit;
k->class_id = PCI_CLASS_SERIAL_USB;
k->config_write = usb_ehci_pci_write_config;
dc->vmsd = &vmstate_ehci_pci;
dc->props = ehci_pci_properties;
dc->reset = usb_ehci_pci_reset;
}
static const TypeInfo ehci_pci_type_info = {
.name = TYPE_PCI_EHCI,
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(EHCIPCIState),
.instance_init = usb_ehci_pci_init,
.abstract = true,
.class_init = ehci_class_init,
};
static void ehci_data_class_init(ObjectClass *klass, void *data)
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(EHCIPCIState),
.instance_init = usb_ehci_pci_init,
.abstract = true,
.class_init = ehci_class_init,
};
Commit Message:
CWE ID: CWE-772 | static void usb_ehci_pci_exit(PCIDevice *dev)
{
EHCIPCIState *i = PCI_EHCI(dev);
static void usb_ehci_pci_reset(DeviceState *dev)
{
PCIDevice *pci_dev = PCI_DEVICE(dev);
EHCIPCIState *i = PCI_EHCI(pci_dev);
EHCIState *s = &i->ehci;
ehci_reset(s);
}
static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr,
uint32_t val, int l)
{
EHCIPCIState *i = PCI_EHCI(dev);
bool busmaster;
pci_default_write_config(dev, addr, val, l);
if (!range_covers_byte(addr, l, PCI_COMMAND)) {
return;
}
busmaster = pci_get_word(dev->config + PCI_COMMAND) & PCI_COMMAND_MASTER;
i->ehci.as = busmaster ? pci_get_address_space(dev) : &address_space_memory;
}
static Property ehci_pci_properties[] = {
DEFINE_PROP_UINT32("maxframes", EHCIPCIState, ehci.maxframes, 128),
DEFINE_PROP_END_OF_LIST(),
};
static const VMStateDescription vmstate_ehci_pci = {
.name = "ehci",
.version_id = 2,
.minimum_version_id = 1,
.fields = (VMStateField[]) {
VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState),
VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState),
VMSTATE_END_OF_LIST()
}
};
static void ehci_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
k->realize = usb_ehci_pci_realize;
k->exit = usb_ehci_pci_exit;
k->class_id = PCI_CLASS_SERIAL_USB;
k->config_write = usb_ehci_pci_write_config;
dc->vmsd = &vmstate_ehci_pci;
dc->props = ehci_pci_properties;
dc->reset = usb_ehci_pci_reset;
}
static const TypeInfo ehci_pci_type_info = {
.name = TYPE_PCI_EHCI,
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(EHCIPCIState),
.instance_init = usb_ehci_pci_init,
.abstract = true,
.class_init = ehci_class_init,
};
static void ehci_data_class_init(ObjectClass *klass, void *data)
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(EHCIPCIState),
.instance_init = usb_ehci_pci_init,
.instance_finalize = usb_ehci_pci_finalize,
.abstract = true,
.class_init = ehci_class_init,
};
| 164,796 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateTransferBuffer");
if (command_buffer_.get()) {
int32 id = command_buffer_->CreateTransferBuffer(size, id_request);
GpuCommandBufferMsg_CreateTransferBuffer::WriteReplyParams(
reply_message, id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Sizes going across an IPC should be uint32.
BUG=164946
Review URL: https://chromiumcodereview.appspot.com/11472038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size,
void GpuCommandBufferStub::OnCreateTransferBuffer(uint32 size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateTransferBuffer");
if (command_buffer_.get()) {
int32 id = command_buffer_->CreateTransferBuffer(size, id_request);
GpuCommandBufferMsg_CreateTransferBuffer::WriteReplyParams(
reply_message, id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
| 171,405 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC)
{
int de;
int NumDirEntries;
int NextDirOffset;
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength);
#endif
ImageInfo->sections_found |= FOUND_IFD0;
NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) {
if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,
offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) {
return FALSE;
}
}
/*
* Ignore IFD2 if it purportedly exists
*/
if (section_index == SECTION_THUMBNAIL) {
return TRUE;
}
/*
* Hack to make it process IDF1 I hope
* There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail
*/
NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);
if (NextDirOffset) {
* Hack to make it process IDF1 I hope
* There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail
*/
NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);
if (NextDirOffset) {
/* the next line seems false but here IFDlength means length of all IFDs */
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size);
#endif
if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN
&& ImageInfo->Thumbnail.size
&& ImageInfo->Thumbnail.offset
&& ImageInfo->read_thumbnail
) {
exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC);
}
return TRUE;
} else {
return FALSE;
}
}
return TRUE;
}
Commit Message:
CWE ID: CWE-119 | static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC)
{
int de;
int NumDirEntries;
int NextDirOffset;
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength);
#endif
ImageInfo->sections_found |= FOUND_IFD0;
if ((dir_start + 2) >= (offset_base+IFDlength)) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size");
return FALSE;
}
NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) {
if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,
offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) {
return FALSE;
}
}
/*
* Ignore IFD2 if it purportedly exists
*/
if (section_index == SECTION_THUMBNAIL) {
return TRUE;
}
/*
* Hack to make it process IDF1 I hope
* There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail
*/
NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);
if (NextDirOffset) {
* Hack to make it process IDF1 I hope
* There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail
*/
if ((dir_start+2+12*de + 4) >= (offset_base+IFDlength)) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size");
return FALSE;
}
NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);
if (NextDirOffset) {
/* the next line seems false but here IFDlength means length of all IFDs */
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size);
#endif
if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN
&& ImageInfo->Thumbnail.size
&& ImageInfo->Thumbnail.offset
&& ImageInfo->read_thumbnail
) {
exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC);
}
return TRUE;
} else {
return FALSE;
}
}
return TRUE;
}
| 165,033 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void EBMLHeader::Init()
{
m_version = 1;
m_readVersion = 1;
m_maxIdLength = 4;
m_maxSizeLength = 8;
if (m_docType)
{
delete[] m_docType;
m_docType = NULL;
}
m_docTypeVersion = 1;
m_docTypeReadVersion = 1;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void EBMLHeader::Init()
long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) {
assert(pReader);
long long total, available;
| 174,389 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetExternalFileEntry",
base::Bind(&FileBrowserHandlerCustomBindings::GetExternalFileEntry,
base::Unretained(this)));
RouteFunction("GetEntryURL",
base::Bind(&FileBrowserHandlerCustomBindings::GetEntryURL,
base::Unretained(this)));
}
Commit Message: [Extensions] Add more bindings access checks
BUG=598165
Review URL: https://codereview.chromium.org/1854983002
Cr-Commit-Position: refs/heads/master@{#385282}
CWE ID: | FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetExternalFileEntry", "fileBrowserHandler",
base::Bind(
&FileBrowserHandlerCustomBindings::GetExternalFileEntryCallback,
base::Unretained(this)));
}
| 173,271 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DataReductionProxySettings::InitDataReductionProxySettings(
PrefService* prefs,
DataReductionProxyIOData* io_data,
std::unique_ptr<DataReductionProxyService> data_reduction_proxy_service) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(prefs);
DCHECK(io_data);
DCHECK(io_data->config());
DCHECK(data_reduction_proxy_service);
prefs_ = prefs;
config_ = io_data->config();
data_reduction_proxy_service_ = std::move(data_reduction_proxy_service);
data_reduction_proxy_service_->AddObserver(this);
InitPrefMembers();
RecordDataReductionInit();
#if defined(OS_ANDROID)
if (spdy_proxy_auth_enabled_.GetValue()) {
data_reduction_proxy_service_->compression_stats()
->SetDataUsageReportingEnabled(true);
}
#endif // defined(OS_ANDROID)
for (auto& observer : observers_)
observer.OnSettingsInitialized();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | void DataReductionProxySettings::InitDataReductionProxySettings(
PrefService* prefs,
DataReductionProxyIOData* io_data,
std::unique_ptr<DataReductionProxyService> data_reduction_proxy_service) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(prefs);
DCHECK(io_data);
DCHECK(io_data->config());
DCHECK(data_reduction_proxy_service);
prefs_ = prefs;
config_ = io_data->config();
data_reduction_proxy_service_ = std::move(data_reduction_proxy_service);
data_reduction_proxy_service_->AddObserver(this);
RecordDataReductionInit();
registrar_.Init(prefs_);
registrar_.Add(
prefs::kDataSaverEnabled,
base::BindRepeating(&DataReductionProxySettings::OnProxyEnabledPrefChange,
base::Unretained(this)));
#if defined(OS_ANDROID)
if (IsDataSaverEnabledByUser(prefs_)) {
data_reduction_proxy_service_->compression_stats()
->SetDataUsageReportingEnabled(true);
}
#endif // defined(OS_ANDROID)
for (auto& observer : observers_)
observer.OnSettingsInitialized();
}
| 172,552 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(unserialize)
{
char *buf = NULL;
size_t buf_len;
const unsigned char *p;
php_unserialize_data_t var_hash;
zval *options = NULL, *classes = NULL;
HashTable *class_hash = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) {
RETURN_FALSE;
}
if (buf_len == 0) {
RETURN_FALSE;
}
p = (const unsigned char*) buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if(options != NULL) {
classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1);
if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {
ALLOC_HASHTABLE(class_hash);
zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);
}
if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {
zval *entry;
zend_string *lcname;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {
convert_to_string_ex(entry);
lcname = zend_string_tolower(Z_STR_P(entry));
zend_hash_add_empty_element(class_hash, lcname);
zend_string_release(lcname);
} ZEND_HASH_FOREACH_END();
}
}
if (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
zval_ptr_dtor(return_value);
if (!EG(exception)) {
php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes",
(zend_long)((char*)p - buf), buf_len);
}
RETURN_FALSE;
}
/* We should keep an reference to return_value to prevent it from being dtor
in case nesting calls to unserialize */
var_push_dtor(&var_hash, return_value);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
}
Commit Message: Complete the fix of bug #70172 for PHP 7
CWE ID: CWE-416 | PHP_FUNCTION(unserialize)
{
char *buf = NULL;
size_t buf_len;
const unsigned char *p;
php_unserialize_data_t var_hash;
zval *options = NULL, *classes = NULL;
zval *retval;
HashTable *class_hash = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) {
RETURN_FALSE;
}
if (buf_len == 0) {
RETURN_FALSE;
}
p = (const unsigned char*) buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if(options != NULL) {
classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1);
if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {
ALLOC_HASHTABLE(class_hash);
zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);
}
if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {
zval *entry;
zend_string *lcname;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {
convert_to_string_ex(entry);
lcname = zend_string_tolower(Z_STR_P(entry));
zend_hash_add_empty_element(class_hash, lcname);
zend_string_release(lcname);
} ZEND_HASH_FOREACH_END();
}
}
retval = var_tmp_var(&var_hash);
if (!php_var_unserialize_ex(retval, &p, p + buf_len, &var_hash, class_hash)) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
if (!EG(exception)) {
php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes",
(zend_long)((char*)p - buf), buf_len);
}
RETURN_FALSE;
}
ZVAL_COPY(return_value, retval);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
}
| 168,666 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int cJSON_GetArraySize( cJSON *array )
{
cJSON *c = array->child;
int i = 0;
while ( c ) {
++i;
c = c->next;
}
return i;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | int cJSON_GetArraySize( cJSON *array )
| 167,287 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return 0.0;
uint32_t key, insamples;
uint32_t repeat, outsamples;
GPMF_stream find_stream;
if (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0;
key = GPMF_Key(gs);
repeat = GPMF_Repeat(gs);
if (rate == 0.0)
rate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST);
if (rate == 0.0)
{
*in = *out = 0.0;
return 0.0;
}
GPMF_CopyState(gs, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
{
outsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));
insamples = outsamples - repeat;
*in = ((double)insamples / (double)rate);
*out = ((double)outsamples / (double)rate);
}
else
{
*in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
*out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
}
return rate;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_OFFSET, GPMF_CURRENT_LEVEL))
GPMF_FormattedData(&find_stream, &timo, 4, 0, 1);
double first, last;
first = -intercept / rate - timo;
last = first + (double)totalsamples / rate;
//printf("%c%c%c%c first sample at time %.3fms, last at %.3fms\n", PRINTF_4CC(fourcc), 1000.0*first, 1000.0*last);
if (firstsampletime) *firstsampletime = first;
if (lastsampletime) *lastsampletime = last;
}
}
}
}
cleanup:
if (payload)
FreePayload(payload);
payload = NULL;
return rate;
}
| 169,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int udf_translate_to_linux(uint8_t *newName, uint8_t *udfName,
int udfLen, uint8_t *fidName,
int fidNameLen)
{
int index, newIndex = 0, needsCRC = 0;
int extIndex = 0, newExtIndex = 0, hasExt = 0;
unsigned short valueCRC;
uint8_t curr;
if (udfName[0] == '.' &&
(udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) {
needsCRC = 1;
newIndex = udfLen;
memcpy(newName, udfName, udfLen);
} else {
for (index = 0; index < udfLen; index++) {
curr = udfName[index];
if (curr == '/' || curr == 0) {
needsCRC = 1;
curr = ILLEGAL_CHAR_MARK;
while (index + 1 < udfLen &&
(udfName[index + 1] == '/' ||
udfName[index + 1] == 0))
index++;
}
if (curr == EXT_MARK &&
(udfLen - index - 1) <= EXT_SIZE) {
if (udfLen == index + 1)
hasExt = 0;
else {
hasExt = 1;
extIndex = index;
newExtIndex = newIndex;
}
}
if (newIndex < 256)
newName[newIndex++] = curr;
else
needsCRC = 1;
}
}
if (needsCRC) {
uint8_t ext[EXT_SIZE];
int localExtIndex = 0;
if (hasExt) {
int maxFilenameLen;
for (index = 0;
index < EXT_SIZE && extIndex + index + 1 < udfLen;
index++) {
curr = udfName[extIndex + index + 1];
if (curr == '/' || curr == 0) {
needsCRC = 1;
curr = ILLEGAL_CHAR_MARK;
while (extIndex + index + 2 < udfLen &&
(index + 1 < EXT_SIZE &&
(udfName[extIndex + index + 2] == '/' ||
udfName[extIndex + index + 2] == 0)))
index++;
}
ext[localExtIndex++] = curr;
}
maxFilenameLen = 250 - localExtIndex;
if (newIndex > maxFilenameLen)
newIndex = maxFilenameLen;
else
newIndex = newExtIndex;
} else if (newIndex > 250)
newIndex = 250;
newName[newIndex++] = CRC_MARK;
valueCRC = crc_itu_t(0, fidName, fidNameLen);
newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8);
newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8);
newName[newIndex++] = hex_asc_upper_hi(valueCRC);
newName[newIndex++] = hex_asc_upper_lo(valueCRC);
if (hasExt) {
newName[newIndex++] = EXT_MARK;
for (index = 0; index < localExtIndex; index++)
newName[newIndex++] = ext[index];
}
}
return newIndex;
}
Commit Message: udf: Check path length when reading symlink
Symlink reading code does not check whether the resulting path fits into
the page provided by the generic code. This isn't as easy as just
checking the symlink size because of various encoding conversions we
perform on path. So we have to check whether there is still enough space
in the buffer on the fly.
CC: [email protected]
Reported-by: Carl Henrik Lunde <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-17 | static int udf_translate_to_linux(uint8_t *newName, uint8_t *udfName,
static int udf_translate_to_linux(uint8_t *newName, int newLen,
uint8_t *udfName, int udfLen,
uint8_t *fidName, int fidNameLen)
{
int index, newIndex = 0, needsCRC = 0;
int extIndex = 0, newExtIndex = 0, hasExt = 0;
unsigned short valueCRC;
uint8_t curr;
if (udfName[0] == '.' &&
(udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) {
needsCRC = 1;
newIndex = udfLen;
memcpy(newName, udfName, udfLen);
} else {
for (index = 0; index < udfLen; index++) {
curr = udfName[index];
if (curr == '/' || curr == 0) {
needsCRC = 1;
curr = ILLEGAL_CHAR_MARK;
while (index + 1 < udfLen &&
(udfName[index + 1] == '/' ||
udfName[index + 1] == 0))
index++;
}
if (curr == EXT_MARK &&
(udfLen - index - 1) <= EXT_SIZE) {
if (udfLen == index + 1)
hasExt = 0;
else {
hasExt = 1;
extIndex = index;
newExtIndex = newIndex;
}
}
if (newIndex < newLen)
newName[newIndex++] = curr;
else
needsCRC = 1;
}
}
if (needsCRC) {
uint8_t ext[EXT_SIZE];
int localExtIndex = 0;
if (hasExt) {
int maxFilenameLen;
for (index = 0;
index < EXT_SIZE && extIndex + index + 1 < udfLen;
index++) {
curr = udfName[extIndex + index + 1];
if (curr == '/' || curr == 0) {
needsCRC = 1;
curr = ILLEGAL_CHAR_MARK;
while (extIndex + index + 2 < udfLen &&
(index + 1 < EXT_SIZE &&
(udfName[extIndex + index + 2] == '/' ||
udfName[extIndex + index + 2] == 0)))
index++;
}
ext[localExtIndex++] = curr;
}
maxFilenameLen = newLen - CRC_LEN - localExtIndex;
if (newIndex > maxFilenameLen)
newIndex = maxFilenameLen;
else
newIndex = newExtIndex;
} else if (newIndex > newLen - CRC_LEN)
newIndex = newLen - CRC_LEN;
newName[newIndex++] = CRC_MARK;
valueCRC = crc_itu_t(0, fidName, fidNameLen);
newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8);
newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8);
newName[newIndex++] = hex_asc_upper_hi(valueCRC);
newName[newIndex++] = hex_asc_upper_lo(valueCRC);
if (hasExt) {
newName[newIndex++] = EXT_MARK;
for (index = 0; index < localExtIndex; index++)
newName[newIndex++] = ext[index];
}
}
return newIndex;
}
| 166,760 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ResetScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
return;
}
PrefService* prefs = g_browser_process->local_state();
restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFirstExecAfterBoot);
reboot_was_requested_ = false;
rollback_available_ = false;
if (!restart_required_) // First exec after boot.
reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested);
if (!restart_required_ && reboot_was_requested_) {
rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested);
ShowWithParams();
} else {
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck,
weak_ptr_factory_.GetWeakPtr()));
}
}
Commit Message: Rollback option put behind the flag.
BUG=368860
Review URL: https://codereview.chromium.org/267393011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269753 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ResetScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
return;
}
PrefService* prefs = g_browser_process->local_state();
restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFirstExecAfterBoot);
reboot_was_requested_ = false;
rollback_available_ = false;
if (!restart_required_) // First exec after boot.
reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested);
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableRollbackOption)) {
rollback_available_ = false;
ShowWithParams();
} else if (!restart_required_ && reboot_was_requested_) {
rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested);
ShowWithParams();
} else {
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck,
weak_ptr_factory_.GetWeakPtr()));
}
}
| 171,181 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mp_pack(lua_State *L) {
int nargs = lua_gettop(L);
int i;
mp_buf *buf;
if (nargs == 0)
return luaL_argerror(L, 0, "MessagePack pack needs input.");
if (!lua_checkstack(L, nargs))
return luaL_argerror(L, 0, "Too many arguments for MessagePack pack.");
buf = mp_buf_new(L);
for(i = 1; i <= nargs; i++) {
/* Copy argument i to top of stack for _encode processing;
* the encode function pops it from the stack when complete. */
lua_pushvalue(L, i);
mp_encode_lua_type(L,buf,0);
lua_pushlstring(L,(char*)buf->b,buf->len);
/* Reuse the buffer for the next operation by
* setting its free count to the total buffer size
* and the current position to zero. */
buf->free += buf->len;
buf->len = 0;
}
mp_buf_free(L, buf);
/* Concatenate all nargs buffers together */
lua_concat(L, nargs);
return 1;
}
Commit Message: Security: more cmsgpack fixes by @soloestoy.
@soloestoy sent me this additional fixes, after searching for similar
problems to the one reported in mp_pack(). I'm committing the changes
because it was not possible during to make a public PR to protect Redis
users and give Redis providers some time to patch their systems.
CWE ID: CWE-119 | int mp_pack(lua_State *L) {
int nargs = lua_gettop(L);
int i;
mp_buf *buf;
if (nargs == 0)
return luaL_argerror(L, 0, "MessagePack pack needs input.");
if (!lua_checkstack(L, nargs))
return luaL_argerror(L, 0, "Too many arguments for MessagePack pack.");
buf = mp_buf_new(L);
for(i = 1; i <= nargs; i++) {
/* Copy argument i to top of stack for _encode processing;
* the encode function pops it from the stack when complete. */
luaL_checkstack(L, 1, "in function mp_check");
lua_pushvalue(L, i);
mp_encode_lua_type(L,buf,0);
lua_pushlstring(L,(char*)buf->b,buf->len);
/* Reuse the buffer for the next operation by
* setting its free count to the total buffer size
* and the current position to zero. */
buf->free += buf->len;
buf->len = 0;
}
mp_buf_free(L, buf);
/* Concatenate all nargs buffers together */
lua_concat(L, nargs);
return 1;
}
| 169,241 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __do_page_fault(struct mm_struct *mm, unsigned long addr,
unsigned int mm_flags, unsigned long vm_flags,
struct task_struct *tsk)
{
struct vm_area_struct *vma;
int fault;
vma = find_vma(mm, addr);
fault = VM_FAULT_BADMAP;
if (unlikely(!vma))
goto out;
if (unlikely(vma->vm_start > addr))
goto check_stack;
/*
* Ok, we have a good vm_area for this memory access, so we can handle
* it.
*/
good_area:
/*
* Check that the permissions on the VMA allow for the fault which
* occurred.
*/
if (!(vma->vm_flags & vm_flags)) {
fault = VM_FAULT_BADACCESS;
goto out;
}
return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags);
check_stack:
if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr))
goto good_area;
out:
return fault;
}
Commit Message: Revert "arm64: Introduce execute-only page access permissions"
This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08.
While the aim is increased security for --x memory maps, it does not
protect against kernel level reads. Until SECCOMP is implemented for
arm64, revert this patch to avoid giving a false idea of execute-only
mappings.
Signed-off-by: Catalin Marinas <[email protected]>
CWE ID: CWE-19 | static int __do_page_fault(struct mm_struct *mm, unsigned long addr,
unsigned int mm_flags, unsigned long vm_flags,
struct task_struct *tsk)
{
struct vm_area_struct *vma;
int fault;
vma = find_vma(mm, addr);
fault = VM_FAULT_BADMAP;
if (unlikely(!vma))
goto out;
if (unlikely(vma->vm_start > addr))
goto check_stack;
/*
* Ok, we have a good vm_area for this memory access, so we can handle
* it.
*/
good_area:
/*
* Check that the permissions on the VMA allow for the fault which
* occurred. If we encountered a write or exec fault, we must have
* appropriate permissions, otherwise we allow any permission.
*/
if (!(vma->vm_flags & vm_flags)) {
fault = VM_FAULT_BADACCESS;
goto out;
}
return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags);
check_stack:
if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr))
goto good_area;
out:
return fault;
}
| 167,583 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)
{
zval** ele_value = NULL;
if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if(Z_TYPE_PP(ele_value)!= IS_STRING ){
/* element value is not a string */
return FAILURE;
}
if(strcmp(key_name, LOC_LANG_TAG) != 0 &&
strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {
/* not lang or grandfathered tag */
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
}
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
}
return LOC_NOT_FOUND;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)
{
zval** ele_value = NULL;
if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if(Z_TYPE_PP(ele_value)!= IS_STRING ){
/* element value is not a string */
return FAILURE;
}
if(strcmp(key_name, LOC_LANG_TAG) != 0 &&
strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {
/* not lang or grandfathered tag */
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
}
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
}
return LOC_NOT_FOUND;
}
| 167,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (is_swapped_out_) {
if (request.url() != GURL("about:swappedout"))
return WebKit::WebNavigationPolicyIgnore;
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
if (!frame->parent() && is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
request.httpMethod() == "GET" && !url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
bool should_fork =
(enabled_bindings_ & content::BINDINGS_POLICY_WEB_UI) ||
frame->isViewSourceModeEnabled() ||
url.SchemeIs(chrome::kViewSourceScheme);
if (!should_fork) {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (is_swapped_out_) {
if (request.url() != GURL("about:swappedout"))
return WebKit::WebNavigationPolicyIgnore;
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
// top-level navigations (not iframes). But we sometimes navigate to
// about:blank to clear a tab, and we want to still allow that.
// Note: this is known to break POST submissions when crossing process
// boundaries until http://crbug.com/101395 is fixed. This is better for
// security than loading a WebUI, extension or app page in the wrong process.
// POST requests don't work because this mechanism does not preserve form
// POST data. We will need to send the request's httpBody data up to the
// browser process, and issue a special POST navigation in WebKit (via
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
// All navigations to WebUI URLs or within WebUI-enabled RenderProcesses
// must be handled by the browser process so that the correct bindings and
// data sources can be registered.
// Similarly, navigations to view-source URLs or within ViewSource mode
// must be handled by the browser process.
int cumulative_bindings =
RenderProcess::current()->GetEnabledBindings();
bool should_fork =
content::GetContentClient()->HasWebUIScheme(url) ||
(cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
frame->isViewSourceModeEnabled();
if (!should_fork) {
// For now, we skip this for POST submissions. This is because
// http://crbug.com/101395 is more likely to cause compatibility issues
// with hosted apps and extensions than WebUI pages. We will remove this
// check when cross-process POST submissions are supported.
if (request.httpMethod() == "GET") {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
| 171,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GesturePoint::IsSecondClickInsideManhattanSquare(
const TouchEvent& event) const {
int manhattanDistance = abs(event.x() - last_tap_position_.x()) +
abs(event.y() - last_tap_position_.y());
return manhattanDistance < kMaximumTouchMoveInPixelsForClick;
}
Commit Message: Add setters for the aura gesture recognizer constants.
BUG=113227
TEST=none
Review URL: http://codereview.chromium.org/9372040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool GesturePoint::IsSecondClickInsideManhattanSquare(
const TouchEvent& event) const {
int manhattanDistance = abs(event.x() - last_tap_position_.x()) +
abs(event.y() - last_tap_position_.y());
return manhattanDistance <
GestureConfiguration::max_touch_move_in_pixels_for_click();
}
| 171,046 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_expand_16_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* expand_16 does something unless the bit depth is already 16. */
return bit_depth < 16;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_expand_16_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* expand_16 does something unless the bit depth is already 16. */
return bit_depth < 16;
}
| 173,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
int bit_depth, unsigned int npalette, int interlace_type,
png_uint_32 w, png_uint_32 h, int do_interlace)
{
pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
if (npalette > 0)
{
pos = safecat(buffer, bufsize, pos, "[");
pos = safecatn(buffer, bufsize, pos, npalette);
pos = safecat(buffer, bufsize, pos, "]");
}
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, bit_depth);
pos = safecat(buffer, bufsize, pos, " bit");
if (interlace_type != PNG_INTERLACE_NONE)
{
pos = safecat(buffer, bufsize, pos, " interlaced");
if (do_interlace)
pos = safecat(buffer, bufsize, pos, "(pngvalid)");
else
pos = safecat(buffer, bufsize, pos, "(libpng)");
}
if (w > 0 || h > 0)
{
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, w);
pos = safecat(buffer, bufsize, pos, "x");
pos = safecatn(buffer, bufsize, pos, h);
}
return pos;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
int bit_depth, unsigned int npalette, int interlace_type,
png_uint_32 w, png_uint_32 h, int do_interlace)
{
pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
if (colour_type == 3) /* must have a palette */
{
pos = safecat(buffer, bufsize, pos, "[");
pos = safecatn(buffer, bufsize, pos, npalette);
pos = safecat(buffer, bufsize, pos, "]");
}
else if (npalette != 0)
pos = safecat(buffer, bufsize, pos, "+tRNS");
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, bit_depth);
pos = safecat(buffer, bufsize, pos, " bit");
if (interlace_type != PNG_INTERLACE_NONE)
{
pos = safecat(buffer, bufsize, pos, " interlaced");
if (do_interlace)
pos = safecat(buffer, bufsize, pos, "(pngvalid)");
else
pos = safecat(buffer, bufsize, pos, "(libpng)");
}
if (w > 0 || h > 0)
{
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, w);
pos = safecat(buffer, bufsize, pos, "x");
pos = safecatn(buffer, bufsize, pos, h);
}
return pos;
}
| 173,700 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int flakey_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg)
{
struct flakey_c *fc = ti->private;
return __blkdev_driver_ioctl(fc->dev->bdev, fc->dev->mode, cmd, arg);
}
Commit Message: dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int flakey_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg)
{
struct flakey_c *fc = ti->private;
struct dm_dev *dev = fc->dev;
int r = 0;
/*
* Only pass ioctls through if the device sizes match exactly.
*/
if (fc->start ||
ti->len != i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT)
r = scsi_verify_blk_ioctl(NULL, cmd);
return r ? : __blkdev_driver_ioctl(dev->bdev, dev->mode, cmd, arg);
}
| 165,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BaseAudioContext::Initialize() {
if (IsDestinationInitialized())
return;
FFTFrame::Initialize();
audio_worklet_ = AudioWorklet::Create(this);
if (destination_node_) {
destination_node_->Handler().Initialize();
listener_ = AudioListener::Create(*this);
}
}
Commit Message: Audio thread should not access destination node
The AudioDestinationNode is an object managed by Oilpan so the audio
thread should not access it. However, the audio thread needs
information (currentTime, etc) from the destination node. So instead
of accessing the audio destination handler (a scoped_refptr) via the
destination node, add a new member to the base audio context that
holds onto the destination handler.
The destination handler is not an oilpan object and lives at least as
long as the base audio context.
Bug: 860626, 860522, 863951
Test: Test case from 860522 doesn't crash on asan build
Change-Id: I3add844d4eb8fdc7e05b89292938b843a0abbb99
Reviewed-on: https://chromium-review.googlesource.com/1138974
Commit-Queue: Raymond Toy <[email protected]>
Reviewed-by: Hongchan Choi <[email protected]>
Cr-Commit-Position: refs/heads/master@{#575509}
CWE ID: CWE-416 | void BaseAudioContext::Initialize() {
if (IsDestinationInitialized())
return;
FFTFrame::Initialize();
audio_worklet_ = AudioWorklet::Create(this);
if (destination_node_) {
destination_node_->Handler().Initialize();
// TODO(crbug.com/863951). The audio thread needs some things from the
// destination handler like the currentTime. But the audio thread
// shouldn't access the |destination_node_| since it's an Oilpan object.
// Thus, get the destination handler, a non-oilpan object, so we can get
// the items directly from the handler instead of through the destination
// node.
destination_handler_ = &destination_node_->GetAudioDestinationHandler();
listener_ = AudioListener::Create(*this);
}
}
| 173,175 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
int new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
uint32_t new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
| 165,496 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionTtsPlatformImpl::set_error(const std::string& error) {
error_ = error;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ExtensionTtsPlatformImpl::set_error(const std::string& error) {
| 170,395 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _zip_cdir_new(int nentry, struct zip_error *error)
{
struct zip_cdir *cd;
if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
return NULL;
}
if ((cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*nentry))
== NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
free(cd);
return NULL;
}
/* entries must be initialized by caller */
cd->nentry = nentry;
cd->size = cd->offset = 0;
cd->comment = NULL;
cd->comment_len = 0;
return cd;
}
Commit Message:
CWE ID: CWE-189 | _zip_cdir_new(int nentry, struct zip_error *error)
{
struct zip_cdir *cd;
if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
return NULL;
}
if ( nentry > ((size_t)-1)/sizeof(*(cd->entry)) || (cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*(size_t)nentry))
== NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
free(cd);
return NULL;
}
/* entries must be initialized by caller */
cd->nentry = nentry;
cd->size = cd->offset = 0;
cd->comment = NULL;
cd->comment_len = 0;
return cd;
}
| 164,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Cues::Init() const
{
if (m_cue_points)
return;
assert(m_count == 0);
assert(m_preload_count == 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop)
{
const long long idpos = pos;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); //TODO
assert((pos + len) <= stop);
pos += len; //consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; //consume Size field
assert((pos + size) <= stop);
if (id == 0x3B) //CuePoint ID
PreloadCuePoint(cue_points_size, idpos);
pos += size; //consume payload
assert(pos <= stop);
}
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Cues::Init() const
long len;
const long long id = ReadUInt(pReader, m_pos, len);
assert(id >= 0); // TODO
assert((m_pos + len) <= stop);
m_pos += len; // consume ID
const long long size = ReadUInt(pReader, m_pos, len);
assert(size >= 0);
assert((m_pos + len) <= stop);
m_pos += len; // consume Size field
assert((m_pos + size) <= stop);
if (id != 0x3B) { // CuePoint ID
m_pos += size; // consume payload
assert(m_pos <= stop);
| 174,390 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PluginInfoMessageFilter::Context::GrantAccess(
const ChromeViewHostMsg_GetPluginInfo_Status& status,
const FilePath& path) const {
if (status.value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
status.value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay) {
ChromePluginServiceFilter::GetInstance()->AuthorizePlugin(
render_process_id_, path);
}
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | void PluginInfoMessageFilter::Context::GrantAccess(
void PluginInfoMessageFilter::Context::MaybeGrantAccess(
const ChromeViewHostMsg_GetPluginInfo_Status& status,
const FilePath& path) const {
if (status.value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
status.value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay) {
ChromePluginServiceFilter::GetInstance()->AuthorizePlugin(
render_process_id_, path);
}
}
| 171,472 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf)
{
fz_stream *file = doc->file;
int64_t ofs;
int len;
char *s;
size_t n;
pdf_token tok;
int64_t i;
int c;
int xref_len = pdf_xref_size_from_old_trailer(ctx, doc, buf);
pdf_xref_entry *table;
int carried;
fz_skip_space(ctx, doc->file);
if (fz_skip_string(ctx, doc->file, "xref"))
fz_throw(ctx, FZ_ERROR_GENERIC, "cannot find xref marker");
fz_skip_space(ctx, doc->file);
while (1)
{
c = fz_peek_byte(ctx, file);
if (!(c >= '0' && c <= '9'))
break;
fz_read_line(ctx, file, buf->scratch, buf->size);
s = buf->scratch;
ofs = fz_atoi64(fz_strsep(&s, " "));
len = fz_atoi(fz_strsep(&s, " "));
/* broken pdfs where the section is not on a separate line */
if (s && *s != '\0')
{
fz_warn(ctx, "broken xref section. proceeding anyway.");
fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR);
}
if (ofs < 0)
fz_throw(ctx, FZ_ERROR_GENERIC, "out of range object num in xref: %d", (int)ofs);
if (ofs > INT64_MAX - len)
fz_throw(ctx, FZ_ERROR_GENERIC, "xref section object numbers too big");
/* broken pdfs where size in trailer undershoots entries in xref sections */
if (ofs + len > xref_len)
{
}
table = pdf_xref_find_subsection(ctx, doc, ofs, len);
/* Xref entries SHOULD be 20 bytes long, but we see 19 byte
* ones more frequently than we'd like (e.g. PCLm drivers).
* Cope with this by 'carrying' data forward. */
carried = 0;
for (i = ofs; i < ofs + len; i++)
{
pdf_xref_entry *entry = &table[i-ofs];
n = fz_read(ctx, file, (unsigned char *) buf->scratch + carried, 20-carried);
if (n != 20-carried)
fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected EOF in xref table");
n += carried;
if (!entry->type)
{
s = buf->scratch;
/* broken pdfs where line start with white space */
while (*s != '\0' && iswhite(*s))
s++;
entry->ofs = fz_atoi64(s);
entry->gen = fz_atoi(s + 11);
entry->num = (int)i;
entry->type = s[17];
if (s[17] != 'f' && s[17] != 'n' && s[17] != 'o')
fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected xref type: 0x%x (%d %d R)", s[17], entry->num, entry->gen);
/* If the last byte of our buffer isn't an EOL (or space), carry one byte forward */
carried = s[19] > 32;
if (carried)
s[0] = s[19];
}
}
if (carried)
fz_unread_byte(ctx, file);
}
tok = pdf_lex(ctx, file, buf);
if (tok != PDF_TOK_TRAILER)
fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer marker");
tok = pdf_lex(ctx, file, buf);
if (tok != PDF_TOK_OPEN_DICT)
fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer dictionary");
return pdf_parse_dict(ctx, doc, file, buf);
}
Commit Message:
CWE ID: CWE-119 | pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf)
{
fz_stream *file = doc->file;
int64_t ofs;
int len;
char *s;
size_t n;
pdf_token tok;
int64_t i;
int c;
int xref_len = pdf_xref_size_from_old_trailer(ctx, doc, buf);
pdf_xref_entry *table;
int carried;
fz_skip_space(ctx, doc->file);
if (fz_skip_string(ctx, doc->file, "xref"))
fz_throw(ctx, FZ_ERROR_GENERIC, "cannot find xref marker");
fz_skip_space(ctx, doc->file);
while (1)
{
c = fz_peek_byte(ctx, file);
if (!(c >= '0' && c <= '9'))
break;
fz_read_line(ctx, file, buf->scratch, buf->size);
s = buf->scratch;
ofs = fz_atoi64(fz_strsep(&s, " "));
len = fz_atoi(fz_strsep(&s, " "));
/* broken pdfs where the section is not on a separate line */
if (s && *s != '\0')
{
fz_warn(ctx, "broken xref section. proceeding anyway.");
fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR);
}
if (ofs < 0 || ofs > PDF_MAX_OBJECT_NUMBER
|| len < 0 || len > PDF_MAX_OBJECT_NUMBER
|| ofs + len - 1 > PDF_MAX_OBJECT_NUMBER)
{
fz_throw(ctx, FZ_ERROR_GENERIC, "xref subsection object numbers are out of range");
}
/* broken pdfs where size in trailer undershoots entries in xref sections */
if (ofs + len > xref_len)
{
}
table = pdf_xref_find_subsection(ctx, doc, ofs, len);
/* Xref entries SHOULD be 20 bytes long, but we see 19 byte
* ones more frequently than we'd like (e.g. PCLm drivers).
* Cope with this by 'carrying' data forward. */
carried = 0;
for (i = ofs; i < ofs + len; i++)
{
pdf_xref_entry *entry = &table[i-ofs];
n = fz_read(ctx, file, (unsigned char *) buf->scratch + carried, 20-carried);
if (n != 20-carried)
fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected EOF in xref table");
n += carried;
if (!entry->type)
{
s = buf->scratch;
/* broken pdfs where line start with white space */
while (*s != '\0' && iswhite(*s))
s++;
entry->ofs = fz_atoi64(s);
entry->gen = fz_atoi(s + 11);
entry->num = (int)i;
entry->type = s[17];
if (s[17] != 'f' && s[17] != 'n' && s[17] != 'o')
fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected xref type: 0x%x (%d %d R)", s[17], entry->num, entry->gen);
/* If the last byte of our buffer isn't an EOL (or space), carry one byte forward */
carried = s[19] > 32;
if (carried)
s[0] = s[19];
}
}
if (carried)
fz_unread_byte(ctx, file);
}
tok = pdf_lex(ctx, file, buf);
if (tok != PDF_TOK_TRAILER)
fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer marker");
tok = pdf_lex(ctx, file, buf);
if (tok != PDF_TOK_OPEN_DICT)
fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer dictionary");
return pdf_parse_dict(ctx, doc, file, buf);
}
| 165,391 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TestNativeHandler::TestNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetWakeEventPage",
base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | TestNativeHandler::TestNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetWakeEventPage", "test",
base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
}
| 172,255 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserViewRenderer::SetTotalRootLayerScrollOffset(
gfx::Vector2dF scroll_offset_dip) {
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2d scroll_offset;
if (max_scroll_offset_dip_.x()) {
scroll_offset.set_x((scroll_offset_dip.x() * max_offset.x()) /
max_scroll_offset_dip_.x());
}
if (max_scroll_offset_dip_.y()) {
scroll_offset.set_y((scroll_offset_dip.y() * max_offset.y()) /
max_scroll_offset_dip_.y());
}
DCHECK_LE(0, scroll_offset.x());
DCHECK_LE(0, scroll_offset.y());
DCHECK_LE(scroll_offset.x(), max_offset.x());
DCHECK_LE(scroll_offset.y(), max_offset.y());
client_->ScrollContainerViewTo(scroll_offset);
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | void BrowserViewRenderer::SetTotalRootLayerScrollOffset(
const gfx::Vector2dF& scroll_offset_dip) {
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2d scroll_offset;
if (max_scroll_offset_dip_.x()) {
scroll_offset.set_x((scroll_offset_dip.x() * max_offset.x()) /
max_scroll_offset_dip_.x());
}
if (max_scroll_offset_dip_.y()) {
scroll_offset.set_y((scroll_offset_dip.y() * max_offset.y()) /
max_scroll_offset_dip_.y());
}
DCHECK_LE(0, scroll_offset.x());
DCHECK_LE(0, scroll_offset.y());
DCHECK_LE(scroll_offset.x(), max_offset.x());
DCHECK_LE(scroll_offset.y(), max_offset.y());
client_->ScrollContainerViewTo(scroll_offset);
}
| 171,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool BackgroundLoaderOffliner::LoadAndSave(
const SavePageRequest& request,
CompletionCallback completion_callback,
const ProgressCallback& progress_callback) {
DCHECK(completion_callback);
DCHECK(progress_callback);
DCHECK(offline_page_model_);
if (pending_request_) {
DVLOG(1) << "Already have pending request";
return false;
}
ClientPolicyController* policy_controller =
offline_page_model_->GetPolicyController();
if (policy_controller->RequiresSpecificUserSettings(
request.client_id().name_space) &&
(AreThirdPartyCookiesBlocked(browser_context_) ||
IsNetworkPredictionDisabled(browser_context_))) {
DVLOG(1) << "WARNING: Unable to load when 3rd party cookies blocked or "
<< "prediction disabled";
if (AreThirdPartyCookiesBlocked(browser_context_)) {
UMA_HISTOGRAM_ENUMERATION(
"OfflinePages.Background.CctApiDisableStatus",
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
THIRD_PARTY_COOKIES_DISABLED),
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED) +
1);
}
if (IsNetworkPredictionDisabled(browser_context_)) {
UMA_HISTOGRAM_ENUMERATION(
"OfflinePages.Background.CctApiDisableStatus",
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED),
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED) +
1);
}
return false;
}
if (request.client_id().name_space == kCCTNamespace) {
UMA_HISTOGRAM_ENUMERATION(
"OfflinePages.Background.CctApiDisableStatus",
static_cast<int>(
OfflinePagesCctApiPrerenderAllowedStatus::PRERENDER_ALLOWED),
static_cast<int>(OfflinePagesCctApiPrerenderAllowedStatus::
NETWORK_PREDICTION_DISABLED) +
1);
}
if (!OfflinePageModel::CanSaveURL(request.url())) {
DVLOG(1) << "Not able to save page for requested url: " << request.url();
return false;
}
ResetLoader();
AttachObservers();
MarkLoadStartTime();
pending_request_.reset(new SavePageRequest(request));
completion_callback_ = std::move(completion_callback);
progress_callback_ = progress_callback;
if (IsOfflinePagesRenovationsEnabled()) {
if (!page_renovation_loader_)
page_renovation_loader_ = std::make_unique<PageRenovationLoader>();
auto script_injector = std::make_unique<RenderFrameScriptInjector>(
loader_->web_contents()->GetMainFrame(),
ISOLATED_WORLD_ID_CHROME_INTERNAL);
page_renovator_ = std::make_unique<PageRenovator>(
page_renovation_loader_.get(), std::move(script_injector),
request.url());
}
loader_.get()->LoadPage(request.url());
snapshot_controller_ = std::make_unique<BackgroundSnapshotController>(
base::ThreadTaskRunnerHandle::Get(), this,
static_cast<bool>(page_renovator_));
return true;
}
Commit Message: Remove unused histograms from the background loader offliner.
Bug: 975512
Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361
Reviewed-by: Cathy Li <[email protected]>
Reviewed-by: Steven Holte <[email protected]>
Commit-Queue: Peter Williamson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#675332}
CWE ID: CWE-119 | bool BackgroundLoaderOffliner::LoadAndSave(
const SavePageRequest& request,
CompletionCallback completion_callback,
const ProgressCallback& progress_callback) {
DCHECK(completion_callback);
DCHECK(progress_callback);
DCHECK(offline_page_model_);
if (pending_request_) {
DVLOG(1) << "Already have pending request";
return false;
}
ClientPolicyController* policy_controller =
offline_page_model_->GetPolicyController();
if (policy_controller->RequiresSpecificUserSettings(
request.client_id().name_space) &&
(AreThirdPartyCookiesBlocked(browser_context_) ||
IsNetworkPredictionDisabled(browser_context_))) {
DVLOG(1) << "WARNING: Unable to load when 3rd party cookies blocked or "
<< "prediction disabled";
return false;
}
if (!OfflinePageModel::CanSaveURL(request.url())) {
DVLOG(1) << "Not able to save page for requested url: " << request.url();
return false;
}
ResetLoader();
AttachObservers();
MarkLoadStartTime();
pending_request_.reset(new SavePageRequest(request));
completion_callback_ = std::move(completion_callback);
progress_callback_ = progress_callback;
if (IsOfflinePagesRenovationsEnabled()) {
if (!page_renovation_loader_)
page_renovation_loader_ = std::make_unique<PageRenovationLoader>();
auto script_injector = std::make_unique<RenderFrameScriptInjector>(
loader_->web_contents()->GetMainFrame(),
ISOLATED_WORLD_ID_CHROME_INTERNAL);
page_renovator_ = std::make_unique<PageRenovator>(
page_renovation_loader_.get(), std::move(script_injector),
request.url());
}
loader_.get()->LoadPage(request.url());
snapshot_controller_ = std::make_unique<BackgroundSnapshotController>(
base::ThreadTaskRunnerHandle::Get(), this,
static_cast<bool>(page_renovator_));
return true;
}
| 172,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool tight_can_send_png_rect(VncState *vs, int w, int h)
{
if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) {
return false;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->clientds.pf.bytes_per_pixel == 1) {
return false;
}
return true;
}
Commit Message:
CWE ID: CWE-125 | static bool tight_can_send_png_rect(VncState *vs, int w, int h)
{
if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) {
return false;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->client_pf.bytes_per_pixel == 1) {
return false;
}
return true;
}
| 165,463 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: checked_xcalloc (size_t num, size_t size)
{
alloc_limit_assert ("checked_xcalloc", (num *size));
return xcalloc (num, size);
}
Commit Message: Fix integer overflows and harden memory allocator.
CWE ID: CWE-190 | checked_xcalloc (size_t num, size_t size)
{
size_t res;
if (check_mul_overflow(num, size, &res))
abort();
alloc_limit_assert ("checked_xcalloc", (res));
return xcalloc (num, size);
}
| 168,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CreateDataReductionProxyChromeIOData(
Profile* profile,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(profile);
DCHECK(profile->GetPrefs());
data_reduction_proxy::DataReductionProxySettings*
data_reduction_proxy_settings =
DataReductionProxyChromeSettingsFactory::GetForBrowserContext(
profile);
bool enabled = data_reduction_proxy_settings &&
data_reduction_proxy_settings->IsDataSaverEnabledByUser();
std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData>
data_reduction_proxy_io_data(
new data_reduction_proxy::DataReductionProxyIOData(
DataReductionProxyChromeSettings::GetClient(),
profile->GetPrefs(), content::GetNetworkConnectionTracker(),
io_task_runner, ui_task_runner, enabled, GetUserAgent(),
version_info::GetChannelString(chrome::GetChannel())));
data_reduction_proxy_io_data->set_lofi_decider(
std::make_unique<data_reduction_proxy::ContentLoFiDecider>());
data_reduction_proxy_io_data->set_resource_type_provider(
std::make_unique<data_reduction_proxy::ContentResourceTypeProvider>());
data_reduction_proxy_io_data->set_lofi_ui_service(
std::make_unique<data_reduction_proxy::ContentLoFiUIService>(
ui_task_runner, base::Bind(&OnLoFiResponseReceivedOnUI)));
return data_reduction_proxy_io_data;
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | CreateDataReductionProxyChromeIOData(
Profile* profile,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(profile);
DCHECK(profile->GetPrefs());
bool enabled = data_reduction_proxy::DataReductionProxySettings::
IsDataSaverEnabledByUser(profile->GetPrefs());
std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData>
data_reduction_proxy_io_data(
new data_reduction_proxy::DataReductionProxyIOData(
DataReductionProxyChromeSettings::GetClient(),
profile->GetPrefs(), content::GetNetworkConnectionTracker(),
io_task_runner, ui_task_runner, enabled, GetUserAgent(),
version_info::GetChannelString(chrome::GetChannel())));
data_reduction_proxy_io_data->set_lofi_decider(
std::make_unique<data_reduction_proxy::ContentLoFiDecider>());
data_reduction_proxy_io_data->set_resource_type_provider(
std::make_unique<data_reduction_proxy::ContentResourceTypeProvider>());
data_reduction_proxy_io_data->set_lofi_ui_service(
std::make_unique<data_reduction_proxy::ContentLoFiUIService>(
ui_task_runner, base::Bind(&OnLoFiResponseReceivedOnUI)));
return data_reduction_proxy_io_data;
}
| 172,549 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static UINT drdynvc_order_recv(drdynvcPlugin* drdynvc, wStream* s)
{
int value;
int Cmd;
int Sp;
int cbChId;
Stream_Read_UINT8(s, value);
Cmd = (value & 0xf0) >> 4;
Sp = (value & 0x0c) >> 2;
cbChId = (value & 0x03) >> 0;
WLog_Print(drdynvc->log, WLOG_DEBUG, "order_recv: Cmd=0x%x, Sp=%d cbChId=%d", Cmd, Sp, cbChId);
switch (Cmd)
{
case CAPABILITY_REQUEST_PDU:
return drdynvc_process_capability_request(drdynvc, Sp, cbChId, s);
case CREATE_REQUEST_PDU:
return drdynvc_process_create_request(drdynvc, Sp, cbChId, s);
case DATA_FIRST_PDU:
return drdynvc_process_data_first(drdynvc, Sp, cbChId, s);
case DATA_PDU:
return drdynvc_process_data(drdynvc, Sp, cbChId, s);
case CLOSE_REQUEST_PDU:
return drdynvc_process_close_request(drdynvc, Sp, cbChId, s);
default:
WLog_Print(drdynvc->log, WLOG_ERROR, "unknown drdynvc cmd 0x%x", Cmd);
return ERROR_INTERNAL_ERROR;
}
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_order_recv(drdynvcPlugin* drdynvc, wStream* s)
{
int value;
int Cmd;
int Sp;
int cbChId;
if (Stream_GetRemainingLength(s) < 1)
return ERROR_INVALID_DATA;
Stream_Read_UINT8(s, value);
Cmd = (value & 0xf0) >> 4;
Sp = (value & 0x0c) >> 2;
cbChId = (value & 0x03) >> 0;
WLog_Print(drdynvc->log, WLOG_DEBUG, "order_recv: Cmd=0x%x, Sp=%d cbChId=%d", Cmd, Sp, cbChId);
switch (Cmd)
{
case CAPABILITY_REQUEST_PDU:
return drdynvc_process_capability_request(drdynvc, Sp, cbChId, s);
case CREATE_REQUEST_PDU:
return drdynvc_process_create_request(drdynvc, Sp, cbChId, s);
case DATA_FIRST_PDU:
return drdynvc_process_data_first(drdynvc, Sp, cbChId, s);
case DATA_PDU:
return drdynvc_process_data(drdynvc, Sp, cbChId, s);
case CLOSE_REQUEST_PDU:
return drdynvc_process_close_request(drdynvc, Sp, cbChId, s);
default:
WLog_Print(drdynvc->log, WLOG_ERROR, "unknown drdynvc cmd 0x%x", Cmd);
return ERROR_INTERNAL_ERROR;
}
}
| 168,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error)
{
int len;
int i;
len = g_strv_length ((char**) in);
*out = g_new0 (char *, len + 1);
for (i = 0; i < len; i++)
{
(*out)[i] = g_ascii_strup (in[i], -1);
}
(*out)[i] = NULL;
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error)
| 165,113 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual InputMethodDescriptors* GetActiveInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual InputMethodDescriptors* GetActiveInputMethods() {
virtual input_method::InputMethodDescriptors* GetActiveInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
| 170,487 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks() {
TRACE_EVENT0(
"cc", "PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks");
DCHECK(should_notify_client_if_no_tasks_are_pending_);
check_for_completed_raster_tasks_callback_.Cancel();
check_for_completed_raster_tasks_pending_ = false;
CheckForCompletedWorkerTasks();
CheckForCompletedUploads();
FlushUploads();
bool will_notify_client_that_no_tasks_required_for_activation_are_pending =
(should_notify_client_if_no_tasks_required_for_activation_are_pending_ &&
!HasPendingTasksRequiredForActivation());
bool will_notify_client_that_no_tasks_are_pending =
(should_notify_client_if_no_tasks_are_pending_ &&
!HasPendingTasks());
should_notify_client_if_no_tasks_required_for_activation_are_pending_ &=
!will_notify_client_that_no_tasks_required_for_activation_are_pending;
should_notify_client_if_no_tasks_are_pending_ &=
!will_notify_client_that_no_tasks_are_pending;
scheduled_raster_task_count_ = 0;
if (PendingRasterTaskCount())
ScheduleMoreTasks();
TRACE_EVENT_ASYNC_STEP_INTO1(
"cc", "ScheduledTasks", this, StateName(),
"state", TracedValue::FromValue(StateAsValue().release()));
if (HasPendingTasks())
ScheduleCheckForCompletedRasterTasks();
if (will_notify_client_that_no_tasks_required_for_activation_are_pending) {
DCHECK(std::find_if(raster_tasks_required_for_activation().begin(),
raster_tasks_required_for_activation().end(),
WasCanceled) ==
raster_tasks_required_for_activation().end());
client()->DidFinishRunningTasksRequiredForActivation();
}
if (will_notify_client_that_no_tasks_are_pending) {
TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this);
DCHECK(!HasPendingTasksRequiredForActivation());
client()->DidFinishRunningTasks();
}
}
Commit Message: cc: Simplify raster task completion notification logic
(Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/)
Previously the pixel buffer raster worker pool used a combination of
polling and explicit notifications from the raster worker pool to decide
when to tell the client about the completion of 1) all tasks or 2) the
subset of tasks required for activation. This patch simplifies the logic
by only triggering the notification based on the OnRasterTasksFinished
and OnRasterTasksRequiredForActivationFinished calls from the worker
pool.
BUG=307841,331534
Review URL: https://codereview.chromium.org/99873007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks() {
TRACE_EVENT0(
"cc", "PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks");
DCHECK(should_notify_client_if_no_tasks_are_pending_);
check_for_completed_raster_tasks_callback_.Cancel();
check_for_completed_raster_tasks_pending_ = false;
CheckForCompletedWorkerTasks();
CheckForCompletedUploads();
FlushUploads();
bool will_notify_client_that_no_tasks_required_for_activation_are_pending =
(should_notify_client_if_no_tasks_required_for_activation_are_pending_ &&
!raster_required_for_activation_finished_task_pending_ &&
!HasPendingTasksRequiredForActivation());
bool will_notify_client_that_no_tasks_are_pending =
(should_notify_client_if_no_tasks_are_pending_ &&
!raster_finished_task_pending_ &&
!HasPendingTasks());
should_notify_client_if_no_tasks_required_for_activation_are_pending_ &=
!will_notify_client_that_no_tasks_required_for_activation_are_pending;
should_notify_client_if_no_tasks_are_pending_ &=
!will_notify_client_that_no_tasks_are_pending;
scheduled_raster_task_count_ = 0;
if (PendingRasterTaskCount())
ScheduleMoreTasks();
TRACE_EVENT_ASYNC_STEP_INTO1(
"cc", "ScheduledTasks", this, StateName(),
"state", TracedValue::FromValue(StateAsValue().release()));
if (HasPendingTasks())
ScheduleCheckForCompletedRasterTasks();
if (will_notify_client_that_no_tasks_required_for_activation_are_pending) {
DCHECK(std::find_if(raster_tasks_required_for_activation().begin(),
raster_tasks_required_for_activation().end(),
WasCanceled) ==
raster_tasks_required_for_activation().end());
client()->DidFinishRunningTasksRequiredForActivation();
}
if (will_notify_client_that_no_tasks_are_pending) {
TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this);
DCHECK(!HasPendingTasksRequiredForActivation());
client()->DidFinishRunningTasks();
}
}
| 171,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: InputMethodStatusConnection()
: current_input_method_changed_(NULL),
register_ime_properties_(NULL),
update_ime_property_(NULL),
connection_change_handler_(NULL),
language_library_(NULL),
ibus_(NULL),
ibus_config_(NULL) {
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | InputMethodStatusConnection()
// Functions that end with Thunk are used to deal with glib callbacks.
//
// Note that we cannot use CHROMEG_CALLBACK_0() here as we'll define
// IBusBusConnected() inline. If we are to define the function outside
// of the class definition, we should use CHROMEG_CALLBACK_0() here.
//
// CHROMEG_CALLBACK_0(Impl,
// void, IBusBusConnected, IBusBus*);
static void IBusBusConnectedThunk(IBusBus* sender, gpointer userdata) {
return reinterpret_cast<IBusControllerImpl*>(userdata)
->IBusBusConnected(sender);
}
static void IBusBusDisconnectedThunk(IBusBus* sender, gpointer userdata) {
return reinterpret_cast<IBusControllerImpl*>(userdata)
->IBusBusDisconnected(sender);
}
static void IBusBusGlobalEngineChangedThunk(IBusBus* sender,
const gchar* engine_name,
gpointer userdata) {
return reinterpret_cast<IBusControllerImpl*>(userdata)
->IBusBusGlobalEngineChanged(sender, engine_name);
}
static void IBusBusNameOwnerChangedThunk(IBusBus* sender,
const gchar* name,
const gchar* old_name,
const gchar* new_name,
gpointer userdata) {
return reinterpret_cast<IBusControllerImpl*>(userdata)
->IBusBusNameOwnerChanged(sender, name, old_name, new_name);
}
static void FocusInThunk(IBusPanelService* sender,
const gchar* input_context_path,
gpointer userdata) {
return reinterpret_cast<IBusControllerImpl*>(userdata)
->FocusIn(sender, input_context_path);
}
static void RegisterPropertiesThunk(IBusPanelService* sender,
IBusPropList* prop_list,
gpointer userdata) {
return reinterpret_cast<IBusControllerImpl*>(userdata)
->RegisterProperties(sender, prop_list);
}
static void UpdatePropertyThunk(IBusPanelService* sender,
IBusProperty* ibus_prop,
gpointer userdata) {
return reinterpret_cast<IBusControllerImpl*>(userdata)
->UpdateProperty(sender, ibus_prop);
}
friend struct DefaultSingletonTraits<IBusControllerImpl>;
IBusControllerImpl()
: ibus_(NULL),
ibus_config_(NULL) {
}
| 170,540 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadMONOImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
x;
size_t
bit,
byte;
ssize_t
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
/*
Initialize image colormap.
*/
image->depth=1;
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(size_t) ReadBlobByte(image);
if (image_info->endian == LSBEndian)
SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x00 : 0x01)
else
SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x01 : 0x00)
bit++;
if (bit == 8)
bit=0;
byte>>=1;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadMONOImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
x;
size_t
bit,
byte;
ssize_t
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
/*
Initialize image colormap.
*/
image->depth=1;
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(size_t) ReadBlobByte(image);
if (image_info->endian == LSBEndian)
SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x00 : 0x01)
else
SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x01 : 0x00)
bit++;
if (bit == 8)
bit=0;
byte>>=1;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,582 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jslTokenAsString(int token, char *str, size_t len) {
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
espruino_snprintf(str, len, "?[%d]", token);
}
Commit Message: remove strncpy usage as it's effectively useless, replace with an assertion since fn is only used internally (fix #1426)
CWE ID: CWE-787 | void jslTokenAsString(int token, char *str, size_t len) {
assert(len>28); // size of largest string
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strcpy(str, "EOF"); return;
case LEX_ID : strcpy(str, "ID"); return;
case LEX_INT : strcpy(str, "INT"); return;
case LEX_FLOAT : strcpy(str, "FLOAT"); return;
case LEX_STR : strcpy(str, "STRING"); return;
case LEX_UNFINISHED_STR : strcpy(str, "UNFINISHED STRING"); return;
case LEX_TEMPLATE_LITERAL : strcpy(str, "TEMPLATE LITERAL"); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strcpy(str, "UNFINISHED TEMPLATE LITERAL"); return;
case LEX_REGEX : strcpy(str, "REGEX"); return;
case LEX_UNFINISHED_REGEX : strcpy(str, "UNFINISHED REGEX"); return;
case LEX_UNFINISHED_COMMENT : strcpy(str, "UNFINISHED COMMENT"); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strcpy(str, &tokenNames[p]);
return;
}
espruino_snprintf(str, len, "?[%d]", token);
}
| 169,215 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
int err;
u32 tsk_portid = cb->args[0];
u32 last_publ = cb->args[1];
u32 done = cb->args[2];
struct net *net = sock_net(skb->sk);
struct tipc_sock *tsk;
if (!tsk_portid) {
struct nlattr **attrs;
struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
err = tipc_nlmsg_parse(cb->nlh, &attrs);
if (err)
return err;
err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
attrs[TIPC_NLA_SOCK],
tipc_nl_sock_policy);
if (err)
return err;
if (!sock[TIPC_NLA_SOCK_REF])
return -EINVAL;
tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
}
if (done)
return 0;
tsk = tipc_sk_lookup(net, tsk_portid);
if (!tsk)
return -EINVAL;
lock_sock(&tsk->sk);
err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
if (!err)
done = 1;
release_sock(&tsk->sk);
sock_put(&tsk->sk);
cb->args[0] = tsk_portid;
cb->args[1] = last_publ;
cb->args[2] = done;
return skb->len;
}
Commit Message: tipc: check nl sock before parsing nested attributes
Make sure the socket for which the user is listing publication exists
before parsing the socket netlink attributes.
Prior to this patch a call without any socket caused a NULL pointer
dereference in tipc_nl_publ_dump().
Tested-and-reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Richard Alpe <[email protected]>
Acked-by: Jon Maloy <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
int err;
u32 tsk_portid = cb->args[0];
u32 last_publ = cb->args[1];
u32 done = cb->args[2];
struct net *net = sock_net(skb->sk);
struct tipc_sock *tsk;
if (!tsk_portid) {
struct nlattr **attrs;
struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
err = tipc_nlmsg_parse(cb->nlh, &attrs);
if (err)
return err;
if (!attrs[TIPC_NLA_SOCK])
return -EINVAL;
err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
attrs[TIPC_NLA_SOCK],
tipc_nl_sock_policy);
if (err)
return err;
if (!sock[TIPC_NLA_SOCK_REF])
return -EINVAL;
tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
}
if (done)
return 0;
tsk = tipc_sk_lookup(net, tsk_portid);
if (!tsk)
return -EINVAL;
lock_sock(&tsk->sk);
err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
if (!err)
done = 1;
release_sock(&tsk->sk);
sock_put(&tsk->sk);
cb->args[0] = tsk_portid;
cb->args[1] = last_publ;
cb->args[2] = done;
return skb->len;
}
| 167,223 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pud_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pud_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
| 170,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Plugin::Plugin(PP_Instance pp_instance)
: pp::InstancePrivate(pp_instance),
scriptable_plugin_(NULL),
argc_(-1),
argn_(NULL),
argv_(NULL),
main_subprocess_("main subprocess", NULL, NULL),
nacl_ready_state_(UNSENT),
nexe_error_reported_(false),
wrapper_factory_(NULL),
last_error_string_(""),
ppapi_proxy_(NULL),
enable_dev_interfaces_(false),
init_time_(0),
ready_time_(0),
nexe_size_(0),
time_of_last_progress_event_(0),
using_ipc_proxy_(false) {
PLUGIN_PRINTF(("Plugin::Plugin (this=%p, pp_instance=%"
NACL_PRId32")\n", static_cast<void*>(this), pp_instance));
callback_factory_.Initialize(this);
nexe_downloader_.Initialize(this);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | Plugin::Plugin(PP_Instance pp_instance)
: pp::InstancePrivate(pp_instance),
scriptable_plugin_(NULL),
argc_(-1),
argn_(NULL),
argv_(NULL),
main_subprocess_("main subprocess", NULL, NULL),
nacl_ready_state_(UNSENT),
nexe_error_reported_(false),
wrapper_factory_(NULL),
last_error_string_(""),
ppapi_proxy_(NULL),
enable_dev_interfaces_(false),
init_time_(0),
ready_time_(0),
nexe_size_(0),
time_of_last_progress_event_(0) {
PLUGIN_PRINTF(("Plugin::Plugin (this=%p, pp_instance=%"
NACL_PRId32")\n", static_cast<void*>(this), pp_instance));
callback_factory_.Initialize(this);
nexe_downloader_.Initialize(this);
}
| 170,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
if (ps_stream->u4_offset < ps_stream->u4_max_offset)
{
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
}
return;
}
Commit Message: Fixed out of bound read in flush_bits
Bug: 28168413
Change-Id: I3db5432a08daf665e160c0dab2d1928a576418b4
CWE ID: CWE-200 | INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
if ((ps_stream->u4_offset + 64) < ps_stream->u4_max_offset)
{
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
}
else
{
UWORD32 u4_temp;
if (((ps_stream->u4_offset & 0x1f) + u4_no_of_bits) >= 32)
{
ps_stream->u4_buf = ps_stream->u4_buf_nxt;
ps_stream->u4_buf_nxt = 0;
}
ps_stream->u4_offset += u4_no_of_bits;
}
return;
}
| 173,549 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && !ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && !ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (struct pgstate *)io;
}
return ((u_char *)ps <= ep? 0 : -1);
}
Commit Message: whiteboard: fixup a few reversed tests (GH #446)
This is a follow-up to commit 3a3ec26.
CWE ID: CWE-20 | wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (struct pgstate *)io;
}
return ((u_char *)ps <= ep? 0 : -1);
}
| 168,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
Commit Message: Fixed bug #72227: imagescale out-of-bounds read
Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a
CWE ID: CWE-125 | int gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
| 170,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
full_itxfm_ = GET_PARAM(0);
partial_itxfm_ = GET_PARAM(1);
tx_size_ = GET_PARAM(2);
last_nonzero_ = GET_PARAM(3);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
ftxfm_ = GET_PARAM(0);
full_itxfm_ = GET_PARAM(1);
partial_itxfm_ = GET_PARAM(2);
tx_size_ = GET_PARAM(3);
last_nonzero_ = GET_PARAM(4);
}
| 174,567 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap,
const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight,
UINT32 bpp, UINT32 length, BOOL compressed,
UINT32 codecId)
{
UINT32 SrcSize = length;
rdpGdi* gdi = context->gdi;
bitmap->compressed = FALSE;
bitmap->format = gdi->dstFormat;
bitmap->length = DstWidth * DstHeight * GetBytesPerPixel(bitmap->format);
bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16);
if (!bitmap->data)
return FALSE;
if (compressed)
{
if (bpp < 32)
{
if (!interleaved_decompress(context->codecs->interleaved,
pSrcData, SrcSize,
DstWidth, DstHeight,
bpp,
bitmap->data, bitmap->format,
0, 0, 0, DstWidth, DstHeight,
&gdi->palette))
return FALSE;
}
else
{
if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize,
DstWidth, DstHeight,
bitmap->data, bitmap->format, 0, 0, 0,
DstWidth, DstHeight, TRUE))
return FALSE;
}
}
else
{
const UINT32 SrcFormat = gdi_get_pixel_format(bpp);
const size_t sbpp = GetBytesPerPixel(SrcFormat);
const size_t dbpp = GetBytesPerPixel(bitmap->format);
if ((sbpp == 0) || (dbpp == 0))
return FALSE;
else
{
const size_t dstSize = SrcSize * dbpp / sbpp;
if (dstSize < bitmap->length)
return FALSE;
}
if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0,
DstWidth, DstHeight, pSrcData, SrcFormat,
0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL))
return FALSE;
}
return TRUE;
}
Commit Message: Fixed CVE-2018-8787
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-190 | static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap,
const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight,
UINT32 bpp, UINT32 length, BOOL compressed,
UINT32 codecId)
{
UINT32 SrcSize = length;
rdpGdi* gdi = context->gdi;
UINT32 size = DstWidth * DstHeight;
bitmap->compressed = FALSE;
bitmap->format = gdi->dstFormat;
if ((GetBytesPerPixel(bitmap->format) == 0) ||
(DstWidth == 0) || (DstHeight == 0) || (DstWidth > UINT32_MAX / DstHeight) ||
(size > (UINT32_MAX / GetBytesPerPixel(bitmap->format))))
return FALSE;
size *= GetBytesPerPixel(bitmap->format);
bitmap->length = size;
bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16);
if (!bitmap->data)
return FALSE;
if (compressed)
{
if (bpp < 32)
{
if (!interleaved_decompress(context->codecs->interleaved,
pSrcData, SrcSize,
DstWidth, DstHeight,
bpp,
bitmap->data, bitmap->format,
0, 0, 0, DstWidth, DstHeight,
&gdi->palette))
return FALSE;
}
else
{
if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize,
DstWidth, DstHeight,
bitmap->data, bitmap->format, 0, 0, 0,
DstWidth, DstHeight, TRUE))
return FALSE;
}
}
else
{
const UINT32 SrcFormat = gdi_get_pixel_format(bpp);
const size_t sbpp = GetBytesPerPixel(SrcFormat);
const size_t dbpp = GetBytesPerPixel(bitmap->format);
if ((sbpp == 0) || (dbpp == 0))
return FALSE;
else
{
const size_t dstSize = SrcSize * dbpp / sbpp;
if (dstSize < bitmap->length)
return FALSE;
}
if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0,
DstWidth, DstHeight, pSrcData, SrcFormat,
0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL))
return FALSE;
}
return TRUE;
}
| 169,292 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct crypto_template *crypto_lookup_template(const char *name)
{
return try_then_request_module(__crypto_lookup_template(name), "%s",
name);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264 | struct crypto_template *crypto_lookup_template(const char *name)
{
return try_then_request_module(__crypto_lookup_template(name),
"crypto-%s", name);
}
| 166,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
PNG_CONST char *name)
{
/* Set the name for png_error */
safecat(ps->test, sizeof ps->test, 0, name);
if (ps->pread != NULL)
png_error(ps->pread, "read store already in use");
store_read_reset(ps);
/* Both the create APIs can return NULL if used in their default mode
* (because there is no other way of handling an error because the jmp_buf
* by default is stored in png_struct and that has not been allocated!)
* However, given that store_error works correctly in these circumstances
* we don't ever expect NULL in this program.
*/
# ifdef PNG_USER_MEM_SUPPORTED
if (!ps->speed)
ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
store_error, store_warning, &ps->read_memory_pool, store_malloc,
store_free);
else
# endif
ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
store_warning);
if (ps->pread == NULL)
{
struct exception_context *the_exception_context = &ps->exception_context;
store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
1 /*error*/);
Throw ps;
}
# ifdef PNG_SET_OPTION_SUPPORTED
{
int opt;
for (opt=0; opt<ps->noptions; ++opt)
if (png_set_option(ps->pread, ps->options[opt].option,
ps->options[opt].setting) == PNG_OPTION_INVALID)
png_error(ps->pread, "png option invalid");
}
# endif
store_read_set(ps, id);
if (ppi != NULL)
*ppi = ps->piread = png_create_info_struct(ps->pread);
return ps->pread;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
const char *name)
{
/* Set the name for png_error */
safecat(ps->test, sizeof ps->test, 0, name);
if (ps->pread != NULL)
png_error(ps->pread, "read store already in use");
store_read_reset(ps);
/* Both the create APIs can return NULL if used in their default mode
* (because there is no other way of handling an error because the jmp_buf
* by default is stored in png_struct and that has not been allocated!)
* However, given that store_error works correctly in these circumstances
* we don't ever expect NULL in this program.
*/
# ifdef PNG_USER_MEM_SUPPORTED
if (!ps->speed)
ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
store_error, store_warning, &ps->read_memory_pool, store_malloc,
store_free);
else
# endif
ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
store_warning);
if (ps->pread == NULL)
{
struct exception_context *the_exception_context = &ps->exception_context;
store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
1 /*error*/);
Throw ps;
}
# ifdef PNG_SET_OPTION_SUPPORTED
{
int opt;
for (opt=0; opt<ps->noptions; ++opt)
if (png_set_option(ps->pread, ps->options[opt].option,
ps->options[opt].setting) == PNG_OPTION_INVALID)
png_error(ps->pread, "png option invalid");
}
# endif
store_read_set(ps, id);
if (ppi != NULL)
*ppi = ps->piread = png_create_info_struct(ps->pread);
return ps->pread;
}
| 173,695 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned int SAD(unsigned int max_sad, int block_idx = 0) {
unsigned int ret;
const uint8_t* const reference = GetReference(block_idx);
REGISTER_STATE_CHECK(ret = GET_PARAM(2)(source_data_, source_stride_,
reference, reference_stride_,
max_sad));
return ret;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | unsigned int SAD(unsigned int max_sad, int block_idx = 0) {
| 174,575 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GaiaOAuthClient::Core::RefreshToken(
const OAuthClientInfo& oauth_client_info,
const std::string& refresh_token,
GaiaOAuthClient::Delegate* delegate) {
DCHECK(!request_.get()) << "Tried to fetch two things at once!";
delegate_ = delegate;
access_token_.clear();
expires_in_seconds_ = 0;
std::string post_body =
"refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) +
"&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
true) +
"&client_secret=" +
net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
"&grant_type=refresh_token";
request_.reset(new UrlFetcher(GURL(provider_info_.access_token_url),
UrlFetcher::POST));
request_->SetRequestContext(request_context_getter_);
request_->SetUploadData("application/x-www-form-urlencoded", post_body);
request_->Start(
base::Bind(&GaiaOAuthClient::Core::OnAuthTokenFetchComplete, this));
}
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void GaiaOAuthClient::Core::RefreshToken(
const OAuthClientInfo& oauth_client_info,
const std::string& refresh_token,
GaiaOAuthClient::Delegate* delegate) {
DCHECK(!request_.get()) << "Tried to fetch two things at once!";
delegate_ = delegate;
access_token_.clear();
expires_in_seconds_ = 0;
std::string post_body =
"refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) +
"&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
true) +
"&client_secret=" +
net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
"&grant_type=refresh_token";
request_.reset(net::URLFetcher::Create(
GURL(provider_info_.access_token_url), net::URLFetcher::POST, this));
request_->SetRequestContext(request_context_getter_);
request_->SetUploadData("application/x-www-form-urlencoded", post_body);
url_fetcher_type_ = URL_FETCHER_REFRESH_TOKEN;
request_->Start();
}
void GaiaOAuthClient::Core::OnURLFetchComplete(
const net::URLFetcher* source) {
std::string response_string;
source->GetResponseAsString(&response_string);
switch (url_fetcher_type_) {
case URL_FETCHER_REFRESH_TOKEN:
OnAuthTokenFetchComplete(source->GetStatus(),
source->GetResponseCode(),
response_string);
break;
case URL_FETCHER_GET_USER_INFO:
OnUserInfoFetchComplete(source->GetStatus(),
source->GetResponseCode(),
response_string);
break;
default:
LOG(ERROR) << "Unrecognised URLFetcher type: " << url_fetcher_type_;
}
}
| 170,809 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + (rlen + 1);
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
list[i] = NULL;
}
} else
list[i] = NULL;
}
}
} else
Commit Message:
CWE ID: CWE-682 | char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + rlen;
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
list[i] = NULL;
}
}
} else
| 164,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add confusability mapping entries for Myanmar and Georgian
U+10D5 (ვ), U+1012 (ဒ) => 3
Bug: 847242, 849398
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I9abb8560cf1c9e8e5e8d89980780b89461f7be52
Reviewed-on: https://chromium-review.googlesource.com/1091430
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565709}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+0437 (з), U+0499 (ҙ), U+04E1 (ӡ), U+10D5 (ვ), U+1012 (ဒ)} => 3
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,152 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) {
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
if (frame) {
WebDataSource* data_source = frame->dataSource();
if (data_source) {
DocumentState* document_state =
DocumentState::FromDataSource(data_source);
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> load_times = v8::Object::New(isolate);
load_times->Set(
v8::String::NewFromUtf8(isolate, "requestTime"),
v8::Number::New(isolate,
document_state->request_time().ToDoubleT()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "startLoadTime"),
v8::Number::New(isolate,
document_state->start_load_time().ToDoubleT()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "commitLoadTime"),
v8::Number::New(isolate,
document_state->commit_load_time().ToDoubleT()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"),
v8::Number::New(
isolate,
document_state->finish_document_load_time().ToDoubleT()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "finishLoadTime"),
v8::Number::New(isolate,
document_state->finish_load_time().ToDoubleT()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "firstPaintTime"),
v8::Number::New(isolate,
document_state->first_paint_time().ToDoubleT()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"),
v8::Number::New(
isolate,
document_state->first_paint_after_load_time().ToDoubleT()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "navigationType"),
v8::String::NewFromUtf8(
isolate, GetNavigationType(data_source->navigationType())));
load_times->Set(
v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"),
v8::Boolean::New(isolate, document_state->was_fetched_via_spdy()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"),
v8::Boolean::New(isolate, document_state->was_npn_negotiated()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"),
v8::String::NewFromUtf8(
isolate, document_state->npn_negotiated_protocol().c_str()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"),
v8::Boolean::New(
isolate, document_state->was_alternate_protocol_available()));
load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"),
v8::String::NewFromUtf8(
isolate,
net::HttpResponseInfo::ConnectionInfoToString(
document_state->connection_info()).c_str()));
args.GetReturnValue().Set(load_times);
return;
}
}
args.GetReturnValue().SetNull();
}
Commit Message: Cache all chrome.loadTimes info before passing them to setters.
The setters can invalidate the pointers frame, data_source and document_state.
BUG=549251
Review URL: https://codereview.chromium.org/1422753007
Cr-Commit-Position: refs/heads/master@{#357201}
CWE ID: | static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) {
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
if (!frame) {
args.GetReturnValue().SetNull();
return;
}
WebDataSource* data_source = frame->dataSource();
if (!data_source) {
args.GetReturnValue().SetNull();
return;
}
DocumentState* document_state = DocumentState::FromDataSource(data_source);
if (!document_state) {
args.GetReturnValue().SetNull();
return;
}
double request_time = document_state->request_time().ToDoubleT();
double start_load_time = document_state->start_load_time().ToDoubleT();
double commit_load_time = document_state->commit_load_time().ToDoubleT();
double finish_document_load_time =
document_state->finish_document_load_time().ToDoubleT();
double finish_load_time = document_state->finish_load_time().ToDoubleT();
double first_paint_time = document_state->first_paint_time().ToDoubleT();
double first_paint_after_load_time =
document_state->first_paint_after_load_time().ToDoubleT();
std::string navigation_type =
GetNavigationType(data_source->navigationType());
bool was_fetched_via_spdy = document_state->was_fetched_via_spdy();
bool was_npn_negotiated = document_state->was_npn_negotiated();
std::string npn_negotiated_protocol =
document_state->npn_negotiated_protocol();
bool was_alternate_protocol_available =
document_state->was_alternate_protocol_available();
std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString(
document_state->connection_info());
// Important: |frame|, |data_source| and |document_state| should not be
// referred to below this line, as JS setters below can invalidate these
// pointers.
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> load_times = v8::Object::New(isolate);
load_times->Set(v8::String::NewFromUtf8(isolate, "requestTime"),
v8::Number::New(isolate, request_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "startLoadTime"),
v8::Number::New(isolate, start_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "commitLoadTime"),
v8::Number::New(isolate, commit_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"),
v8::Number::New(isolate, finish_document_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "finishLoadTime"),
v8::Number::New(isolate, finish_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintTime"),
v8::Number::New(isolate, first_paint_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"),
v8::Number::New(isolate, first_paint_after_load_time));
load_times->Set(v8::String::NewFromUtf8(isolate, "navigationType"),
v8::String::NewFromUtf8(isolate, navigation_type.c_str()));
load_times->Set(v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"),
v8::Boolean::New(isolate, was_fetched_via_spdy));
load_times->Set(v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"),
v8::Boolean::New(isolate, was_npn_negotiated));
load_times->Set(
v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"),
v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str()));
load_times->Set(
v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"),
v8::Boolean::New(isolate, was_alternate_protocol_available));
load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"),
v8::String::NewFromUtf8(isolate, connection_info.c_str()));
args.GetReturnValue().Set(load_times);
}
| 171,766 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs)
{
GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;
u32 i, j, count;
if (!ptr) return GF_BAD_PARAM;
ptr->scalability_mask = gf_bs_read_u16(bs);
gf_bs_read_int(bs, 2);//reserved
count = gf_bs_read_int(bs, 6);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl;
GF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel);
if (!ptl) return GF_OUT_OF_MEM;
ptl->general_profile_space = gf_bs_read_int(bs, 2);
ptl->general_tier_flag= gf_bs_read_int(bs, 1);
ptl->general_profile_idc = gf_bs_read_int(bs, 5);
ptl->general_profile_compatibility_flags = gf_bs_read_u32(bs);
ptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48);
ptl->general_level_idc = gf_bs_read_u8(bs);
gf_list_add(ptr->profile_tier_levels, ptl);
}
count = gf_bs_read_u16(bs);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op;
GF_SAFEALLOC(op, LHEVC_OperatingPoint);
if (!op) return GF_OUT_OF_MEM;
op->output_layer_set_idx = gf_bs_read_u16(bs);
op->max_temporal_id = gf_bs_read_u8(bs);
op->layer_count = gf_bs_read_u8(bs);
for (j = 0; j < op->layer_count; j++) {
op->layers_info[j].ptl_idx = gf_bs_read_u8(bs);
op->layers_info[j].layer_id = gf_bs_read_int(bs, 6);
op->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
op->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
}
op->minPicWidth = gf_bs_read_u16(bs);
op->minPicHeight = gf_bs_read_u16(bs);
op->maxPicWidth = gf_bs_read_u16(bs);
op->maxPicHeight = gf_bs_read_u16(bs);
op->maxChromaFormat = gf_bs_read_int(bs, 2);
op->maxBitDepth = gf_bs_read_int(bs, 3) + 8;
gf_bs_read_int(bs, 1);//reserved
op->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
op->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
if (op->frame_rate_info_flag) {
op->avgFrameRate = gf_bs_read_u16(bs);
gf_bs_read_int(bs, 6); //reserved
op->constantFrameRate = gf_bs_read_int(bs, 2);
}
if (op->bit_rate_info_flag) {
op->maxBitRate = gf_bs_read_u32(bs);
op->avgBitRate = gf_bs_read_u32(bs);
}
gf_list_add(ptr->operating_points, op);
}
count = gf_bs_read_u8(bs);
for (i = 0; i < count; i++) {
LHEVC_DependentLayer *dep;
GF_SAFEALLOC(dep, LHEVC_DependentLayer);
if (!dep) return GF_OUT_OF_MEM;
dep->dependent_layerID = gf_bs_read_u8(bs);
dep->num_layers_dependent_on = gf_bs_read_u8(bs);
for (j = 0; j < dep->num_layers_dependent_on; j++)
dep->dependent_on_layerID[j] = gf_bs_read_u8(bs);
for (j = 0; j < 16; j++) {
if (ptr->scalability_mask & (1 << j))
dep->dimension_identifier[j] = gf_bs_read_u8(bs);
}
gf_list_add(ptr->dependency_layers, dep);
}
return GF_OK;
}
Commit Message: fix some exploitable overflows (#994, #997)
CWE ID: CWE-119 | GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs)
{
GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;
u32 i, j, count;
if (!ptr) return GF_BAD_PARAM;
ptr->scalability_mask = gf_bs_read_u16(bs);
gf_bs_read_int(bs, 2);//reserved
count = gf_bs_read_int(bs, 6);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl;
GF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel);
if (!ptl) return GF_OUT_OF_MEM;
ptl->general_profile_space = gf_bs_read_int(bs, 2);
ptl->general_tier_flag= gf_bs_read_int(bs, 1);
ptl->general_profile_idc = gf_bs_read_int(bs, 5);
ptl->general_profile_compatibility_flags = gf_bs_read_u32(bs);
ptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48);
ptl->general_level_idc = gf_bs_read_u8(bs);
gf_list_add(ptr->profile_tier_levels, ptl);
}
count = gf_bs_read_u16(bs);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op;
GF_SAFEALLOC(op, LHEVC_OperatingPoint);
if (!op) return GF_OUT_OF_MEM;
op->output_layer_set_idx = gf_bs_read_u16(bs);
op->max_temporal_id = gf_bs_read_u8(bs);
op->layer_count = gf_bs_read_u8(bs);
if (op->layer_count > ARRAY_LENGTH(op->layers_info))
return GF_NON_COMPLIANT_BITSTREAM;
for (j = 0; j < op->layer_count; j++) {
op->layers_info[j].ptl_idx = gf_bs_read_u8(bs);
op->layers_info[j].layer_id = gf_bs_read_int(bs, 6);
op->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
op->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
}
op->minPicWidth = gf_bs_read_u16(bs);
op->minPicHeight = gf_bs_read_u16(bs);
op->maxPicWidth = gf_bs_read_u16(bs);
op->maxPicHeight = gf_bs_read_u16(bs);
op->maxChromaFormat = gf_bs_read_int(bs, 2);
op->maxBitDepth = gf_bs_read_int(bs, 3) + 8;
gf_bs_read_int(bs, 1);//reserved
op->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
op->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
if (op->frame_rate_info_flag) {
op->avgFrameRate = gf_bs_read_u16(bs);
gf_bs_read_int(bs, 6); //reserved
op->constantFrameRate = gf_bs_read_int(bs, 2);
}
if (op->bit_rate_info_flag) {
op->maxBitRate = gf_bs_read_u32(bs);
op->avgBitRate = gf_bs_read_u32(bs);
}
gf_list_add(ptr->operating_points, op);
}
count = gf_bs_read_u8(bs);
for (i = 0; i < count; i++) {
LHEVC_DependentLayer *dep;
GF_SAFEALLOC(dep, LHEVC_DependentLayer);
if (!dep) return GF_OUT_OF_MEM;
dep->dependent_layerID = gf_bs_read_u8(bs);
dep->num_layers_dependent_on = gf_bs_read_u8(bs);
for (j = 0; j < dep->num_layers_dependent_on; j++)
dep->dependent_on_layerID[j] = gf_bs_read_u8(bs);
for (j = 0; j < 16; j++) {
if (ptr->scalability_mask & (1 << j))
dep->dimension_identifier[j] = gf_bs_read_u8(bs);
}
gf_list_add(ptr->dependency_layers, dep);
}
return GF_OK;
}
| 169,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static opj_bool pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
Commit Message: [MJ2] To avoid divisions by zero / undefined behaviour on shift
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-369 | static opj_bool pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
| 169,772 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nsc_decode(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT16 rw = ROUND_UP_TO(context->width, 8);
BYTE shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */
BYTE* bmpdata = context->BitmapData;
for (y = 0; y < context->height; y++)
{
const BYTE* yplane;
const BYTE* coplane;
const BYTE* cgplane;
const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */
if (context->ChromaSubsamplingLevel)
{
yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */
coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >>
1); /* Co, supersampled */
cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >>
1); /* Cg, supersampled */
}
else
{
yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */
coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */
cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */
}
for (x = 0; x < context->width; x++)
{
INT16 y_val = (INT16) * yplane;
INT16 co_val = (INT16)(INT8)(*coplane << shift);
INT16 cg_val = (INT16)(INT8)(*cgplane << shift);
INT16 r_val = y_val + co_val - cg_val;
INT16 g_val = y_val + cg_val;
INT16 b_val = y_val - co_val - cg_val;
*bmpdata++ = MINMAX(b_val, 0, 0xFF);
*bmpdata++ = MINMAX(g_val, 0, 0xFF);
*bmpdata++ = MINMAX(r_val, 0, 0xFF);
*bmpdata++ = *aplane;
yplane++;
coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
aplane++;
}
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | static void nsc_decode(NSC_CONTEXT* context)
static BOOL nsc_decode(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE shift;
BYTE* bmpdata;
size_t pos = 0;
if (!context)
return FALSE;
rw = ROUND_UP_TO(context->width, 8);
shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */
bmpdata = context->BitmapData;
if (!bmpdata)
return FALSE;
for (y = 0; y < context->height; y++)
{
const BYTE* yplane;
const BYTE* coplane;
const BYTE* cgplane;
const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */
if (context->ChromaSubsamplingLevel)
{
yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */
coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >>
1); /* Co, supersampled */
cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >>
1); /* Cg, supersampled */
}
else
{
yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */
coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */
cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */
}
for (x = 0; x < context->width; x++)
{
INT16 y_val = (INT16) * yplane;
INT16 co_val = (INT16)(INT8)(*coplane << shift);
INT16 cg_val = (INT16)(INT8)(*cgplane << shift);
INT16 r_val = y_val + co_val - cg_val;
INT16 g_val = y_val + cg_val;
INT16 b_val = y_val - co_val - cg_val;
if (pos + 4 > context->BitmapDataLength)
return FALSE;
pos += 4;
*bmpdata++ = MINMAX(b_val, 0, 0xFF);
*bmpdata++ = MINMAX(g_val, 0, 0xFF);
*bmpdata++ = MINMAX(r_val, 0, 0xFF);
*bmpdata++ = *aplane;
yplane++;
coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
aplane++;
}
}
return TRUE;
}
| 169,282 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int AudioRendererAlgorithm::FillBuffer(
uint8* dest, int requested_frames) {
DCHECK_NE(bytes_per_frame_, 0);
if (playback_rate_ == 0.0f)
return 0;
int total_frames_rendered = 0;
uint8* output_ptr = dest;
while (total_frames_rendered < requested_frames) {
if (index_into_window_ == window_size_)
ResetWindow();
bool rendered_frame = true;
if (playback_rate_ > 1.0)
rendered_frame = OutputFasterPlayback(output_ptr);
else if (playback_rate_ < 1.0)
rendered_frame = OutputSlowerPlayback(output_ptr);
else
rendered_frame = OutputNormalPlayback(output_ptr);
if (!rendered_frame) {
needs_more_data_ = true;
break;
}
output_ptr += bytes_per_frame_;
total_frames_rendered++;
}
return total_frames_rendered;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | int AudioRendererAlgorithm::FillBuffer(
uint8* dest, int requested_frames) {
DCHECK_NE(bytes_per_frame_, 0);
if (playback_rate_ == 0.0f)
return 0;
int slower_step = ceil(window_size_ * playback_rate_);
int faster_step = ceil(window_size_ / playback_rate_);
AlignToFrameBoundary(&slower_step);
AlignToFrameBoundary(&faster_step);
int total_frames_rendered = 0;
uint8* output_ptr = dest;
while (total_frames_rendered < requested_frames) {
if (index_into_window_ == window_size_)
ResetWindow();
bool rendered_frame = true;
if (window_size_ > faster_step) {
rendered_frame = OutputFasterPlayback(
output_ptr, window_size_, faster_step);
} else if (slower_step < window_size_) {
rendered_frame = OutputSlowerPlayback(
output_ptr, slower_step, window_size_);
} else {
rendered_frame = OutputNormalPlayback(output_ptr);
}
if (!rendered_frame) {
needs_more_data_ = true;
break;
}
output_ptr += bytes_per_frame_;
total_frames_rendered++;
}
return total_frames_rendered;
}
| 171,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: process_db_args(krb5_context context, char **db_args, xargs_t *xargs,
OPERATION optype)
{
int i=0;
krb5_error_code st=0;
char *arg=NULL, *arg_val=NULL;
char **dptr=NULL;
unsigned int arg_val_len=0;
if (db_args) {
for (i=0; db_args[i]; ++i) {
arg = strtok_r(db_args[i], "=", &arg_val);
if (strcmp(arg, TKTPOLICY_ARG) == 0) {
dptr = &xargs->tktpolicydn;
} else {
if (strcmp(arg, USERDN_ARG) == 0) {
if (optype == MODIFY_PRINCIPAL ||
xargs->dn != NULL || xargs->containerdn != NULL ||
xargs->linkdn != NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option not supported"),
arg);
goto cleanup;
}
dptr = &xargs->dn;
} else if (strcmp(arg, CONTAINERDN_ARG) == 0) {
if (optype == MODIFY_PRINCIPAL ||
xargs->dn != NULL || xargs->containerdn != NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option not supported"),
arg);
goto cleanup;
}
dptr = &xargs->containerdn;
} else if (strcmp(arg, LINKDN_ARG) == 0) {
if (xargs->dn != NULL || xargs->linkdn != NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option not supported"),
arg);
goto cleanup;
}
dptr = &xargs->linkdn;
} else {
st = EINVAL;
k5_setmsg(context, st, _("unknown option: %s"), arg);
goto cleanup;
}
xargs->dn_from_kbd = TRUE;
if (arg_val == NULL || strlen(arg_val) == 0) {
st = EINVAL;
k5_setmsg(context, st, _("%s option value missing"), arg);
goto cleanup;
}
}
if (arg_val == NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option value missing"), arg);
goto cleanup;
}
arg_val_len = strlen(arg_val) + 1;
if (strcmp(arg, TKTPOLICY_ARG) == 0) {
if ((st = krb5_ldap_name_to_policydn (context,
arg_val,
dptr)) != 0)
goto cleanup;
} else {
*dptr = k5memdup(arg_val, arg_val_len, &st);
if (*dptr == NULL)
goto cleanup;
}
}
}
cleanup:
return st;
}
Commit Message: Fix LDAP null deref on empty arg [CVE-2016-3119]
In the LDAP KDB module's process_db_args(), strtok_r() may return NULL
if there is an empty string in the db_args array. Check for this case
and avoid dereferencing a null pointer.
CVE-2016-3119:
In MIT krb5 1.6 and later, an authenticated attacker with permission
to modify a principal entry can cause kadmind to dereference a null
pointer by supplying an empty DB argument to the modify_principal
command, if kadmind is configured to use the LDAP KDB module.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:ND
ticket: 8383 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: | process_db_args(krb5_context context, char **db_args, xargs_t *xargs,
OPERATION optype)
{
int i=0;
krb5_error_code st=0;
char *arg=NULL, *arg_val=NULL;
char **dptr=NULL;
unsigned int arg_val_len=0;
if (db_args) {
for (i=0; db_args[i]; ++i) {
arg = strtok_r(db_args[i], "=", &arg_val);
arg = (arg != NULL) ? arg : "";
if (strcmp(arg, TKTPOLICY_ARG) == 0) {
dptr = &xargs->tktpolicydn;
} else {
if (strcmp(arg, USERDN_ARG) == 0) {
if (optype == MODIFY_PRINCIPAL ||
xargs->dn != NULL || xargs->containerdn != NULL ||
xargs->linkdn != NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option not supported"),
arg);
goto cleanup;
}
dptr = &xargs->dn;
} else if (strcmp(arg, CONTAINERDN_ARG) == 0) {
if (optype == MODIFY_PRINCIPAL ||
xargs->dn != NULL || xargs->containerdn != NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option not supported"),
arg);
goto cleanup;
}
dptr = &xargs->containerdn;
} else if (strcmp(arg, LINKDN_ARG) == 0) {
if (xargs->dn != NULL || xargs->linkdn != NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option not supported"),
arg);
goto cleanup;
}
dptr = &xargs->linkdn;
} else {
st = EINVAL;
k5_setmsg(context, st, _("unknown option: %s"), arg);
goto cleanup;
}
xargs->dn_from_kbd = TRUE;
if (arg_val == NULL || strlen(arg_val) == 0) {
st = EINVAL;
k5_setmsg(context, st, _("%s option value missing"), arg);
goto cleanup;
}
}
if (arg_val == NULL) {
st = EINVAL;
k5_setmsg(context, st, _("%s option value missing"), arg);
goto cleanup;
}
arg_val_len = strlen(arg_val) + 1;
if (strcmp(arg, TKTPOLICY_ARG) == 0) {
if ((st = krb5_ldap_name_to_policydn (context,
arg_val,
dptr)) != 0)
goto cleanup;
} else {
*dptr = k5memdup(arg_val, arg_val_len, &st);
if (*dptr == NULL)
goto cleanup;
}
}
}
cleanup:
return st;
}
| 167,379 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex
Reported by Google Autofuzz team
CWE ID: CWE-787 | int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest,
const URI_TYPE(QueryList) * queryList,
int maxChars, int * charsWritten, int * charsRequired,
UriBool spaceToPlus, UriBool normalizeBreaks) {
UriBool firstItem = URI_TRUE;
int ampersandLen = 0; /* increased to 1 from second item on */
URI_CHAR * write = dest;
/* Subtract terminator */
if (dest == NULL) {
*charsRequired = 0;
} else {
maxChars--;
}
while (queryList != NULL) {
const URI_CHAR * const key = queryList->key;
const URI_CHAR * const value = queryList->value;
const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3);
const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key);
const int keyRequiredChars = worstCase * keyLen;
const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value);
const int valueRequiredChars = worstCase * valueLen;
if (dest == NULL) {
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
}
(*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL)
? 0
: 1 + valueRequiredChars);
} else {
URI_CHAR * afterKey;
if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy key */
if (firstItem == URI_TRUE) {
ampersandLen = 1;
firstItem = URI_FALSE;
} else {
write[0] = _UT('&');
write++;
}
afterKey = URI_FUNC(EscapeEx)(key, key + keyLen,
write, spaceToPlus, normalizeBreaks);
write += (afterKey - write);
if (value != NULL) {
URI_CHAR * afterValue;
if ((write - dest) + 1 + valueRequiredChars > maxChars) {
return URI_ERROR_OUTPUT_TOO_LARGE;
}
/* Copy value */
write[0] = _UT('=');
write++;
afterValue = URI_FUNC(EscapeEx)(value, value + valueLen,
write, spaceToPlus, normalizeBreaks);
write += (afterValue - write);
}
}
queryList = queryList->next;
}
if (dest != NULL) {
write[0] = _UT('\0');
if (charsWritten != NULL) {
*charsWritten = (int)(write - dest) + 1; /* .. for terminator */
}
}
return URI_SUCCESS;
}
| 168,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error;
address &= PAGE_MASK;
error = security_mmap_addr(address);
if (error)
return error;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
}
Commit Message: mm: enforce min addr even if capable() in expand_downwards()
security_mmap_addr() does a capability check with current_cred(), but
we can reach this code from contexts like a VFS write handler where
current_cred() must not be used.
This can be abused on systems without SMAP to make NULL pointer
dereferences exploitable again.
Fixes: 8869477a49c3 ("security: protect from stack expansion into low vm addresses")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476 | int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error = 0;
address &= PAGE_MASK;
if (address < mmap_min_addr)
return -EPERM;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
}
| 169,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned long long Track::GetDefaultDuration() const
{
return m_info.defaultDuration;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | unsigned long long Track::GetDefaultDuration() const
| 174,302 |
Subsets and Splits