instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromeDownloadManagerDelegate::IsDangerousFile(
const DownloadItem& download,
const FilePath& suggested_path,
bool visited_referrer_before) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (download.GetTransitionType() & content::PAGE_TRANSITION_FROM_ADDRESS_BAR)
return false;
if (extensions::FeatureSwitch::easy_off_store_install()->IsEnabled() &&
download_crx_util::IsExtensionDownload(download) &&
!extensions::WebstoreInstaller::GetAssociatedApproval(download)) {
return true;
}
if (ShouldOpenFileBasedOnExtension(suggested_path) &&
download.HasUserGesture())
return false;
download_util::DownloadDangerLevel danger_level =
download_util::GetFileDangerLevel(suggested_path.BaseName());
if (danger_level == download_util::AllowOnUserGesture)
return !download.HasUserGesture() || !visited_referrer_before;
return danger_level == download_util::Dangerous;
}
Commit Message: For "Dangerous" file type, no user gesture will bypass the download warning.
BUG=170569
Review URL: https://codereview.chromium.org/12039015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178072 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ChromeDownloadManagerDelegate::IsDangerousFile(
const DownloadItem& download,
const FilePath& suggested_path,
bool visited_referrer_before) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (extensions::FeatureSwitch::easy_off_store_install()->IsEnabled() &&
download_crx_util::IsExtensionDownload(download) &&
!extensions::WebstoreInstaller::GetAssociatedApproval(download)) {
return true;
}
if (ShouldOpenFileBasedOnExtension(suggested_path) &&
download.HasUserGesture())
return false;
download_util::DownloadDangerLevel danger_level =
download_util::GetFileDangerLevel(suggested_path.BaseName());
if (danger_level == download_util::AllowOnUserGesture) {
if (download.GetTransitionType() &
content::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
return false;
}
return !download.HasUserGesture() || !visited_referrer_before;
}
return danger_level == download_util::Dangerous;
}
| 171,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int piv_match_card_continued(sc_card_t *card)
{
int i;
int type = -1;
piv_private_data_t *priv = NULL;
int saved_type = card->type;
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
/* piv_match_card may be called with card->type, set by opensc.conf */
/* user provide card type must be one we know */
switch (card->type) {
case -1:
case SC_CARD_TYPE_PIV_II_GENERIC:
case SC_CARD_TYPE_PIV_II_HIST:
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
case SC_CARD_TYPE_PIV_II_GI_DE:
type = card->type;
break;
default:
return 0; /* can not handle the card */
}
if (type == -1) {
/*
*try to identify card by ATR or historical data in ATR
* currently all PIV card will respond to piv_find_aid
* the same. But in future may need to know card type first,
* so do it here.
*/
if (card->reader->atr_info.hist_bytes != NULL) {
if (card->reader->atr_info.hist_bytes_len == 8 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) {
type = SC_CARD_TYPE_PIV_II_YUBIKEY4;
}
else if (card->reader->atr_info.hist_bytes_len >= 7 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) {
type = SC_CARD_TYPE_PIV_II_NEO;
}
/*
* https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1239.pdf
* lists 2 ATRS with historical bytes:
* 73 66 74 65 2D 63 64 30 38 30
* 73 66 74 65 20 63 64 31 34 34
* will check for 73 66 74 65
*/
else if (card->reader->atr_info.hist_bytes_len >= 4 &&
!(memcmp(card->reader->atr_info.hist_bytes, "sfte", 4))) {
type = SC_CARD_TYPE_PIV_II_GI_DE;
}
else if (card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */
size_t datalen;
const u8 *data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
card->reader->atr_info.hist_bytes_len - 1,
0xF0, &datalen);
if (data != NULL) {
int k;
for (k = 0; piv_aids[k].len_long != 0; k++) {
if (datalen == piv_aids[k].len_long
&& !memcmp(data, piv_aids[k].value, datalen)) {
type = SC_CARD_TYPE_PIV_II_HIST;
break;
}
}
}
}
}
if (type == -1)
type = SC_CARD_TYPE_PIV_II_GENERIC;
}
/* allocate and init basic fields */
priv = calloc(1, sizeof(piv_private_data_t));
if (!priv)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
if (card->type == -1)
card->type = type;
card->drv_data = priv; /* will free if no match, or pass on to piv_init */
priv->aid_file = sc_file_new();
priv->selected_obj = -1;
priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */
priv->logged_in = SC_PIN_STATE_UNKNOWN;
priv->tries_left = 10; /* will assume OK at start */
priv->pstate = PIV_STATE_MATCH;
/* Some objects will only be present if History object says so */
for (i=0; i < PIV_OBJ_LAST_ENUM -1; i++)
if(piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT)
priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
sc_lock(card);
/*
* detect if active AID is PIV. NIST 800-73 says Only one PIV application per card
* and PIV must be the default application
* This can avoid doing doing a select_aid and losing the login state on some cards
* We may get interference on some cards by other drivers trying SELECT_AID before
* we get to see if PIV application is still active.
* putting PIV driver first might help.
* This may fail if the wrong AID is active
*/
i = piv_find_discovery(card);
if (i < 0) {
/* Detect by selecting applet */
sc_file_t aidfile;
i = piv_find_aid(card, &aidfile);
}
if (i >= 0) {
/*
* We now know PIV AID is active, test DISCOVERY object
* Some CAC cards with PIV don't support DISCOVERY and return
* SC_ERROR_INCORRECT_PARAMETERS. Any error other then
* SC_ERROR_FILE_NOT_FOUND means we cannot use discovery
* to test for active AID.
*/
int i7e = piv_find_discovery(card);
if (i7e != 0 && i7e != SC_ERROR_FILE_NOT_FOUND) {
priv->card_issues |= CI_DISCOVERY_USELESS;
priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
}
}
if (i < 0) {
/* don't match. Does not have a PIV applet. */
sc_unlock(card);
piv_finish(card);
card->type = saved_type;
return 0;
}
/* Matched, caller will use or free priv and sc_lock as needed */
priv->pstate=PIV_STATE_INIT;
return 1; /* match */
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int piv_match_card_continued(sc_card_t *card)
{
int i;
int type = -1;
piv_private_data_t *priv = NULL;
int saved_type = card->type;
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
/* piv_match_card may be called with card->type, set by opensc.conf */
/* user provide card type must be one we know */
switch (card->type) {
case -1:
case SC_CARD_TYPE_PIV_II_GENERIC:
case SC_CARD_TYPE_PIV_II_HIST:
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
case SC_CARD_TYPE_PIV_II_GI_DE:
type = card->type;
break;
default:
return 0; /* can not handle the card */
}
if (type == -1) {
/*
*try to identify card by ATR or historical data in ATR
* currently all PIV card will respond to piv_find_aid
* the same. But in future may need to know card type first,
* so do it here.
*/
if (card->reader->atr_info.hist_bytes != NULL) {
if (card->reader->atr_info.hist_bytes_len == 8 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) {
type = SC_CARD_TYPE_PIV_II_YUBIKEY4;
}
else if (card->reader->atr_info.hist_bytes_len >= 7 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) {
type = SC_CARD_TYPE_PIV_II_NEO;
}
/*
* https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1239.pdf
* lists 2 ATRS with historical bytes:
* 73 66 74 65 2D 63 64 30 38 30
* 73 66 74 65 20 63 64 31 34 34
* will check for 73 66 74 65
*/
else if (card->reader->atr_info.hist_bytes_len >= 4
&& !(memcmp(card->reader->atr_info.hist_bytes, "sfte", 4))) {
type = SC_CARD_TYPE_PIV_II_GI_DE;
}
else if (card->reader->atr_info.hist_bytes_len > 0
&& card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */
size_t datalen;
const u8 *data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
card->reader->atr_info.hist_bytes_len - 1,
0xF0, &datalen);
if (data != NULL) {
int k;
for (k = 0; piv_aids[k].len_long != 0; k++) {
if (datalen == piv_aids[k].len_long
&& !memcmp(data, piv_aids[k].value, datalen)) {
type = SC_CARD_TYPE_PIV_II_HIST;
break;
}
}
}
}
}
if (type == -1)
type = SC_CARD_TYPE_PIV_II_GENERIC;
}
/* allocate and init basic fields */
priv = calloc(1, sizeof(piv_private_data_t));
if (!priv)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
if (card->type == -1)
card->type = type;
card->drv_data = priv; /* will free if no match, or pass on to piv_init */
priv->aid_file = sc_file_new();
priv->selected_obj = -1;
priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */
priv->logged_in = SC_PIN_STATE_UNKNOWN;
priv->tries_left = 10; /* will assume OK at start */
priv->pstate = PIV_STATE_MATCH;
/* Some objects will only be present if History object says so */
for (i=0; i < PIV_OBJ_LAST_ENUM -1; i++)
if(piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT)
priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
sc_lock(card);
/*
* detect if active AID is PIV. NIST 800-73 says Only one PIV application per card
* and PIV must be the default application
* This can avoid doing doing a select_aid and losing the login state on some cards
* We may get interference on some cards by other drivers trying SELECT_AID before
* we get to see if PIV application is still active.
* putting PIV driver first might help.
* This may fail if the wrong AID is active
*/
i = piv_find_discovery(card);
if (i < 0) {
/* Detect by selecting applet */
sc_file_t aidfile;
i = piv_find_aid(card, &aidfile);
}
if (i >= 0) {
/*
* We now know PIV AID is active, test DISCOVERY object
* Some CAC cards with PIV don't support DISCOVERY and return
* SC_ERROR_INCORRECT_PARAMETERS. Any error other then
* SC_ERROR_FILE_NOT_FOUND means we cannot use discovery
* to test for active AID.
*/
int i7e = piv_find_discovery(card);
if (i7e != 0 && i7e != SC_ERROR_FILE_NOT_FOUND) {
priv->card_issues |= CI_DISCOVERY_USELESS;
priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
}
}
if (i < 0) {
/* don't match. Does not have a PIV applet. */
sc_unlock(card);
piv_finish(card);
card->type = saved_type;
return 0;
}
/* Matched, caller will use or free priv and sc_lock as needed */
priv->pstate=PIV_STATE_INIT;
return 1; /* match */
}
| 169,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int override_release(char __user *release, int len)
{
int ret = 0;
char buf[65];
if (current->personality & UNAME26) {
char *rest = UTS_RELEASE;
int ndots = 0;
unsigned v;
while (*rest) {
if (*rest == '.' && ++ndots >= 3)
break;
if (!isdigit(*rest) && *rest != '.')
break;
rest++;
}
v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;
snprintf(buf, len, "2.6.%u%s", v, rest);
ret = copy_to_user(release, buf, len);
}
return ret;
}
Commit Message: kernel/sys.c: fix stack memory content leak via UNAME26
Calling uname() with the UNAME26 personality set allows a leak of kernel
stack contents. This fixes it by defensively calculating the length of
copy_to_user() call, making the len argument unsigned, and initializing
the stack buffer to zero (now technically unneeded, but hey, overkill).
CVE-2012-0957
Reported-by: PaX Team <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Cc: Andi Kleen <[email protected]>
Cc: PaX Team <[email protected]>
Cc: Brad Spengler <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-16 | static int override_release(char __user *release, int len)
static int override_release(char __user *release, size_t len)
{
int ret = 0;
if (current->personality & UNAME26) {
const char *rest = UTS_RELEASE;
char buf[65] = { 0 };
int ndots = 0;
unsigned v;
size_t copy;
while (*rest) {
if (*rest == '.' && ++ndots >= 3)
break;
if (!isdigit(*rest) && *rest != '.')
break;
rest++;
}
v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;
copy = min(sizeof(buf), max_t(size_t, 1, len));
copy = scnprintf(buf, copy, "2.6.%u%s", v, rest);
ret = copy_to_user(release, buf, copy + 1);
}
return ret;
}
| 165,647 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
}
Commit Message:
CWE ID: CWE-200 | xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
}
| 164,728 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PassOwnPtr<WebCore::GraphicsContext> LayerTreeCoordinator::beginContentUpdate(const WebCore::IntSize& size, ShareableBitmap::Flags flags, ShareableSurface::Handle& handle, WebCore::IntPoint& offset)
{
OwnPtr<WebCore::GraphicsContext> graphicsContext;
for (unsigned i = 0; i < m_updateAtlases.size(); ++i) {
UpdateAtlas* atlas = m_updateAtlases[i].get();
if (atlas->flags() == flags) {
graphicsContext = atlas->beginPaintingOnAvailableBuffer(handle, size, offset);
if (graphicsContext)
return graphicsContext.release();
}
}
static const int ScratchBufferDimension = 1024; // Should be a power of two.
m_updateAtlases.append(adoptPtr(new UpdateAtlas(ScratchBufferDimension, flags)));
return m_updateAtlases.last()->beginPaintingOnAvailableBuffer(handle, size, offset);
}
Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases
https://bugs.webkit.org/show_bug.cgi?id=95072
Reviewed by Jocelyn Turcotte.
Release graphic buffers that haven't been used for a while in order to save memory.
This way we can give back memory to the system when no user interaction happens
after a period of time, for example when we are in the background.
* Shared/ShareableBitmap.h:
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp:
(WebKit::LayerTreeCoordinator::LayerTreeCoordinator):
(WebKit::LayerTreeCoordinator::beginContentUpdate):
(WebKit):
(WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases):
(WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired):
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h:
(LayerTreeCoordinator):
* WebProcess/WebPage/UpdateAtlas.cpp:
(WebKit::UpdateAtlas::UpdateAtlas):
(WebKit::UpdateAtlas::didSwapBuffers):
Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer
and this way we can track whether this atlas is used with m_areaAllocator.
(WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer):
* WebProcess/WebPage/UpdateAtlas.h:
(WebKit::UpdateAtlas::addTimeInactive):
(WebKit::UpdateAtlas::isInactive):
(WebKit::UpdateAtlas::isInUse):
(UpdateAtlas):
git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | PassOwnPtr<WebCore::GraphicsContext> LayerTreeCoordinator::beginContentUpdate(const WebCore::IntSize& size, ShareableBitmap::Flags flags, ShareableSurface::Handle& handle, WebCore::IntPoint& offset)
{
OwnPtr<WebCore::GraphicsContext> graphicsContext;
for (unsigned i = 0; i < m_updateAtlases.size(); ++i) {
UpdateAtlas* atlas = m_updateAtlases[i].get();
if (atlas->flags() == flags) {
graphicsContext = atlas->beginPaintingOnAvailableBuffer(handle, size, offset);
if (graphicsContext)
return graphicsContext.release();
}
}
static const int ScratchBufferDimension = 1024; // Should be a power of two.
m_updateAtlases.append(adoptPtr(new UpdateAtlas(ScratchBufferDimension, flags)));
scheduleReleaseInactiveAtlases();
return m_updateAtlases.last()->beginPaintingOnAvailableBuffer(handle, size, offset);
}
| 170,269 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking)
{
int k, at_head;
Sg_device *sdp = sfp->parentdp;
sg_io_hdr_t *hp = &srp->header;
srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */
hp->status = 0;
hp->masked_status = 0;
hp->msg_status = 0;
hp->info = 0;
hp->host_status = 0;
hp->driver_status = 0;
hp->resid = 0;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n",
(int) cmnd[0], (int) hp->cmd_len));
k = sg_start_req(srp, cmnd);
if (k) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: start_req err=%d\n", k));
sg_finish_rem_req(srp);
return k; /* probably out of space --> ENOMEM */
}
if (atomic_read(&sdp->detaching)) {
if (srp->bio)
blk_end_request_all(srp->rq, -EIO);
sg_finish_rem_req(srp);
return -ENODEV;
}
hp->duration = jiffies_to_msecs(jiffies);
if (hp->interface_id != '\0' && /* v3 (or later) interface */
(SG_FLAG_Q_AT_TAIL & hp->flags))
at_head = 0;
else
at_head = 1;
srp->rq->timeout = timeout;
kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */
blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
srp->rq, at_head, sg_rq_end_io);
return 0;
}
Commit Message: sg: Fix double-free when drives detach during SG_IO
In sg_common_write(), we free the block request and return -ENODEV if
the device is detached in the middle of the SG_IO ioctl().
Unfortunately, sg_finish_rem_req() also tries to free srp->rq, so we
end up freeing rq->cmd in the already free rq object, and then free
the object itself out from under the current user.
This ends up corrupting random memory via the list_head on the rq
object. The most common crash trace I saw is this:
------------[ cut here ]------------
kernel BUG at block/blk-core.c:1420!
Call Trace:
[<ffffffff81281eab>] blk_put_request+0x5b/0x80
[<ffffffffa0069e5b>] sg_finish_rem_req+0x6b/0x120 [sg]
[<ffffffffa006bcb9>] sg_common_write.isra.14+0x459/0x5a0 [sg]
[<ffffffff8125b328>] ? selinux_file_alloc_security+0x48/0x70
[<ffffffffa006bf95>] sg_new_write.isra.17+0x195/0x2d0 [sg]
[<ffffffffa006cef4>] sg_ioctl+0x644/0xdb0 [sg]
[<ffffffff81170f80>] do_vfs_ioctl+0x90/0x520
[<ffffffff81258967>] ? file_has_perm+0x97/0xb0
[<ffffffff811714a1>] SyS_ioctl+0x91/0xb0
[<ffffffff81602afb>] tracesys+0xdd/0xe2
RIP [<ffffffff81281e04>] __blk_put_request+0x154/0x1a0
The solution is straightforward: just set srp->rq to NULL in the
failure branch so that sg_finish_rem_req() doesn't attempt to re-free
it.
Additionally, since sg_rq_end_io() will never be called on the object
when this happens, we need to free memory backing ->cmd if it isn't
embedded in the object itself.
KASAN was extremely helpful in finding the root cause of this bug.
Signed-off-by: Calvin Owens <[email protected]>
Acked-by: Douglas Gilbert <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-415 | sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking)
{
int k, at_head;
Sg_device *sdp = sfp->parentdp;
sg_io_hdr_t *hp = &srp->header;
srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */
hp->status = 0;
hp->masked_status = 0;
hp->msg_status = 0;
hp->info = 0;
hp->host_status = 0;
hp->driver_status = 0;
hp->resid = 0;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n",
(int) cmnd[0], (int) hp->cmd_len));
k = sg_start_req(srp, cmnd);
if (k) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: start_req err=%d\n", k));
sg_finish_rem_req(srp);
return k; /* probably out of space --> ENOMEM */
}
if (atomic_read(&sdp->detaching)) {
if (srp->bio) {
if (srp->rq->cmd != srp->rq->__cmd)
kfree(srp->rq->cmd);
blk_end_request_all(srp->rq, -EIO);
srp->rq = NULL;
}
sg_finish_rem_req(srp);
return -ENODEV;
}
hp->duration = jiffies_to_msecs(jiffies);
if (hp->interface_id != '\0' && /* v3 (or later) interface */
(SG_FLAG_Q_AT_TAIL & hp->flags))
at_head = 0;
else
at_head = 1;
srp->rq->timeout = timeout;
kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */
blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
srp->rq, at_head, sg_rq_end_io);
return 0;
}
| 167,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct pipe_inode_info *pipe;
long ret;
pipe = get_pipe_info(file);
if (!pipe)
return -EBADF;
__pipe_lock(pipe);
switch (cmd) {
case F_SETPIPE_SZ: {
unsigned int size, nr_pages;
size = round_pipe_size(arg);
nr_pages = size >> PAGE_SHIFT;
ret = -EINVAL;
if (!nr_pages)
goto out;
if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) {
ret = -EPERM;
goto out;
}
ret = pipe_set_size(pipe, nr_pages);
break;
}
case F_GETPIPE_SZ:
ret = pipe->buffers * PAGE_SIZE;
break;
default:
ret = -EINVAL;
break;
}
out:
__pipe_unlock(pipe);
return ret;
}
Commit Message: pipe: limit the per-user amount of pages allocated in pipes
On no-so-small systems, it is possible for a single process to cause an
OOM condition by filling large pipes with data that are never read. A
typical process filling 4000 pipes with 1 MB of data will use 4 GB of
memory. On small systems it may be tricky to set the pipe max size to
prevent this from happening.
This patch makes it possible to enforce a per-user soft limit above
which new pipes will be limited to a single page, effectively limiting
them to 4 kB each, as well as a hard limit above which no new pipes may
be created for this user. This has the effect of protecting the system
against memory abuse without hurting other users, and still allowing
pipes to work correctly though with less data at once.
The limit are controlled by two new sysctls : pipe-user-pages-soft, and
pipe-user-pages-hard. Both may be disabled by setting them to zero. The
default soft limit allows the default number of FDs per process (1024)
to create pipes of the default size (64kB), thus reaching a limit of 64MB
before starting to create only smaller pipes. With 256 processes limited
to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB =
1084 MB of memory allocated for a user. The hard limit is disabled by
default to avoid breaking existing applications that make intensive use
of pipes (eg: for splicing).
Reported-by: [email protected]
Reported-by: Tetsuo Handa <[email protected]>
Mitigates: CVE-2013-4312 (Linux 2.0+)
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-399 | long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct pipe_inode_info *pipe;
long ret;
pipe = get_pipe_info(file);
if (!pipe)
return -EBADF;
__pipe_lock(pipe);
switch (cmd) {
case F_SETPIPE_SZ: {
unsigned int size, nr_pages;
size = round_pipe_size(arg);
nr_pages = size >> PAGE_SHIFT;
ret = -EINVAL;
if (!nr_pages)
goto out;
if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) {
ret = -EPERM;
goto out;
} else if ((too_many_pipe_buffers_hard(pipe->user) ||
too_many_pipe_buffers_soft(pipe->user)) &&
!capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) {
ret = -EPERM;
goto out;
}
ret = pipe_set_size(pipe, nr_pages);
break;
}
case F_GETPIPE_SZ:
ret = pipe->buffers * PAGE_SIZE;
break;
default:
ret = -EINVAL;
break;
}
out:
__pipe_unlock(pipe);
return ret;
}
| 167,388 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: TestWCDelegateForDialogsAndFullscreen()
: is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID: | TestWCDelegateForDialogsAndFullscreen()
| 172,718 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _WM_ParseNewHmp(uint8_t *hmp_data, uint32_t hmp_size) {
uint8_t is_hmp2 = 0;
uint32_t zero_cnt = 0;
uint32_t i = 0;
uint32_t hmp_file_length = 0;
uint32_t hmp_chunks = 0;
uint32_t hmp_divisions = 0;
uint32_t hmp_unknown = 0;
uint32_t hmp_bpm = 0;
uint32_t hmp_song_time = 0;
struct _mdi *hmp_mdi;
uint8_t **hmp_chunk;
uint32_t *chunk_length;
uint32_t *chunk_ofs;
uint32_t *chunk_delta;
uint8_t *chunk_end;
uint32_t chunk_num = 0;
uint32_t hmp_track = 0;
uint32_t smallest_delta = 0;
uint32_t subtract_delta = 0;
uint32_t end_of_chunks = 0;
uint32_t var_len_shift = 0;
float tempo_f = 500000.0;
float samples_per_delta_f = 0.0;
uint32_t sample_count = 0;
float sample_count_f = 0;
float sample_remainder = 0;
if (memcmp(hmp_data, "HMIMIDIP", 8)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0);
return NULL;
}
hmp_data += 8;
hmp_size -= 8;
if (!memcmp(hmp_data, "013195", 6)) {
hmp_data += 6;
hmp_size -= 6;
is_hmp2 = 1;
}
if (is_hmp2) {
zero_cnt = 18;
} else {
zero_cnt = 24;
}
for (i = 0; i < zero_cnt; i++) {
if (hmp_data[i] != 0) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0);
return NULL;
}
}
hmp_data += zero_cnt;
hmp_size -= zero_cnt;
hmp_file_length = *hmp_data++;
hmp_file_length += (*hmp_data++ << 8);
hmp_file_length += (*hmp_data++ << 16);
hmp_file_length += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_file_length);
hmp_data += 12;
hmp_size -= 12;
hmp_chunks = *hmp_data++;
hmp_chunks += (*hmp_data++ << 8);
hmp_chunks += (*hmp_data++ << 16);
hmp_chunks += (*hmp_data++ << 24);
hmp_size -= 4;
hmp_unknown = *hmp_data++;
hmp_unknown += (*hmp_data++ << 8);
hmp_unknown += (*hmp_data++ << 16);
hmp_unknown += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_unknown);
hmp_divisions = 60;
hmp_bpm = *hmp_data++;
hmp_bpm += (*hmp_data++ << 8);
hmp_bpm += (*hmp_data++ << 16);
hmp_bpm += (*hmp_data++ << 24);
hmp_size -= 4;
/* Slow but needed for accuracy */
if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) {
tempo_f = (float) (60000000 / hmp_bpm) + 0.5f;
} else {
tempo_f = (float) (60000000 / hmp_bpm);
}
samples_per_delta_f = _WM_GetSamplesPerTick(hmp_divisions, tempo_f);
hmp_song_time = *hmp_data++;
hmp_song_time += (*hmp_data++ << 8);
hmp_song_time += (*hmp_data++ << 16);
hmp_song_time += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_song_time);
if (is_hmp2) {
hmp_data += 840;
hmp_size -= 840;
} else {
hmp_data += 712;
hmp_size -= 712;
}
hmp_mdi = _WM_initMDI();
_WM_midi_setup_divisions(hmp_mdi, hmp_divisions);
_WM_midi_setup_tempo(hmp_mdi, (uint32_t)tempo_f);
hmp_chunk = malloc(sizeof(uint8_t *) * hmp_chunks);
chunk_length = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_delta = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_ofs = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_end = malloc(sizeof(uint8_t) * hmp_chunks);
smallest_delta = 0xffffffff;
for (i = 0; i < hmp_chunks; i++) {
hmp_chunk[i] = hmp_data;
chunk_ofs[i] = 0;
chunk_num = *hmp_data++;
chunk_num += (*hmp_data++ << 8);
chunk_num += (*hmp_data++ << 16);
chunk_num += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
UNUSED(chunk_num);
chunk_length[i] = *hmp_data++;
chunk_length[i] += (*hmp_data++ << 8);
chunk_length[i] += (*hmp_data++ << 16);
chunk_length[i] += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
if (chunk_length[i] > hmp_size) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, "file too short", 0);
goto _hmp_end;
}
hmp_size -= chunk_length[i];
hmp_track = *hmp_data++;
hmp_track += (*hmp_data++ << 8);
hmp_track += (*hmp_data++ << 16);
hmp_track += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
UNUSED(hmp_track);
chunk_delta[i] = 0;
var_len_shift = 0;
if (*hmp_data < 0x80) {
do {
chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift);
var_len_shift += 7;
chunk_ofs[i]++;
} while (*hmp_data < 0x80);
}
chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift);
chunk_ofs[i]++;
if (chunk_delta[i] < smallest_delta) {
smallest_delta = chunk_delta[i];
}
hmp_data = hmp_chunk[i] + chunk_length[i];
hmp_chunk[i] += chunk_ofs[i]++;
chunk_end[i] = 0;
}
subtract_delta = smallest_delta;
sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count;
hmp_mdi->extra_info.approx_total_samples += sample_count;
while (end_of_chunks < hmp_chunks) {
smallest_delta = 0;
for (i = 0; i < hmp_chunks; i++) {
if (chunk_end[i])
continue;
if (chunk_delta[i]) {
chunk_delta[i] -= subtract_delta;
if (chunk_delta[i]) {
if ((!smallest_delta)
|| (smallest_delta > chunk_delta[i])) {
smallest_delta = chunk_delta[i];
}
continue;
}
}
do {
if (((hmp_chunk[i][0] & 0xf0) == 0xb0 ) && ((hmp_chunk[i][1] == 110) || (hmp_chunk[i][1] == 111)) && (hmp_chunk[i][2] > 0x7f)) {
hmp_chunk[i] += 3;
} else {
uint32_t setup_ret = 0;
if ((setup_ret = _WM_SetupMidiEvent(hmp_mdi, hmp_chunk[i], 0)) == 0) {
goto _hmp_end;
}
if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x2f) && (hmp_chunk[i][2] == 0x00)) {
/* End of Chunk */
end_of_chunks++;
chunk_end[i] = 1;
hmp_chunk[i] += 3;
goto NEXT_CHUNK;
} else if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x51) && (hmp_chunk[i][2] == 0x03)) {
/* Tempo */
tempo_f = (float)((hmp_chunk[i][3] << 16) + (hmp_chunk[i][4] << 8)+ hmp_chunk[i][5]);
if (tempo_f == 0.0)
tempo_f = 500000.0;
fprintf(stderr,"DEBUG: Tempo change %f\r\n", tempo_f);
}
hmp_chunk[i] += setup_ret;
}
var_len_shift = 0;
chunk_delta[i] = 0;
if (*hmp_chunk[i] < 0x80) {
do {
chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift);
var_len_shift += 7;
hmp_chunk[i]++;
} while (*hmp_chunk[i] < 0x80);
}
chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift);
hmp_chunk[i]++;
} while (!chunk_delta[i]);
if ((!smallest_delta) || (smallest_delta > chunk_delta[i])) {
smallest_delta = chunk_delta[i];
}
NEXT_CHUNK: continue;
}
subtract_delta = smallest_delta;
sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count;
hmp_mdi->extra_info.approx_total_samples += sample_count;
}
if ((hmp_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _hmp_end;
}
hmp_mdi->extra_info.current_sample = 0;
hmp_mdi->current_event = &hmp_mdi->events[0];
hmp_mdi->samples_to_mix = 0;
hmp_mdi->note = NULL;
_WM_ResetToStart(hmp_mdi);
_hmp_end:
free(hmp_chunk);
free(chunk_length);
free(chunk_delta);
free(chunk_ofs);
free(chunk_end);
if (hmp_mdi->reverb) return (hmp_mdi);
_WM_freeMDI(hmp_mdi);
return NULL;
}
Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows
where to stop reading, and adjust its users properly. Fixes bug #175
(CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.)
CWE ID: CWE-125 | _WM_ParseNewHmp(uint8_t *hmp_data, uint32_t hmp_size) {
uint8_t is_hmp2 = 0;
uint32_t zero_cnt = 0;
uint32_t i = 0;
uint32_t hmp_file_length = 0;
uint32_t hmp_chunks = 0;
uint32_t hmp_divisions = 0;
uint32_t hmp_unknown = 0;
uint32_t hmp_bpm = 0;
uint32_t hmp_song_time = 0;
struct _mdi *hmp_mdi;
uint8_t **hmp_chunk;
uint32_t *chunk_length;
uint32_t *chunk_ofs;
uint32_t *chunk_delta;
uint8_t *chunk_end;
uint32_t chunk_num = 0;
uint32_t hmp_track = 0;
uint32_t smallest_delta = 0;
uint32_t subtract_delta = 0;
uint32_t end_of_chunks = 0;
uint32_t var_len_shift = 0;
float tempo_f = 500000.0;
float samples_per_delta_f = 0.0;
uint32_t sample_count = 0;
float sample_count_f = 0;
float sample_remainder = 0;
if (memcmp(hmp_data, "HMIMIDIP", 8)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0);
return NULL;
}
hmp_data += 8;
hmp_size -= 8;
if (!memcmp(hmp_data, "013195", 6)) {
hmp_data += 6;
hmp_size -= 6;
is_hmp2 = 1;
}
if (is_hmp2) {
zero_cnt = 18;
} else {
zero_cnt = 24;
}
for (i = 0; i < zero_cnt; i++) {
if (hmp_data[i] != 0) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0);
return NULL;
}
}
hmp_data += zero_cnt;
hmp_size -= zero_cnt;
hmp_file_length = *hmp_data++;
hmp_file_length += (*hmp_data++ << 8);
hmp_file_length += (*hmp_data++ << 16);
hmp_file_length += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_file_length);
hmp_data += 12;
hmp_size -= 12;
hmp_chunks = *hmp_data++;
hmp_chunks += (*hmp_data++ << 8);
hmp_chunks += (*hmp_data++ << 16);
hmp_chunks += (*hmp_data++ << 24);
hmp_size -= 4;
hmp_unknown = *hmp_data++;
hmp_unknown += (*hmp_data++ << 8);
hmp_unknown += (*hmp_data++ << 16);
hmp_unknown += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_unknown);
hmp_divisions = 60;
hmp_bpm = *hmp_data++;
hmp_bpm += (*hmp_data++ << 8);
hmp_bpm += (*hmp_data++ << 16);
hmp_bpm += (*hmp_data++ << 24);
hmp_size -= 4;
/* Slow but needed for accuracy */
if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) {
tempo_f = (float) (60000000 / hmp_bpm) + 0.5f;
} else {
tempo_f = (float) (60000000 / hmp_bpm);
}
samples_per_delta_f = _WM_GetSamplesPerTick(hmp_divisions, tempo_f);
hmp_song_time = *hmp_data++;
hmp_song_time += (*hmp_data++ << 8);
hmp_song_time += (*hmp_data++ << 16);
hmp_song_time += (*hmp_data++ << 24);
hmp_size -= 4;
UNUSED(hmp_song_time);
if (is_hmp2) {
hmp_data += 840;
hmp_size -= 840;
} else {
hmp_data += 712;
hmp_size -= 712;
}
hmp_mdi = _WM_initMDI();
_WM_midi_setup_divisions(hmp_mdi, hmp_divisions);
_WM_midi_setup_tempo(hmp_mdi, (uint32_t)tempo_f);
hmp_chunk = malloc(sizeof(uint8_t *) * hmp_chunks);
chunk_length = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_delta = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_ofs = malloc(sizeof(uint32_t) * hmp_chunks);
chunk_end = malloc(sizeof(uint8_t) * hmp_chunks);
smallest_delta = 0xffffffff;
for (i = 0; i < hmp_chunks; i++) {
hmp_chunk[i] = hmp_data;
chunk_ofs[i] = 0;
chunk_num = *hmp_data++;
chunk_num += (*hmp_data++ << 8);
chunk_num += (*hmp_data++ << 16);
chunk_num += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
UNUSED(chunk_num);
chunk_length[i] = *hmp_data++;
chunk_length[i] += (*hmp_data++ << 8);
chunk_length[i] += (*hmp_data++ << 16);
chunk_length[i] += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
if (chunk_length[i] > hmp_size) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, "file too short", 0);
goto _hmp_end;
}
hmp_size -= chunk_length[i];
hmp_track = *hmp_data++;
hmp_track += (*hmp_data++ << 8);
hmp_track += (*hmp_data++ << 16);
hmp_track += (*hmp_data++ << 24);
chunk_ofs[i] += 4;
UNUSED(hmp_track);
chunk_delta[i] = 0;
var_len_shift = 0;
if (*hmp_data < 0x80) {
do {
chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift);
var_len_shift += 7;
chunk_ofs[i]++;
} while (*hmp_data < 0x80);
}
chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift);
chunk_ofs[i]++;
if (chunk_delta[i] < smallest_delta) {
smallest_delta = chunk_delta[i];
}
hmp_data = hmp_chunk[i] + chunk_length[i];
chunk_length[i] -= chunk_ofs[i];
hmp_chunk[i] += chunk_ofs[i]++;
chunk_end[i] = 0;
}
subtract_delta = smallest_delta;
sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count;
hmp_mdi->extra_info.approx_total_samples += sample_count;
while (end_of_chunks < hmp_chunks) {
smallest_delta = 0;
for (i = 0; i < hmp_chunks; i++) {
if (chunk_end[i])
continue;
if (chunk_delta[i]) {
chunk_delta[i] -= subtract_delta;
if (chunk_delta[i]) {
if ((!smallest_delta)
|| (smallest_delta > chunk_delta[i])) {
smallest_delta = chunk_delta[i];
}
continue;
}
}
do {
if (((hmp_chunk[i][0] & 0xf0) == 0xb0 ) && ((hmp_chunk[i][1] == 110) || (hmp_chunk[i][1] == 111)) && (hmp_chunk[i][2] > 0x7f)) {
hmp_chunk[i] += 3;
chunk_length[i] -= 3;
} else {
uint32_t setup_ret = 0;
if ((setup_ret = _WM_SetupMidiEvent(hmp_mdi, hmp_chunk[i], chunk_length[i], 0)) == 0) {
goto _hmp_end;
}
if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x2f) && (hmp_chunk[i][2] == 0x00)) {
/* End of Chunk */
end_of_chunks++;
chunk_end[i] = 1;
chunk_length[i] -= 3;
hmp_chunk[i] += 3;
goto NEXT_CHUNK;
} else if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x51) && (hmp_chunk[i][2] == 0x03)) {
/* Tempo */
tempo_f = (float)((hmp_chunk[i][3] << 16) + (hmp_chunk[i][4] << 8)+ hmp_chunk[i][5]);
if (tempo_f == 0.0)
tempo_f = 500000.0;
fprintf(stderr,"DEBUG: Tempo change %f\r\n", tempo_f);
}
hmp_chunk[i] += setup_ret;
chunk_length[i] -= setup_ret;
}
var_len_shift = 0;
chunk_delta[i] = 0;
if (chunk_length[i] && *hmp_chunk[i] < 0x80) {
do {
if (! chunk_length[i]) break;
chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift);
var_len_shift += 7;
hmp_chunk[i]++;
chunk_length[i]--;
} while (*hmp_chunk[i] < 0x80);
}
if (! chunk_length[i]) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, "file too short", 0);
goto _hmp_end;
}
chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift);
hmp_chunk[i]++;
chunk_length[i]--;
} while (!chunk_delta[i]);
if ((!smallest_delta) || (smallest_delta > chunk_delta[i])) {
smallest_delta = chunk_delta[i];
}
NEXT_CHUNK: continue;
}
subtract_delta = smallest_delta;
sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count;
hmp_mdi->extra_info.approx_total_samples += sample_count;
}
if ((hmp_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _hmp_end;
}
hmp_mdi->extra_info.current_sample = 0;
hmp_mdi->current_event = &hmp_mdi->events[0];
hmp_mdi->samples_to_mix = 0;
hmp_mdi->note = NULL;
_WM_ResetToStart(hmp_mdi);
_hmp_end:
free(hmp_chunk);
free(chunk_length);
free(chunk_delta);
free(chunk_ofs);
free(chunk_end);
if (hmp_mdi->reverb) return (hmp_mdi);
_WM_freeMDI(hmp_mdi);
return NULL;
}
| 168,003 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info,
source_info;
char
format[MaxTextExtent],
message[MaxTextExtent];
const char
*type;
MagickSizeType
length,
number_pixels;
MagickStatusType
status;
size_t
columns,
packet_size;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
assert(image->cache != (Cache) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns == 0) || (image->rows == 0))
ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickSignature);
if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,image->rows) == MagickFalse))
ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed",
image->filename);
source_info=(*cache_info);
source_info.file=(-1);
(void) FormatLocaleString(cache_info->filename,MaxTextExtent,"%s[%.20g]",
image->filename,(double) GetImageIndexInList(image));
cache_info->mode=mode;
cache_info->rows=image->rows;
cache_info->columns=image->columns;
cache_info->channels=image->channels;
cache_info->active_index_channel=((image->storage_class == PseudoClass) ||
(image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse;
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
packet_size=sizeof(PixelPacket);
if (cache_info->active_index_channel != MagickFalse)
packet_size+=sizeof(IndexPacket);
length=number_pixels*packet_size;
columns=(size_t) (length/cache_info->rows/packet_size);
if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) ||
((ssize_t) cache_info->rows < 0))
ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed",
image->filename);
cache_info->length=length;
if (image->ping != MagickFalse)
{
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->type=PingCache;
return(MagickTrue);
}
status=AcquireMagickResource(AreaResource,cache_info->length);
length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));
if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)))
{
status=AcquireMagickResource(MemoryResource,cache_info->length);
if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) ||
(cache_info->type == MemoryCache))
{
AllocatePixelCachePixels(cache_info);
if (cache_info->pixels == (PixelPacket *) NULL)
cache_info->pixels=source_info.pixels;
else
{
/*
Create memory pixel cache.
*/
cache_info->colorspace=image->colorspace;
cache_info->type=MemoryCache;
cache_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
cache_info->indexes=(IndexPacket *) (cache_info->pixels+
number_pixels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status&=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",
type,(double) cache_info->columns,(double) cache_info->rows,
format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
cache_info->storage_class=image->storage_class;
return(MagickTrue);
}
}
RelinquishMagickResource(MemoryResource,cache_info->length);
}
/*
Create pixel cache on disk.
*/
status=AcquireMagickResource(DiskResource,cache_info->length);
if ((status == MagickFalse) || (cache_info->type == DistributedCache))
{
DistributeCacheInfo
*server_info;
if (cache_info->type == DistributedCache)
RelinquishMagickResource(DiskResource,cache_info->length);
server_info=AcquireDistributeCacheInfo(exception);
if (server_info != (DistributeCacheInfo *) NULL)
{
status=OpenDistributePixelCache(server_info,image);
if (status == MagickFalse)
{
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
GetDistributeCacheHostname(server_info));
server_info=DestroyDistributeCacheInfo(server_info);
}
else
{
/*
Create a distributed pixel cache.
*/
cache_info->type=DistributedCache;
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->server_info=server_info;
(void) FormatLocaleString(cache_info->cache_filename,
MaxTextExtent,"%s:%d",GetDistributeCacheHostname(
(DistributeCacheInfo *) cache_info->server_info),
GetDistributeCachePort((DistributeCacheInfo *)
cache_info->server_info));
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,
format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->cache_filename,GetDistributeCacheFile(
(DistributeCacheInfo *) cache_info->server_info),type,
(double) cache_info->columns,(double) cache_info->rows,
format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
return(MagickTrue);
}
}
RelinquishMagickResource(DiskResource,cache_info->length);
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'",image->filename);
return(MagickFalse);
}
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
{
(void) ClosePixelCacheOnDisk(cache_info);
*cache_info->cache_filename='\0';
}
if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse)
{
RelinquishMagickResource(DiskResource,cache_info->length);
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
image->filename);
return(MagickFalse);
}
status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+
cache_info->length);
if (status == MagickFalse)
{
ThrowFileException(exception,CacheError,"UnableToExtendCache",
image->filename);
return(MagickFalse);
}
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));
if (length != (MagickSizeType) ((size_t) length))
cache_info->type=DiskCache;
else
{
status=AcquireMagickResource(MapResource,cache_info->length);
if ((status == MagickFalse) && (cache_info->type != MapCache) &&
(cache_info->type != MemoryCache))
cache_info->type=DiskCache;
else
{
cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode,
cache_info->offset,(size_t) cache_info->length);
if (cache_info->pixels == (PixelPacket *) NULL)
{
cache_info->pixels=source_info.pixels;
cache_info->type=DiskCache;
}
else
{
/*
Create file-backed memory-mapped pixel cache.
*/
(void) ClosePixelCacheOnDisk(cache_info);
cache_info->type=MapCache;
cache_info->mapped=MagickTrue;
cache_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
cache_info->indexes=(IndexPacket *) (cache_info->pixels+
number_pixels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",
cache_info->filename,cache_info->cache_filename,
cache_info->file,type,(double) cache_info->columns,(double)
cache_info->rows,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
return(MagickTrue);
}
}
RelinquishMagickResource(MapResource,cache_info->length);
}
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->cache_filename,cache_info->file,type,(double)
cache_info->columns,(double) cache_info->rows,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(MagickTrue);
}
Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=2&t=28946
CWE ID: CWE-399 | static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info,
source_info;
char
format[MaxTextExtent],
message[MaxTextExtent];
const char
*type;
MagickSizeType
length,
number_pixels;
MagickStatusType
status;
size_t
columns,
packet_size;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
assert(image->cache != (Cache) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns == 0) || (image->rows == 0))
ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickSignature);
if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,image->rows) == MagickFalse))
ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed",
image->filename);
source_info=(*cache_info);
source_info.file=(-1);
(void) FormatLocaleString(cache_info->filename,MaxTextExtent,"%s[%.20g]",
image->filename,(double) GetImageIndexInList(image));
cache_info->mode=mode;
cache_info->rows=image->rows;
cache_info->columns=image->columns;
cache_info->channels=image->channels;
cache_info->active_index_channel=((image->storage_class == PseudoClass) ||
(image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse;
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
packet_size=sizeof(PixelPacket);
if (cache_info->active_index_channel != MagickFalse)
packet_size+=sizeof(IndexPacket);
length=number_pixels*packet_size;
columns=(size_t) (length/cache_info->rows/packet_size);
if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) ||
((ssize_t) cache_info->rows < 0))
ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed",
image->filename);
cache_info->length=length;
if (image->ping != MagickFalse)
{
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->type=PingCache;
return(MagickTrue);
}
status=AcquireMagickResource(AreaResource,cache_info->length);
length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));
if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)))
{
status=AcquireMagickResource(MemoryResource,cache_info->length);
if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) ||
(cache_info->type == MemoryCache))
{
cache_info->mapped=MagickFalse;
cache_info->pixels=(PixelPacket *) MagickAssumeAligned(
AcquireAlignedMemory(1,(size_t) cache_info->length));
if (cache_info->pixels == (PixelPacket *) NULL)
cache_info->pixels=source_info.pixels;
else
{
/*
Create memory pixel cache.
*/
cache_info->colorspace=image->colorspace;
cache_info->type=MemoryCache;
cache_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
cache_info->indexes=(IndexPacket *) (cache_info->pixels+
number_pixels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status&=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",
type,(double) cache_info->columns,(double) cache_info->rows,
format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
cache_info->storage_class=image->storage_class;
return(MagickTrue);
}
}
RelinquishMagickResource(MemoryResource,cache_info->length);
}
/*
Create pixel cache on disk.
*/
status=AcquireMagickResource(DiskResource,cache_info->length);
if ((status == MagickFalse) || (cache_info->type == DistributedCache))
{
DistributeCacheInfo
*server_info;
if (cache_info->type == DistributedCache)
RelinquishMagickResource(DiskResource,cache_info->length);
server_info=AcquireDistributeCacheInfo(exception);
if (server_info != (DistributeCacheInfo *) NULL)
{
status=OpenDistributePixelCache(server_info,image);
if (status == MagickFalse)
{
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
GetDistributeCacheHostname(server_info));
server_info=DestroyDistributeCacheInfo(server_info);
}
else
{
/*
Create a distributed pixel cache.
*/
cache_info->type=DistributedCache;
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->server_info=server_info;
(void) FormatLocaleString(cache_info->cache_filename,
MaxTextExtent,"%s:%d",GetDistributeCacheHostname(
(DistributeCacheInfo *) cache_info->server_info),
GetDistributeCachePort((DistributeCacheInfo *)
cache_info->server_info));
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,
format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->cache_filename,GetDistributeCacheFile(
(DistributeCacheInfo *) cache_info->server_info),type,
(double) cache_info->columns,(double) cache_info->rows,
format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
return(MagickTrue);
}
}
RelinquishMagickResource(DiskResource,cache_info->length);
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'",image->filename);
return(MagickFalse);
}
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
{
(void) ClosePixelCacheOnDisk(cache_info);
*cache_info->cache_filename='\0';
}
if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse)
{
RelinquishMagickResource(DiskResource,cache_info->length);
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
image->filename);
return(MagickFalse);
}
status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+
cache_info->length);
if (status == MagickFalse)
{
ThrowFileException(exception,CacheError,"UnableToExtendCache",
image->filename);
return(MagickFalse);
}
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));
if (length != (MagickSizeType) ((size_t) length))
cache_info->type=DiskCache;
else
{
status=AcquireMagickResource(MapResource,cache_info->length);
if ((status == MagickFalse) && (cache_info->type != MapCache) &&
(cache_info->type != MemoryCache))
cache_info->type=DiskCache;
else
{
cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode,
cache_info->offset,(size_t) cache_info->length);
if (cache_info->pixels == (PixelPacket *) NULL)
{
cache_info->pixels=source_info.pixels;
cache_info->type=DiskCache;
}
else
{
/*
Create file-backed memory-mapped pixel cache.
*/
(void) ClosePixelCacheOnDisk(cache_info);
cache_info->type=MapCache;
cache_info->mapped=MagickTrue;
cache_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
cache_info->indexes=(IndexPacket *) (cache_info->pixels+
number_pixels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",
cache_info->filename,cache_info->cache_filename,
cache_info->file,type,(double) cache_info->columns,(double)
cache_info->rows,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
return(MagickTrue);
}
}
RelinquishMagickResource(MapResource,cache_info->length);
}
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->cache_filename,cache_info->file,type,(double)
cache_info->columns,(double) cache_info->rows,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(MagickTrue);
}
| 168,788 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GesturePoint::IsInClickTimeWindow() const {
double duration = last_touch_time_ - first_touch_time_;
return duration >= kMinimumTouchDownDurationInSecondsForClick &&
duration < kMaximumTouchDownDurationInSecondsForClick;
}
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::IsInClickTimeWindow() const {
double duration = last_touch_time_ - first_touch_time_;
return duration >=
GestureConfiguration::min_touch_down_duration_in_seconds_for_click() &&
duration <
GestureConfiguration::max_touch_down_duration_in_seconds_for_click();
}
| 171,042 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PresentationConnectionProxy::OnClose() {
DCHECK(target_connection_ptr_);
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Closed);
target_connection_ptr_->DidChangeState(
content::PRESENTATION_CONNECTION_STATE_CLOSED);
}
Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures
Add layout test.
1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead.
BUG=697719
Review-Url: https://codereview.chromium.org/2730123003
Cr-Commit-Position: refs/heads/master@{#455225}
CWE ID: | void PresentationConnectionProxy::OnClose() {
DCHECK(target_connection_ptr_);
source_connection_->didClose();
target_connection_ptr_->DidChangeState(
content::PRESENTATION_CONNECTION_STATE_CLOSED);
}
| 172,045 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool DownloadManagerImpl::InterceptDownload(
const download::DownloadCreateInfo& info) {
WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID(
info.render_process_id, info.render_frame_id);
if (info.is_new_download &&
info.result ==
download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) {
if (web_contents) {
std::vector<GURL> url_chain(info.url_chain);
GURL url = url_chain.back();
url_chain.pop_back();
NavigationController::LoadURLParams params(url);
params.has_user_gesture = info.has_user_gesture;
params.referrer = Referrer(
info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
info.referrer_policy));
params.redirect_chain = url_chain;
web_contents->GetController().LoadURLWithParams(params);
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
if (!delegate_ ||
!delegate_->InterceptDownloadIfApplicable(
info.url(), info.mime_type, info.request_origin, web_contents)) {
return false;
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284 | bool DownloadManagerImpl::InterceptDownload(
const download::DownloadCreateInfo& info) {
WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID(
info.render_process_id, info.render_frame_id);
if (info.is_new_download &&
info.result ==
download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) {
if (web_contents) {
std::vector<GURL> url_chain(info.url_chain);
GURL url = url_chain.back();
url_chain.pop_back();
NavigationController::LoadURLParams params(url);
params.has_user_gesture = info.has_user_gesture;
params.referrer = Referrer(
info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
info.referrer_policy));
params.redirect_chain = url_chain;
params.frame_tree_node_id =
RenderFrameHost::GetFrameTreeNodeIdForRoutingId(
info.render_process_id, info.render_frame_id);
web_contents->GetController().LoadURLWithParams(params);
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
if (!delegate_ ||
!delegate_->InterceptDownloadIfApplicable(
info.url(), info.mime_type, info.request_origin, web_contents)) {
return false;
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
| 173,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pgm_print(netdissect_options *ndo,
register const u_char *bp, register u_int length,
register const u_char *bp2)
{
register const struct pgm_header *pgm;
register const struct ip *ip;
register char ch;
uint16_t sport, dport;
u_int nla_afnum;
char nla_buf[INET6_ADDRSTRLEN];
register const struct ip6_hdr *ip6;
uint8_t opt_type, opt_len;
uint32_t seq, opts_len, len, offset;
pgm = (const struct pgm_header *)bp;
ip = (const struct ip *)bp2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)bp2;
else
ip6 = NULL;
ch = '\0';
if (!ND_TTEST(pgm->pgm_dport)) {
if (ip6) {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
return;
} else {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
return;
}
}
sport = EXTRACT_16BITS(&pgm->pgm_sport);
dport = EXTRACT_16BITS(&pgm->pgm_dport);
if (ip6) {
if (ip6->ip6_nxt == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ip6addr_string(ndo, &ip6->ip6_src),
tcpport_string(ndo, sport),
ip6addr_string(ndo, &ip6->ip6_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
} else {
if (ip->ip_p == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ipaddr_string(ndo, &ip->ip_src),
tcpport_string(ndo, sport),
ipaddr_string(ndo, &ip->ip_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
}
ND_TCHECK(*pgm);
ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length)));
if (!ndo->ndo_vflag)
return;
ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ",
pgm->pgm_gsid[0],
pgm->pgm_gsid[1],
pgm->pgm_gsid[2],
pgm->pgm_gsid[3],
pgm->pgm_gsid[4],
pgm->pgm_gsid[5]));
switch (pgm->pgm_type) {
case PGM_SPM: {
const struct pgm_spm *spm;
spm = (const struct pgm_spm *)(pgm + 1);
ND_TCHECK(*spm);
bp = (const u_char *) (spm + 1);
switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s",
EXTRACT_32BITS(&spm->pgms_seq),
EXTRACT_32BITS(&spm->pgms_trailseq),
EXTRACT_32BITS(&spm->pgms_leadseq),
nla_buf));
break;
}
case PGM_POLL: {
const struct pgm_poll *poll_msg;
poll_msg = (const struct pgm_poll *)(pgm + 1);
ND_TCHECK(*poll_msg);
ND_PRINT((ndo, "POLL seq %u round %u",
EXTRACT_32BITS(&poll_msg->pgmp_seq),
EXTRACT_16BITS(&poll_msg->pgmp_round)));
bp = (const u_char *) (poll_msg + 1);
break;
}
case PGM_POLR: {
const struct pgm_polr *polr;
uint32_t ivl, rnd, mask;
polr = (const struct pgm_polr *)(pgm + 1);
ND_TCHECK(*polr);
bp = (const u_char *) (polr + 1);
switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ivl = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
rnd = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
mask = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x "
"mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq),
EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask));
break;
}
case PGM_ODATA: {
const struct pgm_data *odata;
odata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*odata);
ND_PRINT((ndo, "ODATA trail %u seq %u",
EXTRACT_32BITS(&odata->pgmd_trailseq),
EXTRACT_32BITS(&odata->pgmd_seq)));
bp = (const u_char *) (odata + 1);
break;
}
case PGM_RDATA: {
const struct pgm_data *rdata;
rdata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*rdata);
ND_PRINT((ndo, "RDATA trail %u seq %u",
EXTRACT_32BITS(&rdata->pgmd_trailseq),
EXTRACT_32BITS(&rdata->pgmd_seq)));
bp = (const u_char *) (rdata + 1);
break;
}
case PGM_NAK:
case PGM_NULLNAK:
case PGM_NCF: {
const struct pgm_nak *nak;
char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN];
nak = (const struct pgm_nak *)(pgm + 1);
ND_TCHECK(*nak);
bp = (const u_char *) (nak + 1);
/*
* Skip past the source, saving info along the way
* and stopping if we don't have enough.
*/
switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Skip past the group, saving info along the way
* and stopping if we don't have enough.
*/
bp += (2 * sizeof(uint16_t));
switch (EXTRACT_16BITS(bp)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Options decoding can go here.
*/
switch (pgm->pgm_type) {
case PGM_NAK:
ND_PRINT((ndo, "NAK "));
break;
case PGM_NULLNAK:
ND_PRINT((ndo, "NNAK "));
break;
case PGM_NCF:
ND_PRINT((ndo, "NCF "));
break;
default:
break;
}
ND_PRINT((ndo, "(%s -> %s), seq %u",
source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq)));
break;
}
case PGM_ACK: {
const struct pgm_ack *ack;
ack = (const struct pgm_ack *)(pgm + 1);
ND_TCHECK(*ack);
ND_PRINT((ndo, "ACK seq %u",
EXTRACT_32BITS(&ack->pgma_rx_max_seq)));
bp = (const u_char *) (ack + 1);
break;
}
case PGM_SPMR:
ND_PRINT((ndo, "SPMR"));
break;
default:
ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type));
break;
}
if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) {
/*
* make sure there's enough for the first option header
*/
if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) {
ND_PRINT((ndo, "[|OPT]"));
return;
}
/*
* That option header MUST be an OPT_LENGTH option
* (see the first paragraph of section 9.1 in RFC 3208).
*/
opt_type = *bp++;
if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) {
ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK));
return;
}
opt_len = *bp++;
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
opts_len = EXTRACT_16BITS(bp);
if (opts_len < 4) {
ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len));
return;
}
bp += sizeof(uint16_t);
ND_PRINT((ndo, " OPTS LEN %d", opts_len));
opts_len -= 4;
while (opts_len) {
if (opts_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
opt_type = *bp++;
opt_len = *bp++;
if (opt_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len,
PGM_MIN_OPT_LEN));
break;
}
if (opts_len < opt_len) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, opt_len - 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
switch (opt_type & PGM_OPT_MASK) {
case PGM_OPT_LENGTH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
opts_len -= 4;
break;
case PGM_OPT_FRAGMENT:
if (opt_len != 16) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= 16;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= sizeof(uint32_t); /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < sizeof(uint32_t)) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += sizeof(uint32_t);
opt_len -= sizeof(uint32_t);
opts_len -= sizeof(uint32_t);
}
break;
case PGM_OPT_JOIN:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= 8;
break;
case PGM_OPT_NAK_BO_IVL:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_NAK_BO_RNG:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_REDIRECT:
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 4 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 4 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 4 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 4 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_PARITY_GRP:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= 8;
break;
case PGM_OPT_CURR_TGSIZE:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_NBR_UNREACH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= 4;
break;
case PGM_OPT_PATH_NLA:
ND_PRINT((ndo, " PATH_NLA [%d]", opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_SYN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= 4;
break;
case PGM_OPT_FIN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= 4;
break;
case PGM_OPT_RST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= 4;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= 4;
break;
case PGM_OPT_PGMCC_DATA:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf));
break;
case PGM_OPT_PGMCC_FEEDBACK:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf));
break;
default:
ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
}
if (opt_type & PGM_OPT_END)
break;
}
}
ND_PRINT((ndo, " [%u]", length));
if (ndo->ndo_packettype == PT_PGM_ZMTP1 &&
(pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA))
zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length));
return;
trunc:
ND_PRINT((ndo, "[|pgm]"));
if (ch != '\0')
ND_PRINT((ndo, ">"));
}
Commit Message: CVE-2017-13018/PGM: Add a missing bounds check.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | pgm_print(netdissect_options *ndo,
register const u_char *bp, register u_int length,
register const u_char *bp2)
{
register const struct pgm_header *pgm;
register const struct ip *ip;
register char ch;
uint16_t sport, dport;
u_int nla_afnum;
char nla_buf[INET6_ADDRSTRLEN];
register const struct ip6_hdr *ip6;
uint8_t opt_type, opt_len;
uint32_t seq, opts_len, len, offset;
pgm = (const struct pgm_header *)bp;
ip = (const struct ip *)bp2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)bp2;
else
ip6 = NULL;
ch = '\0';
if (!ND_TTEST(pgm->pgm_dport)) {
if (ip6) {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
return;
} else {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
return;
}
}
sport = EXTRACT_16BITS(&pgm->pgm_sport);
dport = EXTRACT_16BITS(&pgm->pgm_dport);
if (ip6) {
if (ip6->ip6_nxt == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ip6addr_string(ndo, &ip6->ip6_src),
tcpport_string(ndo, sport),
ip6addr_string(ndo, &ip6->ip6_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
} else {
if (ip->ip_p == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ipaddr_string(ndo, &ip->ip_src),
tcpport_string(ndo, sport),
ipaddr_string(ndo, &ip->ip_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
}
ND_TCHECK(*pgm);
ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length)));
if (!ndo->ndo_vflag)
return;
ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ",
pgm->pgm_gsid[0],
pgm->pgm_gsid[1],
pgm->pgm_gsid[2],
pgm->pgm_gsid[3],
pgm->pgm_gsid[4],
pgm->pgm_gsid[5]));
switch (pgm->pgm_type) {
case PGM_SPM: {
const struct pgm_spm *spm;
spm = (const struct pgm_spm *)(pgm + 1);
ND_TCHECK(*spm);
bp = (const u_char *) (spm + 1);
switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s",
EXTRACT_32BITS(&spm->pgms_seq),
EXTRACT_32BITS(&spm->pgms_trailseq),
EXTRACT_32BITS(&spm->pgms_leadseq),
nla_buf));
break;
}
case PGM_POLL: {
const struct pgm_poll *poll_msg;
poll_msg = (const struct pgm_poll *)(pgm + 1);
ND_TCHECK(*poll_msg);
ND_PRINT((ndo, "POLL seq %u round %u",
EXTRACT_32BITS(&poll_msg->pgmp_seq),
EXTRACT_16BITS(&poll_msg->pgmp_round)));
bp = (const u_char *) (poll_msg + 1);
break;
}
case PGM_POLR: {
const struct pgm_polr *polr;
uint32_t ivl, rnd, mask;
polr = (const struct pgm_polr *)(pgm + 1);
ND_TCHECK(*polr);
bp = (const u_char *) (polr + 1);
switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ivl = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
rnd = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
mask = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x "
"mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq),
EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask));
break;
}
case PGM_ODATA: {
const struct pgm_data *odata;
odata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*odata);
ND_PRINT((ndo, "ODATA trail %u seq %u",
EXTRACT_32BITS(&odata->pgmd_trailseq),
EXTRACT_32BITS(&odata->pgmd_seq)));
bp = (const u_char *) (odata + 1);
break;
}
case PGM_RDATA: {
const struct pgm_data *rdata;
rdata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*rdata);
ND_PRINT((ndo, "RDATA trail %u seq %u",
EXTRACT_32BITS(&rdata->pgmd_trailseq),
EXTRACT_32BITS(&rdata->pgmd_seq)));
bp = (const u_char *) (rdata + 1);
break;
}
case PGM_NAK:
case PGM_NULLNAK:
case PGM_NCF: {
const struct pgm_nak *nak;
char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN];
nak = (const struct pgm_nak *)(pgm + 1);
ND_TCHECK(*nak);
bp = (const u_char *) (nak + 1);
/*
* Skip past the source, saving info along the way
* and stopping if we don't have enough.
*/
switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Skip past the group, saving info along the way
* and stopping if we don't have enough.
*/
bp += (2 * sizeof(uint16_t));
switch (EXTRACT_16BITS(bp)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Options decoding can go here.
*/
switch (pgm->pgm_type) {
case PGM_NAK:
ND_PRINT((ndo, "NAK "));
break;
case PGM_NULLNAK:
ND_PRINT((ndo, "NNAK "));
break;
case PGM_NCF:
ND_PRINT((ndo, "NCF "));
break;
default:
break;
}
ND_PRINT((ndo, "(%s -> %s), seq %u",
source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq)));
break;
}
case PGM_ACK: {
const struct pgm_ack *ack;
ack = (const struct pgm_ack *)(pgm + 1);
ND_TCHECK(*ack);
ND_PRINT((ndo, "ACK seq %u",
EXTRACT_32BITS(&ack->pgma_rx_max_seq)));
bp = (const u_char *) (ack + 1);
break;
}
case PGM_SPMR:
ND_PRINT((ndo, "SPMR"));
break;
default:
ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type));
break;
}
if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) {
/*
* make sure there's enough for the first option header
*/
if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) {
ND_PRINT((ndo, "[|OPT]"));
return;
}
/*
* That option header MUST be an OPT_LENGTH option
* (see the first paragraph of section 9.1 in RFC 3208).
*/
opt_type = *bp++;
if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) {
ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK));
return;
}
opt_len = *bp++;
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
opts_len = EXTRACT_16BITS(bp);
if (opts_len < 4) {
ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len));
return;
}
bp += sizeof(uint16_t);
ND_PRINT((ndo, " OPTS LEN %d", opts_len));
opts_len -= 4;
while (opts_len) {
if (opts_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
opt_type = *bp++;
opt_len = *bp++;
if (opt_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len,
PGM_MIN_OPT_LEN));
break;
}
if (opts_len < opt_len) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, opt_len - 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
switch (opt_type & PGM_OPT_MASK) {
case PGM_OPT_LENGTH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
opts_len -= 4;
break;
case PGM_OPT_FRAGMENT:
if (opt_len != 16) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= 16;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= sizeof(uint32_t); /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < sizeof(uint32_t)) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += sizeof(uint32_t);
opt_len -= sizeof(uint32_t);
opts_len -= sizeof(uint32_t);
}
break;
case PGM_OPT_JOIN:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= 8;
break;
case PGM_OPT_NAK_BO_IVL:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_NAK_BO_RNG:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_REDIRECT:
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 4 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 4 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 4 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 4 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_PARITY_GRP:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= 8;
break;
case PGM_OPT_CURR_TGSIZE:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_NBR_UNREACH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= 4;
break;
case PGM_OPT_PATH_NLA:
ND_PRINT((ndo, " PATH_NLA [%d]", opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_SYN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= 4;
break;
case PGM_OPT_FIN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= 4;
break;
case PGM_OPT_RST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= 4;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= 4;
break;
case PGM_OPT_PGMCC_DATA:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf));
break;
case PGM_OPT_PGMCC_FEEDBACK:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf));
break;
default:
ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
}
if (opt_type & PGM_OPT_END)
break;
}
}
ND_PRINT((ndo, " [%u]", length));
if (ndo->ndo_packettype == PT_PGM_ZMTP1 &&
(pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA))
zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length));
return;
trunc:
ND_PRINT((ndo, "[|pgm]"));
if (ch != '\0')
ND_PRINT((ndo, ">"));
}
| 167,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int NaClIPCAdapter::TakeClientFileDescriptor() {
return io_thread_data_.channel_->TakeClientFileDescriptor();
}
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 | int NaClIPCAdapter::TakeClientFileDescriptor() {
| 170,731 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: dns_resolver_match(const struct key *key,
const struct key_match_data *match_data)
{
int slen, dlen, ret = 0;
const char *src = key->description, *dsp = match_data->raw_data;
kenter("%s,%s", src, dsp);
if (!src || !dsp)
goto no_match;
if (strcasecmp(src, dsp) == 0)
goto matched;
slen = strlen(src);
dlen = strlen(dsp);
if (slen <= 0 || dlen <= 0)
goto no_match;
if (src[slen - 1] == '.')
slen--;
if (dsp[dlen - 1] == '.')
dlen--;
if (slen != dlen || strncasecmp(src, dsp, slen) != 0)
goto no_match;
matched:
ret = 1;
no_match:
kleave(" = %d", ret);
return ret;
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476 | dns_resolver_match(const struct key *key,
static int dns_resolver_cmp(const struct key *key,
const struct key_match_data *match_data)
{
int slen, dlen, ret = 0;
const char *src = key->description, *dsp = match_data->raw_data;
kenter("%s,%s", src, dsp);
if (!src || !dsp)
goto no_match;
if (strcasecmp(src, dsp) == 0)
goto matched;
slen = strlen(src);
dlen = strlen(dsp);
if (slen <= 0 || dlen <= 0)
goto no_match;
if (src[slen - 1] == '.')
slen--;
if (dsp[dlen - 1] == '.')
dlen--;
if (slen != dlen || strncasecmp(src, dsp, slen) != 0)
goto no_match;
matched:
ret = 1;
no_match:
kleave(" = %d", ret);
return ret;
}
| 168,438 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
{
write_seqlock(&state->seqlock);
nfs_set_open_stateid_locked(state, stateid, open_flags);
write_sequnlock(&state->seqlock);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
{
write_seqlock(&state->seqlock);
nfs_set_open_stateid_locked(state, stateid, fmode);
write_sequnlock(&state->seqlock);
}
| 165,705 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UsbDeviceImpl::OpenInterface(int interface_id,
const OpenCallback& callback) {
chromeos::PermissionBrokerClient* client =
chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient();
DCHECK(client) << "Could not get permission broker client.";
client->RequestPathAccess(
device_path_, interface_id,
base::Bind(&UsbDeviceImpl::OnPathAccessRequestComplete, this, callback));
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399 | void UsbDeviceImpl::OpenInterface(int interface_id,
| 171,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nl80211_trigger_scan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_scan_request *request;
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
enum ieee80211_band band;
size_t ie_len;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
wiphy = &rdev->wiphy;
if (!rdev->ops->scan)
return -EOPNOTSUPP;
if (rdev->scan_req)
return -EBUSY;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len)
return -EINVAL;
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request)
return -ENOMEM;
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_FREQUENCIES], tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) {
if (request->ssids[i].ssid_len > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr));
request->ssids[i].ssid_len = nla_len(attr);
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
rdev->scan_req = request;
err = rdev->ops->scan(&rdev->wiphy, dev, request);
if (!err) {
nl80211_send_scan_start(rdev, dev);
dev_hold(dev);
} else {
out_free:
rdev->scan_req = NULL;
kfree(request);
}
return err;
}
Commit Message: nl80211: fix check for valid SSID size in scan operations
In both trigger_scan and sched_scan operations, we were checking for
the SSID length before assigning the value correctly. Since the
memory was just kzalloc'ed, the check was always failing and SSID with
over 32 characters were allowed to go through.
This was causing a buffer overflow when copying the actual SSID to the
proper place.
This bug has been there since 2.6.29-rc4.
Cc: [email protected]
Signed-off-by: Luciano Coelho <[email protected]>
Signed-off-by: John W. Linville <[email protected]>
CWE ID: CWE-119 | static int nl80211_trigger_scan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_scan_request *request;
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
enum ieee80211_band band;
size_t ie_len;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
wiphy = &rdev->wiphy;
if (!rdev->ops->scan)
return -EOPNOTSUPP;
if (rdev->scan_req)
return -EBUSY;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len)
return -EINVAL;
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request)
return -ENOMEM;
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_FREQUENCIES], tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) {
request->ssids[i].ssid_len = nla_len(attr);
if (request->ssids[i].ssid_len > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr));
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
rdev->scan_req = request;
err = rdev->ops->scan(&rdev->wiphy, dev, request);
if (!err) {
nl80211_send_scan_start(rdev, dev);
dev_hold(dev);
} else {
out_free:
rdev->scan_req = NULL;
kfree(request);
}
return err;
}
| 165,858 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void cmd_parse_status(struct ImapData *idata, char *s)
{
char *value = NULL;
struct Buffy *inc = NULL;
struct ImapMbox mx;
struct ImapStatus *status = NULL;
unsigned int olduv, oldun;
unsigned int litlen;
short new = 0;
short new_msg_count = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
mailbox = idata->buf;
s = mailbox + litlen;
*s = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
*(s - 1) = '\0';
imap_unmunge_mbox_name(idata, mailbox);
}
status = imap_mboxcache_get(idata, mailbox, 1);
olduv = status->uidvalidity;
oldun = status->uidnext;
if (*s++ != '(')
{
mutt_debug(1, "Error parsing STATUS\n");
return;
}
while (*s && *s != ')')
{
value = imap_next_word(s);
errno = 0;
const unsigned long ulcount = strtoul(value, &value, 10);
if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))
{
mutt_debug(1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_strncmp("MESSAGES", s, 8) == 0)
{
status->messages = count;
new_msg_count = 1;
}
else if (mutt_str_strncmp("RECENT", s, 6) == 0)
status->recent = count;
else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0)
status->uidnext = count;
else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0)
status->uidvalidity = count;
else if (mutt_str_strncmp("UNSEEN", s, 6) == 0)
status->unseen = count;
s = value;
if (*s && *s != ')')
s = imap_next_word(s);
}
mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
status->name, status->uidvalidity, status->uidnext,
status->messages, status->recent, status->unseen);
/* caller is prepared to handle the result herself */
if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)
{
memcpy(idata->cmddata, status, sizeof(struct ImapStatus));
return;
}
mutt_debug(3, "Running default STATUS handler\n");
/* should perhaps move this code back to imap_buffy_check */
for (inc = Incoming; inc; inc = inc->next)
{
if (inc->magic != MUTT_IMAP)
continue;
if (imap_parse_path(inc->path, &mx) < 0)
{
mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path);
continue;
}
if (imap_account_match(&idata->conn->account, &mx.account))
{
if (mx.mbox)
{
value = mutt_str_strdup(mx.mbox);
imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);
FREE(&mx.mbox);
}
else
value = mutt_str_strdup("INBOX");
if (value && (imap_mxcmp(mailbox, value) == 0))
{
mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox,
olduv, oldun, status->unseen);
if (MailCheckRecent)
{
if (olduv && olduv == status->uidvalidity)
{
if (oldun < status->uidnext)
new = (status->unseen > 0);
}
else if (!olduv && !oldun)
{
/* first check per session, use recent. might need a flag for this. */
new = (status->recent > 0);
}
else
new = (status->unseen > 0);
}
else
new = (status->unseen > 0);
#ifdef USE_SIDEBAR
if ((inc->new != new) || (inc->msg_count != status->messages) ||
(inc->msg_unread != status->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
inc->new = new;
if (new_msg_count)
inc->msg_count = status->messages;
inc->msg_unread = status->unseen;
if (inc->new)
{
/* force back to keep detecting new mail until the mailbox is
opened */
status->uidnext = oldun;
}
FREE(&value);
return;
}
FREE(&value);
}
FREE(&mx.mbox);
}
}
Commit Message: Ensure litlen isn't larger than our mailbox
CWE ID: CWE-20 | static void cmd_parse_status(struct ImapData *idata, char *s)
{
char *value = NULL;
struct Buffy *inc = NULL;
struct ImapMbox mx;
struct ImapStatus *status = NULL;
unsigned int olduv, oldun;
unsigned int litlen;
short new = 0;
short new_msg_count = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
if (strlen(idata->buf) < litlen)
{
mutt_debug(1, "Error parsing STATUS mailbox\n");
return;
}
mailbox = idata->buf;
s = mailbox + litlen;
*s = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
*(s - 1) = '\0';
imap_unmunge_mbox_name(idata, mailbox);
}
status = imap_mboxcache_get(idata, mailbox, 1);
olduv = status->uidvalidity;
oldun = status->uidnext;
if (*s++ != '(')
{
mutt_debug(1, "Error parsing STATUS\n");
return;
}
while (*s && *s != ')')
{
value = imap_next_word(s);
errno = 0;
const unsigned long ulcount = strtoul(value, &value, 10);
if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))
{
mutt_debug(1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_strncmp("MESSAGES", s, 8) == 0)
{
status->messages = count;
new_msg_count = 1;
}
else if (mutt_str_strncmp("RECENT", s, 6) == 0)
status->recent = count;
else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0)
status->uidnext = count;
else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0)
status->uidvalidity = count;
else if (mutt_str_strncmp("UNSEEN", s, 6) == 0)
status->unseen = count;
s = value;
if (*s && *s != ')')
s = imap_next_word(s);
}
mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
status->name, status->uidvalidity, status->uidnext,
status->messages, status->recent, status->unseen);
/* caller is prepared to handle the result herself */
if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)
{
memcpy(idata->cmddata, status, sizeof(struct ImapStatus));
return;
}
mutt_debug(3, "Running default STATUS handler\n");
/* should perhaps move this code back to imap_buffy_check */
for (inc = Incoming; inc; inc = inc->next)
{
if (inc->magic != MUTT_IMAP)
continue;
if (imap_parse_path(inc->path, &mx) < 0)
{
mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path);
continue;
}
if (imap_account_match(&idata->conn->account, &mx.account))
{
if (mx.mbox)
{
value = mutt_str_strdup(mx.mbox);
imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);
FREE(&mx.mbox);
}
else
value = mutt_str_strdup("INBOX");
if (value && (imap_mxcmp(mailbox, value) == 0))
{
mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox,
olduv, oldun, status->unseen);
if (MailCheckRecent)
{
if (olduv && olduv == status->uidvalidity)
{
if (oldun < status->uidnext)
new = (status->unseen > 0);
}
else if (!olduv && !oldun)
{
/* first check per session, use recent. might need a flag for this. */
new = (status->recent > 0);
}
else
new = (status->unseen > 0);
}
else
new = (status->unseen > 0);
#ifdef USE_SIDEBAR
if ((inc->new != new) || (inc->msg_count != status->messages) ||
(inc->msg_unread != status->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
inc->new = new;
if (new_msg_count)
inc->msg_count = status->messages;
inc->msg_unread = status->unseen;
if (inc->new)
{
/* force back to keep detecting new mail until the mailbox is
opened */
status->uidnext = oldun;
}
FREE(&value);
return;
}
FREE(&value);
}
FREE(&mx.mbox);
}
}
| 169,138 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OMXNodeInstance::onEvent(
OMX_EVENTTYPE event, OMX_U32 arg1, OMX_U32 arg2) {
const char *arg1String = "??";
const char *arg2String = "??";
ADebug::Level level = ADebug::kDebugInternalState;
switch (event) {
case OMX_EventCmdComplete:
arg1String = asString((OMX_COMMANDTYPE)arg1);
switch (arg1) {
case OMX_CommandStateSet:
arg2String = asString((OMX_STATETYPE)arg2);
level = ADebug::kDebugState;
break;
case OMX_CommandFlush:
case OMX_CommandPortEnable:
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
default:
arg2String = portString(arg2);
}
break;
case OMX_EventError:
arg1String = asString((OMX_ERRORTYPE)arg1);
level = ADebug::kDebugLifeCycle;
break;
case OMX_EventPortSettingsChanged:
arg2String = asString((OMX_INDEXEXTTYPE)arg2);
default:
arg1String = portString(arg1);
}
CLOGI_(level, onEvent, "%s(%x), %s(%x), %s(%x)",
asString(event), event, arg1String, arg1, arg2String, arg2);
const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource());
if (bufferSource != NULL
&& event == OMX_EventCmdComplete
&& arg1 == OMX_CommandStateSet
&& arg2 == OMX_StateExecuting) {
bufferSource->omxExecuting();
}
}
Commit Message: IOMX: allow configuration after going to loaded state
This was disallowed recently but we still use it as MediaCodcec.stop
only goes to loaded state, and does not free component.
Bug: 31450460
Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d
(cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b)
CWE ID: CWE-200 | void OMXNodeInstance::onEvent(
OMX_EVENTTYPE event, OMX_U32 arg1, OMX_U32 arg2) {
const char *arg1String = "??";
const char *arg2String = "??";
ADebug::Level level = ADebug::kDebugInternalState;
switch (event) {
case OMX_EventCmdComplete:
arg1String = asString((OMX_COMMANDTYPE)arg1);
switch (arg1) {
case OMX_CommandStateSet:
arg2String = asString((OMX_STATETYPE)arg2);
level = ADebug::kDebugState;
break;
case OMX_CommandFlush:
case OMX_CommandPortEnable:
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
default:
arg2String = portString(arg2);
}
break;
case OMX_EventError:
arg1String = asString((OMX_ERRORTYPE)arg1);
level = ADebug::kDebugLifeCycle;
break;
case OMX_EventPortSettingsChanged:
arg2String = asString((OMX_INDEXEXTTYPE)arg2);
default:
arg1String = portString(arg1);
}
CLOGI_(level, onEvent, "%s(%x), %s(%x), %s(%x)",
asString(event), event, arg1String, arg1, arg2String, arg2);
const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource());
if (bufferSource != NULL
&& event == OMX_EventCmdComplete
&& arg1 == OMX_CommandStateSet
&& arg2 == OMX_StateExecuting) {
bufferSource->omxExecuting();
}
// allow configuration if we return to the loaded state
if (event == OMX_EventCmdComplete
&& arg1 == OMX_CommandStateSet
&& arg2 == OMX_StateLoaded) {
mSailed = false;
}
}
| 173,379 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
const struct net_device_ops *slave_ops = slave_dev->netdev_ops;
struct slave *new_slave = NULL;
struct netdev_hw_addr *ha;
struct sockaddr addr;
int link_reporting;
int res = 0;
if (!bond->params.use_carrier && slave_dev->ethtool_ops == NULL &&
slave_ops->ndo_do_ioctl == NULL) {
pr_warning("%s: Warning: no link monitoring support for %s\n",
bond_dev->name, slave_dev->name);
}
/* already enslaved */
if (slave_dev->flags & IFF_SLAVE) {
pr_debug("Error, Device was already enslaved\n");
return -EBUSY;
}
/* vlan challenged mutual exclusion */
/* no need to lock since we're protected by rtnl_lock */
if (slave_dev->features & NETIF_F_VLAN_CHALLENGED) {
pr_debug("%s: NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
if (bond_vlan_used(bond)) {
pr_err("%s: Error: cannot enslave VLAN challenged slave %s on VLAN enabled bond %s\n",
bond_dev->name, slave_dev->name, bond_dev->name);
return -EPERM;
} else {
pr_warning("%s: Warning: enslaved VLAN challenged slave %s. Adding VLANs will be blocked as long as %s is part of bond %s\n",
bond_dev->name, slave_dev->name,
slave_dev->name, bond_dev->name);
}
} else {
pr_debug("%s: ! NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
}
/*
* Old ifenslave binaries are no longer supported. These can
* be identified with moderate accuracy by the state of the slave:
* the current ifenslave will set the interface down prior to
* enslaving it; the old ifenslave will not.
*/
if ((slave_dev->flags & IFF_UP)) {
pr_err("%s is up. This may be due to an out of date ifenslave.\n",
slave_dev->name);
res = -EPERM;
goto err_undo_flags;
}
/* set bonding device ether type by slave - bonding netdevices are
* created with ether_setup, so when the slave type is not ARPHRD_ETHER
* there is a need to override some of the type dependent attribs/funcs.
*
* bond ether type mutual exclusion - don't allow slaves of dissimilar
* ether type (eg ARPHRD_ETHER and ARPHRD_INFINIBAND) share the same bond
*/
if (bond->slave_cnt == 0) {
if (bond_dev->type != slave_dev->type) {
pr_debug("%s: change device type from %d to %d\n",
bond_dev->name,
bond_dev->type, slave_dev->type);
res = netdev_bonding_change(bond_dev,
NETDEV_PRE_TYPE_CHANGE);
res = notifier_to_errno(res);
if (res) {
pr_err("%s: refused to change device type\n",
bond_dev->name);
res = -EBUSY;
goto err_undo_flags;
}
/* Flush unicast and multicast addresses */
dev_uc_flush(bond_dev);
dev_mc_flush(bond_dev);
if (slave_dev->type != ARPHRD_ETHER)
bond_setup_by_slave(bond_dev, slave_dev);
else
ether_setup(bond_dev);
netdev_bonding_change(bond_dev,
NETDEV_POST_TYPE_CHANGE);
}
} else if (bond_dev->type != slave_dev->type) {
pr_err("%s ether type (%d) is different from other slaves (%d), can not enslave it.\n",
slave_dev->name,
slave_dev->type, bond_dev->type);
res = -EINVAL;
goto err_undo_flags;
}
if (slave_ops->ndo_set_mac_address == NULL) {
if (bond->slave_cnt == 0) {
pr_warning("%s: Warning: The first slave device specified does not support setting the MAC address. Setting fail_over_mac to active.",
bond_dev->name);
bond->params.fail_over_mac = BOND_FOM_ACTIVE;
} else if (bond->params.fail_over_mac != BOND_FOM_ACTIVE) {
pr_err("%s: Error: The slave device specified does not support setting the MAC address, but fail_over_mac is not set to active.\n",
bond_dev->name);
res = -EOPNOTSUPP;
goto err_undo_flags;
}
}
call_netdevice_notifiers(NETDEV_JOIN, slave_dev);
/* If this is the first slave, then we need to set the master's hardware
* address to be the same as the slave's. */
if (is_zero_ether_addr(bond->dev->dev_addr))
memcpy(bond->dev->dev_addr, slave_dev->dev_addr,
slave_dev->addr_len);
new_slave = kzalloc(sizeof(struct slave), GFP_KERNEL);
if (!new_slave) {
res = -ENOMEM;
goto err_undo_flags;
}
/*
* Set the new_slave's queue_id to be zero. Queue ID mapping
* is set via sysfs or module option if desired.
*/
new_slave->queue_id = 0;
/* Save slave's original mtu and then set it to match the bond */
new_slave->original_mtu = slave_dev->mtu;
res = dev_set_mtu(slave_dev, bond->dev->mtu);
if (res) {
pr_debug("Error %d calling dev_set_mtu\n", res);
goto err_free;
}
/*
* Save slave's original ("permanent") mac address for modes
* that need it, and for restoring it upon release, and then
* set it to the master's address
*/
memcpy(new_slave->perm_hwaddr, slave_dev->dev_addr, ETH_ALEN);
if (!bond->params.fail_over_mac) {
/*
* Set slave to master's mac address. The application already
* set the master's mac address to that of the first slave
*/
memcpy(addr.sa_data, bond_dev->dev_addr, bond_dev->addr_len);
addr.sa_family = slave_dev->type;
res = dev_set_mac_address(slave_dev, &addr);
if (res) {
pr_debug("Error %d calling set_mac_address\n", res);
goto err_restore_mtu;
}
}
res = netdev_set_bond_master(slave_dev, bond_dev);
if (res) {
pr_debug("Error %d calling netdev_set_bond_master\n", res);
goto err_restore_mac;
}
/* open the slave since the application closed it */
res = dev_open(slave_dev);
if (res) {
pr_debug("Opening slave %s failed\n", slave_dev->name);
goto err_unset_master;
}
new_slave->bond = bond;
new_slave->dev = slave_dev;
slave_dev->priv_flags |= IFF_BONDING;
if (bond_is_lb(bond)) {
/* bond_alb_init_slave() must be called before all other stages since
* it might fail and we do not want to have to undo everything
*/
res = bond_alb_init_slave(bond, new_slave);
if (res)
goto err_close;
}
/* If the mode USES_PRIMARY, then the new slave gets the
* master's promisc (and mc) settings only if it becomes the
* curr_active_slave, and that is taken care of later when calling
* bond_change_active()
*/
if (!USES_PRIMARY(bond->params.mode)) {
/* set promiscuity level to new slave */
if (bond_dev->flags & IFF_PROMISC) {
res = dev_set_promiscuity(slave_dev, 1);
if (res)
goto err_close;
}
/* set allmulti level to new slave */
if (bond_dev->flags & IFF_ALLMULTI) {
res = dev_set_allmulti(slave_dev, 1);
if (res)
goto err_close;
}
netif_addr_lock_bh(bond_dev);
/* upload master's mc_list to new slave */
netdev_for_each_mc_addr(ha, bond_dev)
dev_mc_add(slave_dev, ha->addr);
netif_addr_unlock_bh(bond_dev);
}
if (bond->params.mode == BOND_MODE_8023AD) {
/* add lacpdu mc addr to mc list */
u8 lacpdu_multicast[ETH_ALEN] = MULTICAST_LACPDU_ADDR;
dev_mc_add(slave_dev, lacpdu_multicast);
}
bond_add_vlans_on_slave(bond, slave_dev);
write_lock_bh(&bond->lock);
bond_attach_slave(bond, new_slave);
new_slave->delay = 0;
new_slave->link_failure_count = 0;
write_unlock_bh(&bond->lock);
bond_compute_features(bond);
read_lock(&bond->lock);
new_slave->last_arp_rx = jiffies;
if (bond->params.miimon && !bond->params.use_carrier) {
link_reporting = bond_check_dev_link(bond, slave_dev, 1);
if ((link_reporting == -1) && !bond->params.arp_interval) {
/*
* miimon is set but a bonded network driver
* does not support ETHTOOL/MII and
* arp_interval is not set. Note: if
* use_carrier is enabled, we will never go
* here (because netif_carrier is always
* supported); thus, we don't need to change
* the messages for netif_carrier.
*/
pr_warning("%s: Warning: MII and ETHTOOL support not available for interface %s, and arp_interval/arp_ip_target module parameters not specified, thus bonding will not detect link failures! see bonding.txt for details.\n",
bond_dev->name, slave_dev->name);
} else if (link_reporting == -1) {
/* unable get link status using mii/ethtool */
pr_warning("%s: Warning: can't get link status from interface %s; the network driver associated with this interface does not support MII or ETHTOOL link status reporting, thus miimon has no effect on this interface.\n",
bond_dev->name, slave_dev->name);
}
}
/* check for initial state */
if (!bond->params.miimon ||
(bond_check_dev_link(bond, slave_dev, 0) == BMSR_LSTATUS)) {
if (bond->params.updelay) {
pr_debug("Initial state of slave_dev is BOND_LINK_BACK\n");
new_slave->link = BOND_LINK_BACK;
new_slave->delay = bond->params.updelay;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_UP\n");
new_slave->link = BOND_LINK_UP;
}
new_slave->jiffies = jiffies;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_DOWN\n");
new_slave->link = BOND_LINK_DOWN;
}
if (bond_update_speed_duplex(new_slave) &&
(new_slave->link != BOND_LINK_DOWN)) {
pr_warning("%s: Warning: failed to get speed and duplex from %s, assumed to be 100Mb/sec and Full.\n",
bond_dev->name, new_slave->dev->name);
if (bond->params.mode == BOND_MODE_8023AD) {
pr_warning("%s: Warning: Operation of 802.3ad mode requires ETHTOOL support in base driver for proper aggregator selection.\n",
bond_dev->name);
}
}
if (USES_PRIMARY(bond->params.mode) && bond->params.primary[0]) {
/* if there is a primary slave, remember it */
if (strcmp(bond->params.primary, new_slave->dev->name) == 0) {
bond->primary_slave = new_slave;
bond->force_primary = true;
}
}
write_lock_bh(&bond->curr_slave_lock);
switch (bond->params.mode) {
case BOND_MODE_ACTIVEBACKUP:
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
case BOND_MODE_8023AD:
/* in 802.3ad mode, the internal mechanism
* will activate the slaves in the selected
* aggregator
*/
bond_set_slave_inactive_flags(new_slave);
/* if this is the first slave */
if (bond->slave_cnt == 1) {
SLAVE_AD_INFO(new_slave).id = 1;
/* Initialize AD with the number of times that the AD timer is called in 1 second
* can be called only after the mac address of the bond is set
*/
bond_3ad_initialize(bond, 1000/AD_TIMER_INTERVAL);
} else {
SLAVE_AD_INFO(new_slave).id =
SLAVE_AD_INFO(new_slave->prev).id + 1;
}
bond_3ad_bind_slave(new_slave);
break;
case BOND_MODE_TLB:
case BOND_MODE_ALB:
bond_set_active_slave(new_slave);
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
default:
pr_debug("This slave is always active in trunk mode\n");
/* always active in trunk mode */
bond_set_active_slave(new_slave);
/* In trunking mode there is little meaning to curr_active_slave
* anyway (it holds no special properties of the bond device),
* so we can change it without calling change_active_interface()
*/
if (!bond->curr_active_slave)
bond->curr_active_slave = new_slave;
break;
} /* switch(bond_mode) */
write_unlock_bh(&bond->curr_slave_lock);
bond_set_carrier(bond);
#ifdef CONFIG_NET_POLL_CONTROLLER
slave_dev->npinfo = bond_netpoll_info(bond);
if (slave_dev->npinfo) {
if (slave_enable_netpoll(new_slave)) {
read_unlock(&bond->lock);
pr_info("Error, %s: master_dev is using netpoll, "
"but new slave device does not support netpoll.\n",
bond_dev->name);
res = -EBUSY;
goto err_close;
}
}
#endif
read_unlock(&bond->lock);
res = bond_create_slave_symlinks(bond_dev, slave_dev);
if (res)
goto err_close;
res = netdev_rx_handler_register(slave_dev, bond_handle_frame,
new_slave);
if (res) {
pr_debug("Error %d calling netdev_rx_handler_register\n", res);
goto err_dest_symlinks;
}
pr_info("%s: enslaving %s as a%s interface with a%s link.\n",
bond_dev->name, slave_dev->name,
bond_is_active_slave(new_slave) ? "n active" : " backup",
new_slave->link != BOND_LINK_DOWN ? "n up" : " down");
/* enslave is successful */
return 0;
/* Undo stages on error */
err_dest_symlinks:
bond_destroy_slave_symlinks(bond_dev, slave_dev);
err_close:
dev_close(slave_dev);
err_unset_master:
netdev_set_bond_master(slave_dev, NULL);
err_restore_mac:
if (!bond->params.fail_over_mac) {
/* XXX TODO - fom follow mode needs to change master's
* MAC if this slave's MAC is in use by the bond, or at
* least print a warning.
*/
memcpy(addr.sa_data, new_slave->perm_hwaddr, ETH_ALEN);
addr.sa_family = slave_dev->type;
dev_set_mac_address(slave_dev, &addr);
}
err_restore_mtu:
dev_set_mtu(slave_dev, new_slave->original_mtu);
err_free:
kfree(new_slave);
err_undo_flags:
bond_compute_features(bond);
return res;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
const struct net_device_ops *slave_ops = slave_dev->netdev_ops;
struct slave *new_slave = NULL;
struct netdev_hw_addr *ha;
struct sockaddr addr;
int link_reporting;
int res = 0;
if (!bond->params.use_carrier && slave_dev->ethtool_ops == NULL &&
slave_ops->ndo_do_ioctl == NULL) {
pr_warning("%s: Warning: no link monitoring support for %s\n",
bond_dev->name, slave_dev->name);
}
/* already enslaved */
if (slave_dev->flags & IFF_SLAVE) {
pr_debug("Error, Device was already enslaved\n");
return -EBUSY;
}
/* vlan challenged mutual exclusion */
/* no need to lock since we're protected by rtnl_lock */
if (slave_dev->features & NETIF_F_VLAN_CHALLENGED) {
pr_debug("%s: NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
if (bond_vlan_used(bond)) {
pr_err("%s: Error: cannot enslave VLAN challenged slave %s on VLAN enabled bond %s\n",
bond_dev->name, slave_dev->name, bond_dev->name);
return -EPERM;
} else {
pr_warning("%s: Warning: enslaved VLAN challenged slave %s. Adding VLANs will be blocked as long as %s is part of bond %s\n",
bond_dev->name, slave_dev->name,
slave_dev->name, bond_dev->name);
}
} else {
pr_debug("%s: ! NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
}
/*
* Old ifenslave binaries are no longer supported. These can
* be identified with moderate accuracy by the state of the slave:
* the current ifenslave will set the interface down prior to
* enslaving it; the old ifenslave will not.
*/
if ((slave_dev->flags & IFF_UP)) {
pr_err("%s is up. This may be due to an out of date ifenslave.\n",
slave_dev->name);
res = -EPERM;
goto err_undo_flags;
}
/* set bonding device ether type by slave - bonding netdevices are
* created with ether_setup, so when the slave type is not ARPHRD_ETHER
* there is a need to override some of the type dependent attribs/funcs.
*
* bond ether type mutual exclusion - don't allow slaves of dissimilar
* ether type (eg ARPHRD_ETHER and ARPHRD_INFINIBAND) share the same bond
*/
if (bond->slave_cnt == 0) {
if (bond_dev->type != slave_dev->type) {
pr_debug("%s: change device type from %d to %d\n",
bond_dev->name,
bond_dev->type, slave_dev->type);
res = netdev_bonding_change(bond_dev,
NETDEV_PRE_TYPE_CHANGE);
res = notifier_to_errno(res);
if (res) {
pr_err("%s: refused to change device type\n",
bond_dev->name);
res = -EBUSY;
goto err_undo_flags;
}
/* Flush unicast and multicast addresses */
dev_uc_flush(bond_dev);
dev_mc_flush(bond_dev);
if (slave_dev->type != ARPHRD_ETHER)
bond_setup_by_slave(bond_dev, slave_dev);
else {
ether_setup(bond_dev);
bond_dev->priv_flags &= ~IFF_TX_SKB_SHARING;
}
netdev_bonding_change(bond_dev,
NETDEV_POST_TYPE_CHANGE);
}
} else if (bond_dev->type != slave_dev->type) {
pr_err("%s ether type (%d) is different from other slaves (%d), can not enslave it.\n",
slave_dev->name,
slave_dev->type, bond_dev->type);
res = -EINVAL;
goto err_undo_flags;
}
if (slave_ops->ndo_set_mac_address == NULL) {
if (bond->slave_cnt == 0) {
pr_warning("%s: Warning: The first slave device specified does not support setting the MAC address. Setting fail_over_mac to active.",
bond_dev->name);
bond->params.fail_over_mac = BOND_FOM_ACTIVE;
} else if (bond->params.fail_over_mac != BOND_FOM_ACTIVE) {
pr_err("%s: Error: The slave device specified does not support setting the MAC address, but fail_over_mac is not set to active.\n",
bond_dev->name);
res = -EOPNOTSUPP;
goto err_undo_flags;
}
}
call_netdevice_notifiers(NETDEV_JOIN, slave_dev);
/* If this is the first slave, then we need to set the master's hardware
* address to be the same as the slave's. */
if (is_zero_ether_addr(bond->dev->dev_addr))
memcpy(bond->dev->dev_addr, slave_dev->dev_addr,
slave_dev->addr_len);
new_slave = kzalloc(sizeof(struct slave), GFP_KERNEL);
if (!new_slave) {
res = -ENOMEM;
goto err_undo_flags;
}
/*
* Set the new_slave's queue_id to be zero. Queue ID mapping
* is set via sysfs or module option if desired.
*/
new_slave->queue_id = 0;
/* Save slave's original mtu and then set it to match the bond */
new_slave->original_mtu = slave_dev->mtu;
res = dev_set_mtu(slave_dev, bond->dev->mtu);
if (res) {
pr_debug("Error %d calling dev_set_mtu\n", res);
goto err_free;
}
/*
* Save slave's original ("permanent") mac address for modes
* that need it, and for restoring it upon release, and then
* set it to the master's address
*/
memcpy(new_slave->perm_hwaddr, slave_dev->dev_addr, ETH_ALEN);
if (!bond->params.fail_over_mac) {
/*
* Set slave to master's mac address. The application already
* set the master's mac address to that of the first slave
*/
memcpy(addr.sa_data, bond_dev->dev_addr, bond_dev->addr_len);
addr.sa_family = slave_dev->type;
res = dev_set_mac_address(slave_dev, &addr);
if (res) {
pr_debug("Error %d calling set_mac_address\n", res);
goto err_restore_mtu;
}
}
res = netdev_set_bond_master(slave_dev, bond_dev);
if (res) {
pr_debug("Error %d calling netdev_set_bond_master\n", res);
goto err_restore_mac;
}
/* open the slave since the application closed it */
res = dev_open(slave_dev);
if (res) {
pr_debug("Opening slave %s failed\n", slave_dev->name);
goto err_unset_master;
}
new_slave->bond = bond;
new_slave->dev = slave_dev;
slave_dev->priv_flags |= IFF_BONDING;
if (bond_is_lb(bond)) {
/* bond_alb_init_slave() must be called before all other stages since
* it might fail and we do not want to have to undo everything
*/
res = bond_alb_init_slave(bond, new_slave);
if (res)
goto err_close;
}
/* If the mode USES_PRIMARY, then the new slave gets the
* master's promisc (and mc) settings only if it becomes the
* curr_active_slave, and that is taken care of later when calling
* bond_change_active()
*/
if (!USES_PRIMARY(bond->params.mode)) {
/* set promiscuity level to new slave */
if (bond_dev->flags & IFF_PROMISC) {
res = dev_set_promiscuity(slave_dev, 1);
if (res)
goto err_close;
}
/* set allmulti level to new slave */
if (bond_dev->flags & IFF_ALLMULTI) {
res = dev_set_allmulti(slave_dev, 1);
if (res)
goto err_close;
}
netif_addr_lock_bh(bond_dev);
/* upload master's mc_list to new slave */
netdev_for_each_mc_addr(ha, bond_dev)
dev_mc_add(slave_dev, ha->addr);
netif_addr_unlock_bh(bond_dev);
}
if (bond->params.mode == BOND_MODE_8023AD) {
/* add lacpdu mc addr to mc list */
u8 lacpdu_multicast[ETH_ALEN] = MULTICAST_LACPDU_ADDR;
dev_mc_add(slave_dev, lacpdu_multicast);
}
bond_add_vlans_on_slave(bond, slave_dev);
write_lock_bh(&bond->lock);
bond_attach_slave(bond, new_slave);
new_slave->delay = 0;
new_slave->link_failure_count = 0;
write_unlock_bh(&bond->lock);
bond_compute_features(bond);
read_lock(&bond->lock);
new_slave->last_arp_rx = jiffies;
if (bond->params.miimon && !bond->params.use_carrier) {
link_reporting = bond_check_dev_link(bond, slave_dev, 1);
if ((link_reporting == -1) && !bond->params.arp_interval) {
/*
* miimon is set but a bonded network driver
* does not support ETHTOOL/MII and
* arp_interval is not set. Note: if
* use_carrier is enabled, we will never go
* here (because netif_carrier is always
* supported); thus, we don't need to change
* the messages for netif_carrier.
*/
pr_warning("%s: Warning: MII and ETHTOOL support not available for interface %s, and arp_interval/arp_ip_target module parameters not specified, thus bonding will not detect link failures! see bonding.txt for details.\n",
bond_dev->name, slave_dev->name);
} else if (link_reporting == -1) {
/* unable get link status using mii/ethtool */
pr_warning("%s: Warning: can't get link status from interface %s; the network driver associated with this interface does not support MII or ETHTOOL link status reporting, thus miimon has no effect on this interface.\n",
bond_dev->name, slave_dev->name);
}
}
/* check for initial state */
if (!bond->params.miimon ||
(bond_check_dev_link(bond, slave_dev, 0) == BMSR_LSTATUS)) {
if (bond->params.updelay) {
pr_debug("Initial state of slave_dev is BOND_LINK_BACK\n");
new_slave->link = BOND_LINK_BACK;
new_slave->delay = bond->params.updelay;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_UP\n");
new_slave->link = BOND_LINK_UP;
}
new_slave->jiffies = jiffies;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_DOWN\n");
new_slave->link = BOND_LINK_DOWN;
}
if (bond_update_speed_duplex(new_slave) &&
(new_slave->link != BOND_LINK_DOWN)) {
pr_warning("%s: Warning: failed to get speed and duplex from %s, assumed to be 100Mb/sec and Full.\n",
bond_dev->name, new_slave->dev->name);
if (bond->params.mode == BOND_MODE_8023AD) {
pr_warning("%s: Warning: Operation of 802.3ad mode requires ETHTOOL support in base driver for proper aggregator selection.\n",
bond_dev->name);
}
}
if (USES_PRIMARY(bond->params.mode) && bond->params.primary[0]) {
/* if there is a primary slave, remember it */
if (strcmp(bond->params.primary, new_slave->dev->name) == 0) {
bond->primary_slave = new_slave;
bond->force_primary = true;
}
}
write_lock_bh(&bond->curr_slave_lock);
switch (bond->params.mode) {
case BOND_MODE_ACTIVEBACKUP:
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
case BOND_MODE_8023AD:
/* in 802.3ad mode, the internal mechanism
* will activate the slaves in the selected
* aggregator
*/
bond_set_slave_inactive_flags(new_slave);
/* if this is the first slave */
if (bond->slave_cnt == 1) {
SLAVE_AD_INFO(new_slave).id = 1;
/* Initialize AD with the number of times that the AD timer is called in 1 second
* can be called only after the mac address of the bond is set
*/
bond_3ad_initialize(bond, 1000/AD_TIMER_INTERVAL);
} else {
SLAVE_AD_INFO(new_slave).id =
SLAVE_AD_INFO(new_slave->prev).id + 1;
}
bond_3ad_bind_slave(new_slave);
break;
case BOND_MODE_TLB:
case BOND_MODE_ALB:
bond_set_active_slave(new_slave);
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
default:
pr_debug("This slave is always active in trunk mode\n");
/* always active in trunk mode */
bond_set_active_slave(new_slave);
/* In trunking mode there is little meaning to curr_active_slave
* anyway (it holds no special properties of the bond device),
* so we can change it without calling change_active_interface()
*/
if (!bond->curr_active_slave)
bond->curr_active_slave = new_slave;
break;
} /* switch(bond_mode) */
write_unlock_bh(&bond->curr_slave_lock);
bond_set_carrier(bond);
#ifdef CONFIG_NET_POLL_CONTROLLER
slave_dev->npinfo = bond_netpoll_info(bond);
if (slave_dev->npinfo) {
if (slave_enable_netpoll(new_slave)) {
read_unlock(&bond->lock);
pr_info("Error, %s: master_dev is using netpoll, "
"but new slave device does not support netpoll.\n",
bond_dev->name);
res = -EBUSY;
goto err_close;
}
}
#endif
read_unlock(&bond->lock);
res = bond_create_slave_symlinks(bond_dev, slave_dev);
if (res)
goto err_close;
res = netdev_rx_handler_register(slave_dev, bond_handle_frame,
new_slave);
if (res) {
pr_debug("Error %d calling netdev_rx_handler_register\n", res);
goto err_dest_symlinks;
}
pr_info("%s: enslaving %s as a%s interface with a%s link.\n",
bond_dev->name, slave_dev->name,
bond_is_active_slave(new_slave) ? "n active" : " backup",
new_slave->link != BOND_LINK_DOWN ? "n up" : " down");
/* enslave is successful */
return 0;
/* Undo stages on error */
err_dest_symlinks:
bond_destroy_slave_symlinks(bond_dev, slave_dev);
err_close:
dev_close(slave_dev);
err_unset_master:
netdev_set_bond_master(slave_dev, NULL);
err_restore_mac:
if (!bond->params.fail_over_mac) {
/* XXX TODO - fom follow mode needs to change master's
* MAC if this slave's MAC is in use by the bond, or at
* least print a warning.
*/
memcpy(addr.sa_data, new_slave->perm_hwaddr, ETH_ALEN);
addr.sa_family = slave_dev->type;
dev_set_mac_address(slave_dev, &addr);
}
err_restore_mtu:
dev_set_mtu(slave_dev, new_slave->original_mtu);
err_free:
kfree(new_slave);
err_undo_flags:
bond_compute_features(bond);
return res;
}
| 165,726 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
/* prevent an integer overflow issue */
l_current_pi->include = 00;
if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))
{
l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));
}
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
}
Commit Message: Cast to size_t before multiplication
Need to cast to size_t before multiplication otherwise overflow check is useless.
CWE ID: CWE-125 | opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
/* prevent an integer overflow issue */
l_current_pi->include = 00;
if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))
{
l_current_pi->include = (OPJ_INT16*) opj_calloc((size_t)(l_tcp->numlayers + 1U) * l_step_l, sizeof(OPJ_INT16));
}
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
}
| 169,941 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostImpl::Destroy(bool also_delete) {
DCHECK(!destroyed_);
destroyed_ = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, Source<RenderWidgetHost>(this),
NotificationService::NoDetails());
if (view_) {
view_->Destroy();
view_.reset();
}
process_->RemoveRoute(routing_id_);
g_routing_id_widget_map.Get().erase(
RenderWidgetHostID(process_->GetID(), routing_id_));
if (delegate_)
delegate_->RenderWidgetDeleted(this);
if (also_delete)
delete this;
}
Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI
BUG=590284
Review URL: https://codereview.chromium.org/1747183002
Cr-Commit-Position: refs/heads/master@{#378844}
CWE ID: | void RenderWidgetHostImpl::Destroy(bool also_delete) {
DCHECK(!destroyed_);
destroyed_ = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, Source<RenderWidgetHost>(this),
NotificationService::NoDetails());
if (view_) {
view_->Destroy();
view_.reset();
}
process_->RemoveRoute(routing_id_);
g_routing_id_widget_map.Get().erase(
RenderWidgetHostID(process_->GetID(), routing_id_));
if (delegate_)
delegate_->RenderWidgetDeleted(this);
if (also_delete) {
CHECK(!owner_delegate_);
delete this;
}
}
| 172,116 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long cs;
int cpl = ctxt->ops->cpl(ctxt);
rc = emulate_pop(ctxt, &ctxt->_eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->op_bytes == 4)
ctxt->_eip = (u32)ctxt->_eip;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS);
return rc;
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
u16 old_cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_cs, &old_desc, NULL,
VCPU_SREG_CS);
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, 0, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, new_desc.l);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64);
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
}
return rc;
}
| 166,340 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rename_in_ns(int pid, char *oldname, char **newnamep)
{
int fd = -1, ofd = -1, ret, ifindex = -1;
bool grab_newname = false;
ofd = lxc_preserve_ns(getpid(), "net");
if (ofd < 0) {
fprintf(stderr, "Failed opening network namespace path for '%d'.", getpid());
return -1;
}
fd = lxc_preserve_ns(pid, "net");
if (fd < 0) {
fprintf(stderr, "Failed opening network namespace path for '%d'.", pid);
return -1;
}
if (setns(fd, 0) < 0) {
fprintf(stderr, "setns to container network namespace\n");
goto out_err;
}
close(fd); fd = -1;
if (!*newnamep) {
grab_newname = true;
*newnamep = VETH_DEF_NAME;
if (!(ifindex = if_nametoindex(oldname))) {
fprintf(stderr, "failed to get netdev index\n");
goto out_err;
}
}
if ((ret = lxc_netdev_rename_by_name(oldname, *newnamep)) < 0) {
fprintf(stderr, "Error %d renaming netdev %s to %s in container\n", ret, oldname, *newnamep);
goto out_err;
}
if (grab_newname) {
char ifname[IFNAMSIZ], *namep = ifname;
if (!if_indextoname(ifindex, namep)) {
fprintf(stderr, "Failed to get new netdev name\n");
goto out_err;
}
*newnamep = strdup(namep);
if (!*newnamep)
goto out_err;
}
if (setns(ofd, 0) < 0) {
fprintf(stderr, "Error returning to original netns\n");
close(ofd);
return -1;
}
close(ofd);
return 0;
out_err:
if (ofd >= 0)
close(ofd);
if (setns(ofd, 0) < 0)
fprintf(stderr, "Error returning to original network namespace\n");
if (fd >= 0)
close(fd);
return -1;
}
Commit Message: CVE-2017-5985: Ensure target netns is caller-owned
Before this commit, lxc-user-nic could potentially have been tricked into
operating on a network namespace over which the caller did not hold privilege.
This commit ensures that the caller is privileged over the network namespace by
temporarily dropping privilege.
Launchpad: https://bugs.launchpad.net/ubuntu/+source/lxc/+bug/1654676
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Christian Brauner <[email protected]>
CWE ID: CWE-862 | static int rename_in_ns(int pid, char *oldname, char **newnamep)
{
uid_t ruid, suid, euid;
int fret = -1;
int fd = -1, ifindex = -1, ofd = -1, ret;
bool grab_newname = false;
ofd = lxc_preserve_ns(getpid(), "net");
if (ofd < 0) {
usernic_error("Failed opening network namespace path for '%d'.", getpid());
return fret;
}
fd = lxc_preserve_ns(pid, "net");
if (fd < 0) {
usernic_error("Failed opening network namespace path for '%d'.", pid);
goto do_partial_cleanup;
}
ret = getresuid(&ruid, &euid, &suid);
if (ret < 0) {
usernic_error("Failed to retrieve real, effective, and saved "
"user IDs: %s\n",
strerror(errno));
goto do_partial_cleanup;
}
ret = setns(fd, CLONE_NEWNET);
close(fd);
fd = -1;
if (ret < 0) {
usernic_error("Failed to setns() to the network namespace of "
"the container with PID %d: %s.\n",
pid, strerror(errno));
goto do_partial_cleanup;
}
ret = setresuid(ruid, ruid, 0);
if (ret < 0) {
usernic_error("Failed to drop privilege by setting effective "
"user id and real user id to %d, and saved user "
"ID to 0: %s.\n",
ruid, strerror(errno));
// COMMENT(brauner): It's ok to jump to do_full_cleanup here
// since setresuid() will succeed when trying to set real,
// effective, and saved to values they currently have.
goto do_full_cleanup;
}
if (!*newnamep) {
grab_newname = true;
*newnamep = VETH_DEF_NAME;
ifindex = if_nametoindex(oldname);
if (!ifindex) {
usernic_error("Failed to get netdev index: %s.\n", strerror(errno));
goto do_full_cleanup;
}
}
ret = lxc_netdev_rename_by_name(oldname, *newnamep);
if (ret < 0) {
usernic_error("Error %d renaming netdev %s to %s in container.\n", ret, oldname, *newnamep);
goto do_full_cleanup;
}
if (grab_newname) {
char ifname[IFNAMSIZ];
char *namep = ifname;
if (!if_indextoname(ifindex, namep)) {
usernic_error("Failed to get new netdev name: %s.\n", strerror(errno));
goto do_full_cleanup;
}
*newnamep = strdup(namep);
if (!*newnamep)
goto do_full_cleanup;
}
fret = 0;
do_full_cleanup:
ret = setresuid(ruid, euid, suid);
if (ret < 0) {
usernic_error("Failed to restore privilege by setting effective "
"user id to %d, real user id to %d, and saved user "
"ID to %d: %s.\n",
ruid, euid, suid, strerror(errno));
fret = -1;
// COMMENT(brauner): setns() should fail if setresuid() doesn't
// succeed but there's no harm in falling through; keeps the
// code cleaner.
}
ret = setns(ofd, CLONE_NEWNET);
if (ret < 0) {
usernic_error("Failed to setns() to original network namespace "
"of PID %d: %s.\n",
ofd, strerror(errno));
fret = -1;
}
do_partial_cleanup:
if (fd >= 0)
close(fd);
close(ofd);
return fret;
}
| 168,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool check_underflow(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->ip))
return false;
t = ipt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | static bool check_underflow(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(e))
return false;
t = ipt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
| 167,368 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cib_notify_client(gpointer key, gpointer value, gpointer user_data)
{
const char *type = NULL;
gboolean do_send = FALSE;
cib_client_t *client = value;
xmlNode *update_msg = user_data;
CRM_CHECK(client != NULL, return TRUE);
CRM_CHECK(update_msg != NULL, return TRUE);
if (client->ipc == NULL) {
crm_warn("Skipping client with NULL channel");
return FALSE;
}
type = crm_element_value(update_msg, F_SUBTYPE);
CRM_LOG_ASSERT(type != NULL);
if (client->diffs && safe_str_eq(type, T_CIB_DIFF_NOTIFY)) {
do_send = TRUE;
} else if (client->replace && safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) {
do_send = TRUE;
} else if (client->confirmations && safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) {
do_send = TRUE;
} else if (client->pre_notify && safe_str_eq(type, T_CIB_PRE_NOTIFY)) {
do_send = TRUE;
} else if (client->post_notify && safe_str_eq(type, T_CIB_POST_NOTIFY)) {
do_send = TRUE;
}
if (do_send) {
if (client->ipc) {
if(crm_ipcs_send(client->ipc, 0, update_msg, TRUE) == FALSE) {
crm_warn("Notification of client %s/%s failed", client->name, client->id);
}
#ifdef HAVE_GNUTLS_GNUTLS_H
} else if (client->session) {
crm_debug("Sent %s notification to client %s/%s", type, client->name, client->id);
crm_send_remote_msg(client->session, update_msg, client->encrypted);
#endif
} else {
crm_err("Unknown transport for %s", client->name);
}
}
return FALSE;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_notify_client(gpointer key, gpointer value, gpointer user_data)
{
const char *type = NULL;
gboolean do_send = FALSE;
cib_client_t *client = value;
xmlNode *update_msg = user_data;
CRM_CHECK(client != NULL, return TRUE);
CRM_CHECK(update_msg != NULL, return TRUE);
if (client->ipc == NULL && client->session == NULL) {
crm_warn("Skipping client with NULL channel");
return FALSE;
}
type = crm_element_value(update_msg, F_SUBTYPE);
CRM_LOG_ASSERT(type != NULL);
if (client->diffs && safe_str_eq(type, T_CIB_DIFF_NOTIFY)) {
do_send = TRUE;
} else if (client->replace && safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) {
do_send = TRUE;
} else if (client->confirmations && safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) {
do_send = TRUE;
} else if (client->pre_notify && safe_str_eq(type, T_CIB_PRE_NOTIFY)) {
do_send = TRUE;
} else if (client->post_notify && safe_str_eq(type, T_CIB_POST_NOTIFY)) {
do_send = TRUE;
}
if (do_send) {
if (client->ipc) {
if(crm_ipcs_send(client->ipc, 0, update_msg, TRUE) == FALSE) {
crm_warn("Notification of client %s/%s failed", client->name, client->id);
}
#ifdef HAVE_GNUTLS_GNUTLS_H
} else if (client->session) {
crm_debug("Sent %s notification to client %s/%s", type, client->name, client->id);
crm_send_remote_msg(client->session, update_msg, client->encrypted);
#endif
} else {
crm_err("Unknown transport for %s", client->name);
}
}
return FALSE;
}
| 166,146 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
BT_DBG("sock %p, sk %p", sock, sk);
sa->rc_family = AF_BLUETOOTH;
sa->rc_channel = rfcomm_pi(sk)->channel;
if (peer)
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->dst);
else
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->src);
*len = sizeof(struct sockaddr_rc);
return 0;
}
Commit Message: Bluetooth: RFCOMM - Fix info leak via getsockname()
The RFCOMM code fails to initialize the trailing padding byte of struct
sockaddr_rc added for alignment. It that for leaks one byte kernel stack
via the getsockname() syscall. Add an explicit memset(0) before filling
the structure to avoid the info leak.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Marcel Holtmann <[email protected]>
Cc: Gustavo Padovan <[email protected]>
Cc: Johan Hedberg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
BT_DBG("sock %p, sk %p", sock, sk);
memset(sa, 0, sizeof(*sa));
sa->rc_family = AF_BLUETOOTH;
sa->rc_channel = rfcomm_pi(sk)->channel;
if (peer)
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->dst);
else
bacpy(&sa->rc_bdaddr, &bt_sk(sk)->src);
*len = sizeof(struct sockaddr_rc);
return 0;
}
| 166,181 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetImePropertyActivated(const char* key, bool activated) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImePropertyActivated: IBus connection is not alive";
return;
}
if (!key || (key[0] == '\0')) {
return;
}
if (input_context_path_.empty()) {
LOG(ERROR) << "Input context is unknown";
return;
}
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_property_activate(
context, key, (activated ? PROP_STATE_CHECKED : PROP_STATE_UNCHECKED));
g_object_unref(context);
}
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 | void SetImePropertyActivated(const char* key, bool activated) {
// IBusController override.
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImePropertyActivated: IBus connection is not alive";
return;
}
if (key.empty()) {
return;
}
if (input_context_path_.empty()) {
LOG(ERROR) << "Input context is unknown";
return;
}
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_property_activate(
context, key.c_str(),
(activated ? PROP_STATE_CHECKED : PROP_STATE_UNCHECKED));
g_object_unref(context);
}
| 170,548 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190 | static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
| 168,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
{
RenderStyle* oldStyle = style();
s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle.position()
&& containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
markAllDescendantsWithFloatsForLayout();
RenderBlock::styleWillChange(diff, newStyle);
}
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
[email protected], [email protected], [email protected]
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
{
RenderStyle* oldStyle = style();
s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
if (oldStyle && parent() && diff.needsFullLayout() && oldStyle->position() != newStyle.position()
&& containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
markAllDescendantsWithFloatsForLayout();
RenderBlock::styleWillChange(diff, newStyle);
}
| 171,463 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: FakePlatformSensor::FakePlatformSensor(mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
PlatformSensorProvider* provider)
: PlatformSensor(type, std::move(mapping), provider) {
ON_CALL(*this, StartSensor(_))
.WillByDefault(
Invoke([this](const PlatformSensorConfiguration& configuration) {
SensorReading reading;
if (GetType() == mojom::SensorType::AMBIENT_LIGHT) {
reading.als.value = configuration.frequency();
UpdateSharedBufferAndNotifyClients(reading);
}
return true;
}));
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | FakePlatformSensor::FakePlatformSensor(mojom::SensorType type,
FakePlatformSensor::FakePlatformSensor(
mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
PlatformSensorProvider* provider)
: PlatformSensor(type, reading_buffer, provider) {
ON_CALL(*this, StartSensor(_))
.WillByDefault(
Invoke([this](const PlatformSensorConfiguration& configuration) {
SensorReading reading;
if (GetType() == mojom::SensorType::AMBIENT_LIGHT) {
reading.als.value = configuration.frequency();
UpdateSharedBufferAndNotifyClients(reading);
}
return true;
}));
}
| 172,819 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION( locale_get_script )
PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,182 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
assert((cc0%rowsize)==0);
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
if((cc0%rowsize)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile",
"%s", "(cc0%rowsize)!=0");
return 0;
}
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
| 166,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
{
for (unsigned i = 0; i < nSamples; ++i) {
for (unsigned c = 0; c < nChannels; ++c) {
*dst++ = src[c][i] << 8;
}
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
static void copyMultiCh8(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels)
{
for (unsigned i = 0; i < nSamples; ++i) {
for (unsigned c = 0; c < nChannels; ++c) {
*dst++ = src[c][i] << 8;
}
}
}
| 174,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
{
struct request *rq = tags->rqs[tag];
/* mq_ctx of flush rq is always cloned from the corresponding req */
struct blk_flush_queue *fq = blk_get_flush_queue(rq->q, rq->mq_ctx);
if (!is_flush_request(rq, fq, tag))
return rq;
return fq->flush_rq;
}
Commit Message: blk-mq: fix race between timeout and freeing request
Inside timeout handler, blk_mq_tag_to_rq() is called
to retrieve the request from one tag. This way is obviously
wrong because the request can be freed any time and some
fiedds of the request can't be trusted, then kernel oops
might be triggered[1].
Currently wrt. blk_mq_tag_to_rq(), the only special case is
that the flush request can share same tag with the request
cloned from, and the two requests can't be active at the same
time, so this patch fixes the above issue by updating tags->rqs[tag]
with the active request(either flush rq or the request cloned
from) of the tag.
Also blk_mq_tag_to_rq() gets much simplified with this patch.
Given blk_mq_tag_to_rq() is mainly for drivers and the caller must
make sure the request can't be freed, so in bt_for_each() this
helper is replaced with tags->rqs[tag].
[1] kernel oops log
[ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M
[ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M
[ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M
[ 439.700653] Dumping ftrace buffer:^M
[ 439.700653] (ftrace buffer empty)^M
[ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M
[ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M
[ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M
[ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M
[ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M
[ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M
[ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M
[ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M
[ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M
[ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M
[ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M
[ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M
[ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M
[ 439.730500] Stack:^M
[ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M
[ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M
[ 439.755663] Call Trace:^M
[ 439.755663] <IRQ> ^M
[ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M
[ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M
[ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M
[ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M
[ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M
[ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M
[ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M
[ 439.755663] <EOI> ^M
[ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M
[ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M
[ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M
[ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M
[ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M
[ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M
[ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M
[ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M
[ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M
[ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M
[ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M
[ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M
[ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89
f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b
53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10
^M
[ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.790911] RSP <ffff880819203da0>^M
[ 439.790911] CR2: 0000000000000158^M
[ 439.790911] ---[ end trace d40af58949325661 ]---^M
Cc: <[email protected]>
Signed-off-by: Ming Lei <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-362 | struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
{
return tags->rqs[tag];
}
| 169,457 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static u32 apic_get_tmcct(struct kvm_lapic *apic)
{
ktime_t remaining;
s64 ns;
u32 tmcct;
ASSERT(apic != NULL);
/* if initial count is 0, current count should also be 0 */
if (kvm_apic_get_reg(apic, APIC_TMICT) == 0)
return 0;
remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
if (ktime_to_ns(remaining) < 0)
remaining = ktime_set(0, 0);
ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
tmcct = div64_u64(ns,
(APIC_BUS_CYCLE_NS * apic->divide_count));
return tmcct;
}
Commit Message: KVM: x86: Fix potential divide by 0 in lapic (CVE-2013-6367)
Under guest controllable circumstances apic_get_tmcct will execute a
divide by zero and cause a crash. If the guest cpuid support
tsc deadline timers and performs the following sequence of requests
the host will crash.
- Set the mode to periodic
- Set the TMICT to 0
- Set the mode bits to 11 (neither periodic, nor one shot, nor tsc deadline)
- Set the TMICT to non-zero.
Then the lapic_timer.period will be 0, but the TMICT will not be. If the
guest then reads from the TMCCT then the host will perform a divide by 0.
This patch ensures that if the lapic_timer.period is 0, then the division
does not occur.
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-189 | static u32 apic_get_tmcct(struct kvm_lapic *apic)
{
ktime_t remaining;
s64 ns;
u32 tmcct;
ASSERT(apic != NULL);
/* if initial count is 0, current count should also be 0 */
if (kvm_apic_get_reg(apic, APIC_TMICT) == 0 ||
apic->lapic_timer.period == 0)
return 0;
remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
if (ktime_to_ns(remaining) < 0)
remaining = ktime_set(0, 0);
ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
tmcct = div64_u64(ns,
(APIC_BUS_CYCLE_NS * apic->divide_count));
return tmcct;
}
| 165,951 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: zsethalftone5(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
uint count;
gs_halftone_component *phtc = 0;
gs_halftone_component *pc;
int code = 0;
int j;
bool have_default;
gs_halftone *pht = 0;
gx_device_halftone *pdht = 0;
ref sprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
ref tprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
gs_memory_t *mem;
uint edepth = ref_stack_count(&e_stack);
int npop = 2;
int dict_enum = dict_first(op);
ref rvalue[2];
int cname, colorant_number;
byte * pname;
uint name_size;
int halftonetype, type = 0;
gs_gstate *pgs = igs;
int space_index = r_space_index(op - 1);
mem = (gs_memory_t *) idmemory->spaces_indexed[space_index];
* the device color space, so we need to mark them
* with a different internal halftone type.
*/
code = dict_int_param(op - 1, "HalftoneType", 1, 100, 0, &type);
if (code < 0)
return code;
halftonetype = (type == 2 || type == 4)
? ht_type_multiple_colorscreen
: ht_type_multiple;
/* Count how many components that we will actually use. */
have_default = false;
for (count = 0; ;) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
else if (colorant_number == GX_DEVICE_COLOR_MAX_COMPONENTS) {
/* If here then we have the "Default" component */
if (have_default)
return_error(gs_error_rangecheck);
have_default = true;
}
count++;
/*
* Check to see if we have already reached the legal number of
* components.
*/
if (count > GS_CLIENT_COLOR_MAX_COMPONENTS + 1) {
code = gs_note_error(gs_error_rangecheck);
break;
}
}
if (count == 0 || (halftonetype == ht_type_multiple && ! have_default))
code = gs_note_error(gs_error_rangecheck);
if (code >= 0) {
check_estack(5); /* for sampling Type 1 screens */
refset_null(sprocs, count);
refset_null(tprocs, count);
rc_alloc_struct_0(pht, gs_halftone, &st_halftone,
imemory, pht = 0, ".sethalftone5");
phtc = gs_alloc_struct_array(mem, count, gs_halftone_component,
&st_ht_component_element,
".sethalftone5");
rc_alloc_struct_0(pdht, gx_device_halftone, &st_device_halftone,
imemory, pdht = 0, ".sethalftone5");
if (pht == 0 || phtc == 0 || pdht == 0) {
j = 0; /* Quiet the compiler:
gs_note_error isn't necessarily identity,
so j could be left ununitialized. */
code = gs_note_error(gs_error_VMerror);
}
}
if (code >= 0) {
dict_enum = dict_first(op);
for (j = 0, pc = phtc; ;) {
int type;
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue; /* Do not use this component */
pc->cname = cname;
pc->comp_number = colorant_number;
/* Now process the component dictionary */
check_dict_read(rvalue[1]);
if (dict_int_param(&rvalue[1], "HalftoneType", 1, 7, 0, &type) < 0) {
code = gs_note_error(gs_error_typecheck);
break;
}
switch (type) {
default:
code = gs_note_error(gs_error_rangecheck);
break;
case 1:
code = dict_spot_params(&rvalue[1], &pc->params.spot,
sprocs + j, tprocs + j, mem);
pc->params.spot.screen.spot_function = spot1_dummy;
pc->type = ht_type_spot;
break;
case 3:
code = dict_threshold_params(&rvalue[1], &pc->params.threshold,
tprocs + j);
pc->type = ht_type_threshold;
break;
case 7:
code = dict_threshold2_params(&rvalue[1], &pc->params.threshold2,
tprocs + j, imemory);
pc->type = ht_type_threshold2;
break;
}
if (code < 0)
break;
pc++;
j++;
}
}
if (code >= 0) {
pht->type = halftonetype;
pht->params.multiple.components = phtc;
pht->params.multiple.num_comp = j;
pht->params.multiple.get_colorname_string = gs_get_colorname_string;
code = gs_sethalftone_prepare(igs, pht, pdht);
}
if (code >= 0) {
/*
* Put the actual frequency and angle in the spot function component dictionaries.
*/
dict_enum = dict_first(op);
for (pc = phtc; ; ) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/* Verify that we have a valid component */
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component and verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
if (pc->type == ht_type_spot) {
code = dict_spot_results(i_ctx_p, &rvalue[1], &pc->params.spot);
if (code < 0)
break;
}
pc++;
}
}
if (code >= 0) {
/*
* Schedule the sampling of any Type 1 screens,
* and any (Type 1 or Type 3) TransferFunctions.
* Save the stack depths in case we have to back out.
*/
uint odepth = ref_stack_count(&o_stack);
ref odict, odict5;
odict = op[-1];
odict5 = *op;
pop(2);
op = osp;
esp += 5;
make_mark_estack(esp - 4, es_other, sethalftone_cleanup);
esp[-3] = odict;
make_istruct(esp - 2, 0, pht);
make_istruct(esp - 1, 0, pdht);
make_op_estack(esp, sethalftone_finish);
for (j = 0; j < count; j++) {
gx_ht_order *porder = NULL;
if (pdht->components == 0)
porder = &pdht->order;
else {
/* Find the component in pdht that matches component j in
the pht; gs_sethalftone_prepare() may permute these. */
int k;
int comp_number = phtc[j].comp_number;
for (k = 0; k < count; k++) {
if (pdht->components[k].comp_number == comp_number) {
porder = &pdht->components[k].corder;
break;
}
}
}
switch (phtc[j].type) {
case ht_type_spot:
code = zscreen_enum_init(i_ctx_p, porder,
&phtc[j].params.spot.screen,
&sprocs[j], 0, 0, space_index);
if (code < 0)
break;
/* falls through */
case ht_type_threshold:
if (!r_has_type(tprocs + j, t__invalid)) {
/* Schedule TransferFunction sampling. */
/****** check_xstack IS WRONG ******/
check_ostack(zcolor_remap_one_ostack);
check_estack(zcolor_remap_one_estack);
code = zcolor_remap_one(i_ctx_p, tprocs + j,
porder->transfer, igs,
zcolor_remap_one_finish);
op = osp;
}
break;
default: /* not possible here, but to keep */
/* the compilers happy.... */
;
}
if (code < 0) { /* Restore the stack. */
ref_stack_pop_to(&o_stack, odepth);
ref_stack_pop_to(&e_stack, edepth);
op = osp;
op[-1] = odict;
*op = odict5;
break;
}
npop = 0;
}
}
if (code < 0) {
gs_free_object(mem, pdht, ".sethalftone5");
gs_free_object(mem, phtc, ".sethalftone5");
gs_free_object(mem, pht, ".sethalftone5");
return code;
}
pop(npop);
return (ref_stack_count(&e_stack) > edepth ? o_push_estack : 0);
}
Commit Message:
CWE ID: CWE-704 | zsethalftone5(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
uint count;
gs_halftone_component *phtc = 0;
gs_halftone_component *pc;
int code = 0;
int j;
bool have_default;
gs_halftone *pht = 0;
gx_device_halftone *pdht = 0;
ref sprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
ref tprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
gs_memory_t *mem;
uint edepth = ref_stack_count(&e_stack);
int npop = 2;
int dict_enum;
ref rvalue[2];
int cname, colorant_number;
byte * pname;
uint name_size;
int halftonetype, type = 0;
gs_gstate *pgs = igs;
int space_index;
if (ref_stack_count(&o_stack) < 2)
return_error(gs_error_stackunderflow);
check_type(*op, t_dictionary);
check_type(*(op - 1), t_dictionary);
dict_enum = dict_first(op);
space_index = r_space_index(op - 1);
mem = (gs_memory_t *) idmemory->spaces_indexed[space_index];
* the device color space, so we need to mark them
* with a different internal halftone type.
*/
code = dict_int_param(op - 1, "HalftoneType", 1, 100, 0, &type);
if (code < 0)
return code;
halftonetype = (type == 2 || type == 4)
? ht_type_multiple_colorscreen
: ht_type_multiple;
/* Count how many components that we will actually use. */
have_default = false;
for (count = 0; ;) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
else if (colorant_number == GX_DEVICE_COLOR_MAX_COMPONENTS) {
/* If here then we have the "Default" component */
if (have_default)
return_error(gs_error_rangecheck);
have_default = true;
}
count++;
/*
* Check to see if we have already reached the legal number of
* components.
*/
if (count > GS_CLIENT_COLOR_MAX_COMPONENTS + 1) {
code = gs_note_error(gs_error_rangecheck);
break;
}
}
if (count == 0 || (halftonetype == ht_type_multiple && ! have_default))
code = gs_note_error(gs_error_rangecheck);
if (code >= 0) {
check_estack(5); /* for sampling Type 1 screens */
refset_null(sprocs, count);
refset_null(tprocs, count);
rc_alloc_struct_0(pht, gs_halftone, &st_halftone,
imemory, pht = 0, ".sethalftone5");
phtc = gs_alloc_struct_array(mem, count, gs_halftone_component,
&st_ht_component_element,
".sethalftone5");
rc_alloc_struct_0(pdht, gx_device_halftone, &st_device_halftone,
imemory, pdht = 0, ".sethalftone5");
if (pht == 0 || phtc == 0 || pdht == 0) {
j = 0; /* Quiet the compiler:
gs_note_error isn't necessarily identity,
so j could be left ununitialized. */
code = gs_note_error(gs_error_VMerror);
}
}
if (code >= 0) {
dict_enum = dict_first(op);
for (j = 0, pc = phtc; ;) {
int type;
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue; /* Do not use this component */
pc->cname = cname;
pc->comp_number = colorant_number;
/* Now process the component dictionary */
check_dict_read(rvalue[1]);
if (dict_int_param(&rvalue[1], "HalftoneType", 1, 7, 0, &type) < 0) {
code = gs_note_error(gs_error_typecheck);
break;
}
switch (type) {
default:
code = gs_note_error(gs_error_rangecheck);
break;
case 1:
code = dict_spot_params(&rvalue[1], &pc->params.spot,
sprocs + j, tprocs + j, mem);
pc->params.spot.screen.spot_function = spot1_dummy;
pc->type = ht_type_spot;
break;
case 3:
code = dict_threshold_params(&rvalue[1], &pc->params.threshold,
tprocs + j);
pc->type = ht_type_threshold;
break;
case 7:
code = dict_threshold2_params(&rvalue[1], &pc->params.threshold2,
tprocs + j, imemory);
pc->type = ht_type_threshold2;
break;
}
if (code < 0)
break;
pc++;
j++;
}
}
if (code >= 0) {
pht->type = halftonetype;
pht->params.multiple.components = phtc;
pht->params.multiple.num_comp = j;
pht->params.multiple.get_colorname_string = gs_get_colorname_string;
code = gs_sethalftone_prepare(igs, pht, pdht);
}
if (code >= 0) {
/*
* Put the actual frequency and angle in the spot function component dictionaries.
*/
dict_enum = dict_first(op);
for (pc = phtc; ; ) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/* Verify that we have a valid component */
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component and verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
if (pc->type == ht_type_spot) {
code = dict_spot_results(i_ctx_p, &rvalue[1], &pc->params.spot);
if (code < 0)
break;
}
pc++;
}
}
if (code >= 0) {
/*
* Schedule the sampling of any Type 1 screens,
* and any (Type 1 or Type 3) TransferFunctions.
* Save the stack depths in case we have to back out.
*/
uint odepth = ref_stack_count(&o_stack);
ref odict, odict5;
odict = op[-1];
odict5 = *op;
pop(2);
op = osp;
esp += 5;
make_mark_estack(esp - 4, es_other, sethalftone_cleanup);
esp[-3] = odict;
make_istruct(esp - 2, 0, pht);
make_istruct(esp - 1, 0, pdht);
make_op_estack(esp, sethalftone_finish);
for (j = 0; j < count; j++) {
gx_ht_order *porder = NULL;
if (pdht->components == 0)
porder = &pdht->order;
else {
/* Find the component in pdht that matches component j in
the pht; gs_sethalftone_prepare() may permute these. */
int k;
int comp_number = phtc[j].comp_number;
for (k = 0; k < count; k++) {
if (pdht->components[k].comp_number == comp_number) {
porder = &pdht->components[k].corder;
break;
}
}
}
switch (phtc[j].type) {
case ht_type_spot:
code = zscreen_enum_init(i_ctx_p, porder,
&phtc[j].params.spot.screen,
&sprocs[j], 0, 0, space_index);
if (code < 0)
break;
/* falls through */
case ht_type_threshold:
if (!r_has_type(tprocs + j, t__invalid)) {
/* Schedule TransferFunction sampling. */
/****** check_xstack IS WRONG ******/
check_ostack(zcolor_remap_one_ostack);
check_estack(zcolor_remap_one_estack);
code = zcolor_remap_one(i_ctx_p, tprocs + j,
porder->transfer, igs,
zcolor_remap_one_finish);
op = osp;
}
break;
default: /* not possible here, but to keep */
/* the compilers happy.... */
;
}
if (code < 0) { /* Restore the stack. */
ref_stack_pop_to(&o_stack, odepth);
ref_stack_pop_to(&e_stack, edepth);
op = osp;
op[-1] = odict;
*op = odict5;
break;
}
npop = 0;
}
}
if (code < 0) {
gs_free_object(mem, pdht, ".sethalftone5");
gs_free_object(mem, phtc, ".sethalftone5");
gs_free_object(mem, pht, ".sethalftone5");
return code;
}
pop(npop);
return (ref_stack_count(&e_stack) > edepth ? o_push_estack : 0);
}
| 165,263 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
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);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
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));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: Added check for bogus num_images value.
CWE ID: CWE-20 | static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
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);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
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));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 170,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DirectoryEntrySync* DirectoryEntrySync::getDirectory(const String& path, const Dictionary& options, ExceptionState& exceptionState)
{
FileSystemFlags flags(options);
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->getDirectory(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return static_cast<DirectoryEntrySync*>(helper->getResult(exceptionState));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | DirectoryEntrySync* DirectoryEntrySync::getDirectory(const String& path, const Dictionary& options, ExceptionState& exceptionState)
{
FileSystemFlags flags(options);
EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create();
m_fileSystem->getDirectory(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return static_cast<DirectoryEntrySync*>(helper->getResult(exceptionState));
}
| 171,417 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_islice(dec_struct_t *ps_dec,
UWORD16 u2_first_mb_in_slice)
{
dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst;
UWORD32 u4_temp;
WORD32 i_temp;
WORD32 ret;
/*--------------------------------------------------------------------*/
/* Read remaining contents of the slice header */
/*--------------------------------------------------------------------*/
/* dec_ref_pic_marking function */
/* G050 */
if(ps_slice->u1_nal_ref_idc != 0)
{
if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read)
ps_dec->u4_bitoffset = ih264d_read_mmco_commands(
ps_dec);
else
ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset;
}
/* G050 */
/* Read slice_qp_delta */
i_temp = ps_pps->u1_pic_init_qp
+ ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if((i_temp < 0) || (i_temp > 51))
return ERROR_INV_RANGE_QP_T;
ps_slice->u1_slice_qp = i_temp;
COPYTHECONTEXT("SH: slice_qp_delta",
ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp);
if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp);
if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED)
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->u1_disable_dblk_filter_idc = u4_temp;
if(u4_temp != 1)
{
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_alpha_c0_offset = i_temp;
COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2",
ps_slice->i1_slice_alpha_c0_offset >> 1);
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_beta_offset = i_temp;
COPYTHECONTEXT("SH: slice_beta_offset_div2",
ps_slice->i1_slice_beta_offset >> 1);
}
else
{
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
}
else
{
ps_slice->u1_disable_dblk_filter_idc = 0;
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
/* Initialization to check if number of motion vector per 2 Mbs */
/* are exceeding the range or not */
ps_dec->u2_mv_2mb[0] = 0;
ps_dec->u2_mv_2mb[1] = 0;
/*set slice header cone to 2 ,to indicate correct header*/
ps_dec->u1_slice_header_done = 2;
if(ps_pps->u1_entropy_coding_mode)
{
SWITCHOFFTRACE; SWITCHONTRACECABAC;
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff;
ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice,
u2_first_mb_in_slice);
if(ret != OK)
return ret;
SWITCHONTRACE; SWITCHOFFTRACECABAC;
}
else
{
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff;
ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice,
u2_first_mb_in_slice);
if(ret != OK)
return ret;
}
return OK;
}
Commit Message: Return error when there are more mmco params than allocated size
Bug: 25818142
Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d
CWE ID: CWE-119 | WORD32 ih264d_parse_islice(dec_struct_t *ps_dec,
UWORD16 u2_first_mb_in_slice)
{
dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst;
UWORD32 u4_temp;
WORD32 i_temp;
WORD32 ret;
/*--------------------------------------------------------------------*/
/* Read remaining contents of the slice header */
/*--------------------------------------------------------------------*/
/* dec_ref_pic_marking function */
/* G050 */
if(ps_slice->u1_nal_ref_idc != 0)
{
if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read)
{
i_temp = ih264d_read_mmco_commands(ps_dec);
if (i_temp < 0)
{
return ERROR_DBP_MANAGER_T;
}
ps_dec->u4_bitoffset = i_temp;
}
else
ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset;
}
/* G050 */
/* Read slice_qp_delta */
i_temp = ps_pps->u1_pic_init_qp
+ ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if((i_temp < 0) || (i_temp > 51))
return ERROR_INV_RANGE_QP_T;
ps_slice->u1_slice_qp = i_temp;
COPYTHECONTEXT("SH: slice_qp_delta",
ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp);
if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp);
if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED)
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->u1_disable_dblk_filter_idc = u4_temp;
if(u4_temp != 1)
{
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_alpha_c0_offset = i_temp;
COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2",
ps_slice->i1_slice_alpha_c0_offset >> 1);
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_beta_offset = i_temp;
COPYTHECONTEXT("SH: slice_beta_offset_div2",
ps_slice->i1_slice_beta_offset >> 1);
}
else
{
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
}
else
{
ps_slice->u1_disable_dblk_filter_idc = 0;
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
/* Initialization to check if number of motion vector per 2 Mbs */
/* are exceeding the range or not */
ps_dec->u2_mv_2mb[0] = 0;
ps_dec->u2_mv_2mb[1] = 0;
/*set slice header cone to 2 ,to indicate correct header*/
ps_dec->u1_slice_header_done = 2;
if(ps_pps->u1_entropy_coding_mode)
{
SWITCHOFFTRACE; SWITCHONTRACECABAC;
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff;
ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice,
u2_first_mb_in_slice);
if(ret != OK)
return ret;
SWITCHONTRACE; SWITCHOFFTRACECABAC;
}
else
{
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff;
}
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff;
ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice,
u2_first_mb_in_slice);
if(ret != OK)
return ret;
}
return OK;
}
| 173,909 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
struct _store_object *obj;
int failure = 0;
if (!EG(objects_store).object_buckets) {
return;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
/* Make sure we hold a reference count during the destructor call
otherwise, when the destructor ends the storage might be freed
when the refcount reaches 0 a second time
*/
if (EG(objects_store).object_buckets[handle].valid) {
if (obj->refcount == 1) {
if (!EG(objects_store).object_buckets[handle].destructor_called) {
EG(objects_store).object_buckets[handle].destructor_called = 1;
if (obj->dtor) {
if (handlers && !obj->handlers) {
obj->handlers = handlers;
}
zend_try {
obj->dtor(obj->object, handle TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
}
/* re-read the object from the object store as the store might have been reallocated in the dtor */
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->refcount == 1) {
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
if (obj->free_storage) {
zend_try {
obj->free_storage(obj->object TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
}
}
}
obj->refcount--;
#if ZEND_DEBUG_OBJECTS
if (obj->refcount == 0) {
fprintf(stderr, "Deallocated object id #%d\n", handle);
} else {
fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
}
#endif
if (failure) {
zend_bailout();
}
}
/* }}} */
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction
CWE ID: CWE-119 | ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
struct _store_object *obj;
int failure = 0;
if (!EG(objects_store).object_buckets) {
return;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
/* Make sure we hold a reference count during the destructor call
otherwise, when the destructor ends the storage might be freed
when the refcount reaches 0 a second time
*/
if (EG(objects_store).object_buckets[handle].valid) {
if (obj->refcount == 1) {
if (!EG(objects_store).object_buckets[handle].destructor_called) {
EG(objects_store).object_buckets[handle].destructor_called = 1;
if (obj->dtor) {
if (handlers && !obj->handlers) {
obj->handlers = handlers;
}
zend_try {
obj->dtor(obj->object, handle TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
}
/* re-read the object from the object store as the store might have been reallocated in the dtor */
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->refcount == 1) {
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
if (obj->free_storage) {
zend_try {
obj->free_storage(obj->object TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
}
}
}
obj->refcount--;
#if ZEND_DEBUG_OBJECTS
if (obj->refcount == 0) {
fprintf(stderr, "Deallocated object id #%d\n", handle);
} else {
fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
}
#endif
if (failure) {
zend_bailout();
}
}
/* }}} */
| 166,939 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Track::~Track()
{
Info& info = const_cast<Info&>(m_info);
info.Clear();
ContentEncoding** i = content_encoding_entries_;
ContentEncoding** const j = content_encoding_entries_end_;
while (i != j) {
ContentEncoding* const encoding = *i++;
delete encoding;
}
delete [] content_encoding_entries_;
}
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 | Track::~Track()
long Track::Create(Segment* pSegment, const Info& info, long long element_start,
long long element_size, Track*& pResult) {
if (pResult)
return -1;
Track* const pTrack =
new (std::nothrow) Track(pSegment, element_start, element_size);
if (pTrack == NULL)
return -1; // generic error
const int status = info.Copy(pTrack->m_info);
if (status) { // error
delete pTrack;
return status;
}
pResult = pTrack;
return 0; // success
}
| 174,472 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
int retsize;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
effect_param_t *p = (effect_param_t *)pCmdData;
if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
cmdSize < (sizeof(effect_param_t) + p->psize) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (sizeof(effect_param_t) + p->psize)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
(size_t *)&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
Commit Message: fix possible overflow in effect wrappers.
Add checks on parameter size field in effect command handlers
to avoid overflow leading to invalid comparison with min allowed
size for command and reply buffers.
Bug: 26347509.
Change-Id: I20e6a9b6de8e5172b957caa1ac9410b9752efa4d
(cherry picked from commit ad1bd92a49d78df6bc6e75bee68c517c1326f3cf)
CWE ID: CWE-189 | int Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
int retsize;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
effect_param_t *p = (effect_param_t *)pCmdData;
if (SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) {
android_errorWriteLog(0x534e4554, "26347509");
return -EINVAL;
}
if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
cmdSize < (sizeof(effect_param_t) + p->psize) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (sizeof(effect_param_t) + p->psize)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
(size_t *)&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
| 173,935 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int persistent_prepare_exception(struct dm_exception_store *store,
struct dm_exception *e)
{
struct pstore *ps = get_info(store);
uint32_t stride;
chunk_t next_free;
sector_t size = get_dev_size(dm_snap_cow(store->snap)->bdev);
/* Is there enough room ? */
if (size < ((ps->next_free + 1) * store->chunk_size))
return -ENOSPC;
e->new_chunk = ps->next_free;
/*
* Move onto the next free pending, making sure to take
* into account the location of the metadata chunks.
*/
stride = (ps->exceptions_per_area + 1);
next_free = ++ps->next_free;
if (sector_div(next_free, stride) == 1)
ps->next_free++;
atomic_inc(&ps->pending_count);
return 0;
}
Commit Message: dm snapshot: fix data corruption
This patch fixes a particular type of data corruption that has been
encountered when loading a snapshot's metadata from disk.
When we allocate a new chunk in persistent_prepare, we increment
ps->next_free and we make sure that it doesn't point to a metadata area
by further incrementing it if necessary.
When we load metadata from disk on device activation, ps->next_free is
positioned after the last used data chunk. However, if this last used
data chunk is followed by a metadata area, ps->next_free is positioned
erroneously to the metadata area. A newly-allocated chunk is placed at
the same location as the metadata area, resulting in data or metadata
corruption.
This patch changes the code so that ps->next_free skips the metadata
area when metadata are loaded in function read_exceptions.
The patch also moves a piece of code from persistent_prepare_exception
to a separate function skip_metadata to avoid code duplication.
CVE-2013-4299
Signed-off-by: Mikulas Patocka <[email protected]>
Cc: [email protected]
Cc: Mike Snitzer <[email protected]>
Signed-off-by: Alasdair G Kergon <[email protected]>
CWE ID: CWE-264 | static int persistent_prepare_exception(struct dm_exception_store *store,
struct dm_exception *e)
{
struct pstore *ps = get_info(store);
sector_t size = get_dev_size(dm_snap_cow(store->snap)->bdev);
/* Is there enough room ? */
if (size < ((ps->next_free + 1) * store->chunk_size))
return -ENOSPC;
e->new_chunk = ps->next_free;
/*
* Move onto the next free pending, making sure to take
* into account the location of the metadata chunks.
*/
ps->next_free++;
skip_metadata(ps);
atomic_inc(&ps->pending_count);
return 0;
}
| 165,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_HELP:
default:
usage();
break;
}
}
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
numcmpts = jas_image_numcmpts(image);
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
Commit Message: Fixed a sanitizer failure in the BMP codec.
Also, added a --debug-level command line option to the imginfo command
for debugging purposes.
CWE ID: CWE-476 | int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
debug = 0;
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
numcmpts = jas_image_numcmpts(image);
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
| 168,761 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
int i, j;
int w, h;
int leftbyte, rightbyte;
int shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = (x + w < dst->width) ? w : dst->width - x;
h = (y + h < dst->height) ? h : dst->height - y;
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = x >> 3;
rightbyte = (x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
uint32_t i, j;
uint32_t w, h;
uint32_t leftbyte, rightbyte;
uint32_t shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = ((uint32_t)x + w < dst->width) ? w : ((dst->width >= (uint32_t)x) ? dst->width - (uint32_t)x : 0);
h = ((uint32_t)y + h < dst->height) ? h : ((dst->height >= (uint32_t)y) ? dst->height - (uint32_t)y : 0);
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = (uint32_t)x >> 3;
rightbyte = ((uint32_t)x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
| 165,489 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserEventRouter::DispatchTabUpdatedEvent(
WebContents* contents, DictionaryValue* changed_properties) {
DCHECK(changed_properties);
DCHECK(contents);
scoped_ptr<ListValue> args_base(new ListValue());
args_base->AppendInteger(ExtensionTabUtil::GetTabId(contents));
args_base->Append(changed_properties);
Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
scoped_ptr<Event> event(new Event(events::kOnTabUpdated, args_base.Pass()));
event->restrict_to_profile = profile;
event->user_gesture = EventRouter::USER_GESTURE_NOT_ENABLED;
event->will_dispatch_callback =
base::Bind(&WillDispatchTabUpdatedEvent, contents);
ExtensionSystem::Get(profile)->event_router()->BroadcastEvent(event.Pass());
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void BrowserEventRouter::DispatchTabUpdatedEvent(
WebContents* contents, scoped_ptr<DictionaryValue> changed_properties) {
DCHECK(changed_properties);
DCHECK(contents);
scoped_ptr<ListValue> args_base(new ListValue());
args_base->AppendInteger(ExtensionTabUtil::GetTabId(contents));
// Second arg: An object containing the changes to the tab state. Filled in
// by WillDispatchTabUpdatedEvent as a copy of changed_properties, if the
// extension has the tabs permission.
Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
scoped_ptr<Event> event(new Event(events::kOnTabUpdated, args_base.Pass()));
event->restrict_to_profile = profile;
event->user_gesture = EventRouter::USER_GESTURE_NOT_ENABLED;
event->will_dispatch_callback =
base::Bind(&WillDispatchTabUpdatedEvent,
contents, changed_properties.get());
ExtensionSystem::Get(profile)->event_router()->BroadcastEvent(event.Pass());
}
| 171,449 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppCacheDatabase::ReadCacheRecord(
const sql::Statement& statement, CacheRecord* record) {
record->cache_id = statement.ColumnInt64(0);
record->group_id = statement.ColumnInt64(1);
record->online_wildcard = statement.ColumnBool(2);
record->update_time =
base::Time::FromInternalValue(statement.ColumnInt64(3));
record->cache_size = statement.ColumnInt64(4);
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCacheDatabase::ReadCacheRecord(
const sql::Statement& statement, CacheRecord* record) {
record->cache_id = statement.ColumnInt64(0);
record->group_id = statement.ColumnInt64(1);
record->online_wildcard = statement.ColumnBool(2);
record->update_time =
base::Time::FromInternalValue(statement.ColumnInt64(3));
record->cache_size = statement.ColumnInt64(4);
record->padding_size = statement.ColumnInt64(5);
}
| 172,981 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
{
if (png_get_bit_depth(pp, pi) != dp->bit_depth)
png_error(pp, "validate: bit depth changed");
if (png_get_color_type(pp, pi) != dp->colour_type)
png_error(pp, "validate: color type changed");
if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
png_error(pp, "validate: filter type changed");
if (png_get_interlace_type(pp, pi) != dp->interlace_type)
png_error(pp, "validate: interlacing changed");
if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
png_error(pp, "validate: compression type changed");
dp->w = png_get_image_width(pp, pi);
if (dp->w != standard_width(pp, dp->id))
png_error(pp, "validate: image width changed");
dp->h = png_get_image_height(pp, pi);
if (dp->h != standard_height(pp, dp->id))
png_error(pp, "validate: image height changed");
/* Record (but don't check at present) the input sBIT according to the colour
* type information.
*/
{
png_color_8p sBIT = 0;
if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
{
int sBIT_invalid = 0;
if (sBIT == 0)
png_error(pp, "validate: unexpected png_get_sBIT result");
if (dp->colour_type & PNG_COLOR_MASK_COLOR)
{
if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
sBIT_invalid = 1;
else
dp->red_sBIT = sBIT->red;
if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
sBIT_invalid = 1;
else
dp->green_sBIT = sBIT->green;
if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
sBIT_invalid = 1;
else
dp->blue_sBIT = sBIT->blue;
}
else /* !COLOR */
{
if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
sBIT_invalid = 1;
else
dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
}
/* All 8 bits in tRNS for a palette image are significant - see the
* spec.
*/
if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
{
if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
sBIT_invalid = 1;
else
dp->alpha_sBIT = sBIT->alpha;
}
if (sBIT_invalid)
png_error(pp, "validate: sBIT value out of range");
}
}
/* Important: this is validating the value *before* any transforms have been
* put in place. It doesn't matter for the standard tests, where there are
* no transforms, but it does for other tests where rowbytes may change after
* png_read_update_info.
*/
if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
png_error(pp, "validate: row size changed");
/* Validate the colour type 3 palette (this can be present on other color
* types.)
*/
standard_palette_validate(dp, pp, pi);
/* In any case always check for a tranparent color (notice that the
* colour type 3 case must not give a successful return on the get_tRNS call
* with these arguments!)
*/
{
png_color_16p trans_color = 0;
if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
{
if (trans_color == 0)
png_error(pp, "validate: unexpected png_get_tRNS (color) result");
switch (dp->colour_type)
{
case 0:
dp->transparent.red = dp->transparent.green = dp->transparent.blue =
trans_color->gray;
dp->is_transparent = 1;
break;
case 2:
dp->transparent.red = trans_color->red;
dp->transparent.green = trans_color->green;
dp->transparent.blue = trans_color->blue;
dp->is_transparent = 1;
break;
case 3:
/* Not expected because it should result in the array case
* above.
*/
png_error(pp, "validate: unexpected png_get_tRNS result");
break;
default:
png_error(pp, "validate: invalid tRNS chunk with alpha image");
}
}
}
/* Read the number of passes - expected to match the value used when
* creating the image (interlaced or not). This has the side effect of
* turning on interlace handling (if do_interlace is not set.)
*/
dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
if (!dp->do_interlace && dp->npasses != png_set_interlace_handling(pp))
png_error(pp, "validate: file changed interlace type");
/* Caller calls png_read_update_info or png_start_read_image now, then calls
* part2.
*/
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
{
if (png_get_bit_depth(pp, pi) != dp->bit_depth)
png_error(pp, "validate: bit depth changed");
if (png_get_color_type(pp, pi) != dp->colour_type)
png_error(pp, "validate: color type changed");
if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
png_error(pp, "validate: filter type changed");
if (png_get_interlace_type(pp, pi) != dp->interlace_type)
png_error(pp, "validate: interlacing changed");
if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
png_error(pp, "validate: compression type changed");
dp->w = png_get_image_width(pp, pi);
if (dp->w != standard_width(pp, dp->id))
png_error(pp, "validate: image width changed");
dp->h = png_get_image_height(pp, pi);
if (dp->h != standard_height(pp, dp->id))
png_error(pp, "validate: image height changed");
/* Record (but don't check at present) the input sBIT according to the colour
* type information.
*/
{
png_color_8p sBIT = 0;
if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
{
int sBIT_invalid = 0;
if (sBIT == 0)
png_error(pp, "validate: unexpected png_get_sBIT result");
if (dp->colour_type & PNG_COLOR_MASK_COLOR)
{
if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
sBIT_invalid = 1;
else
dp->red_sBIT = sBIT->red;
if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
sBIT_invalid = 1;
else
dp->green_sBIT = sBIT->green;
if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
sBIT_invalid = 1;
else
dp->blue_sBIT = sBIT->blue;
}
else /* !COLOR */
{
if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
sBIT_invalid = 1;
else
dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
}
/* All 8 bits in tRNS for a palette image are significant - see the
* spec.
*/
if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
{
if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
sBIT_invalid = 1;
else
dp->alpha_sBIT = sBIT->alpha;
}
if (sBIT_invalid)
png_error(pp, "validate: sBIT value out of range");
}
}
/* Important: this is validating the value *before* any transforms have been
* put in place. It doesn't matter for the standard tests, where there are
* no transforms, but it does for other tests where rowbytes may change after
* png_read_update_info.
*/
if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
png_error(pp, "validate: row size changed");
/* Validate the colour type 3 palette (this can be present on other color
* types.)
*/
standard_palette_validate(dp, pp, pi);
/* In any case always check for a tranparent color (notice that the
* colour type 3 case must not give a successful return on the get_tRNS call
* with these arguments!)
*/
{
png_color_16p trans_color = 0;
if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
{
if (trans_color == 0)
png_error(pp, "validate: unexpected png_get_tRNS (color) result");
switch (dp->colour_type)
{
case 0:
dp->transparent.red = dp->transparent.green = dp->transparent.blue =
trans_color->gray;
dp->has_tRNS = 1;
break;
case 2:
dp->transparent.red = trans_color->red;
dp->transparent.green = trans_color->green;
dp->transparent.blue = trans_color->blue;
dp->has_tRNS = 1;
break;
case 3:
/* Not expected because it should result in the array case
* above.
*/
png_error(pp, "validate: unexpected png_get_tRNS result");
break;
default:
png_error(pp, "validate: invalid tRNS chunk with alpha image");
}
}
}
/* Read the number of passes - expected to match the value used when
* creating the image (interlaced or not). This has the side effect of
* turning on interlace handling (if do_interlace is not set.)
*/
dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
if (!dp->do_interlace)
{
# ifdef PNG_READ_INTERLACING_SUPPORTED
if (dp->npasses != png_set_interlace_handling(pp))
png_error(pp, "validate: file changed interlace type");
# else /* !READ_INTERLACING */
/* This should never happen: the relevant tests (!do_interlace) should
* not be run.
*/
if (dp->npasses > 1)
png_error(pp, "validate: no libpng interlace support");
# endif /* !READ_INTERLACING */
}
/* Caller calls png_read_update_info or png_start_read_image now, then calls
* part2.
*/
}
| 173,698 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int timer_start(Unit *u) {
Timer *t = TIMER(u);
TimerValue *v;
assert(t);
assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);
if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
return -ENOENT;
t->last_trigger = DUAL_TIMESTAMP_NULL;
/* Reenable all timers that depend on unit activation time */
LIST_FOREACH(value, v, t->values)
if (v->base == TIMER_ACTIVE)
v->disabled = false;
if (t->stamp_path) {
struct stat st;
if (stat(t->stamp_path, &st) >= 0)
t->last_trigger.realtime = timespec_load(&st.st_atim);
else if (errno == ENOENT)
/* The timer has never run before,
* make sure a stamp file exists.
*/
touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
}
t->result = TIMER_SUCCESS;
timer_enter_waiting(t, true);
return 1;
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264 | static int timer_start(Unit *u) {
Timer *t = TIMER(u);
TimerValue *v;
assert(t);
assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);
if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
return -ENOENT;
t->last_trigger = DUAL_TIMESTAMP_NULL;
/* Reenable all timers that depend on unit activation time */
LIST_FOREACH(value, v, t->values)
if (v->base == TIMER_ACTIVE)
v->disabled = false;
if (t->stamp_path) {
struct stat st;
if (stat(t->stamp_path, &st) >= 0)
t->last_trigger.realtime = timespec_load(&st.st_atim);
else if (errno == ENOENT)
/* The timer has never run before,
* make sure a stamp file exists.
*/
touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
}
t->result = TIMER_SUCCESS;
timer_enter_waiting(t, true);
return 1;
}
| 170,107 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct net *get_net_ns_by_id(struct net *net, int id)
{
struct net *peer;
if (id < 0)
return NULL;
rcu_read_lock();
spin_lock_bh(&net->nsid_lock);
peer = idr_find(&net->netns_ids, id);
if (peer)
get_net(peer);
spin_unlock_bh(&net->nsid_lock);
rcu_read_unlock();
return peer;
}
Commit Message: net: Fix double free and memory corruption in get_net_ns_by_id()
(I can trivially verify that that idr_remove in cleanup_net happens
after the network namespace count has dropped to zero --EWB)
Function get_net_ns_by_id() does not check for net::count
after it has found a peer in netns_ids idr.
It may dereference a peer, after its count has already been
finaly decremented. This leads to double free and memory
corruption:
put_net(peer) rtnl_lock()
atomic_dec_and_test(&peer->count) [count=0] ...
__put_net(peer) get_net_ns_by_id(net, id)
spin_lock(&cleanup_list_lock)
list_add(&net->cleanup_list, &cleanup_list)
spin_unlock(&cleanup_list_lock)
queue_work() peer = idr_find(&net->netns_ids, id)
| get_net(peer) [count=1]
| ...
| (use after final put)
v ...
cleanup_net() ...
spin_lock(&cleanup_list_lock) ...
list_replace_init(&cleanup_list, ..) ...
spin_unlock(&cleanup_list_lock) ...
... ...
... put_net(peer)
... atomic_dec_and_test(&peer->count) [count=0]
... spin_lock(&cleanup_list_lock)
... list_add(&net->cleanup_list, &cleanup_list)
... spin_unlock(&cleanup_list_lock)
... queue_work()
... rtnl_unlock()
rtnl_lock() ...
for_each_net(tmp) { ...
id = __peernet2id(tmp, peer) ...
spin_lock_irq(&tmp->nsid_lock) ...
idr_remove(&tmp->netns_ids, id) ...
... ...
net_drop_ns() ...
net_free(peer) ...
} ...
|
v
cleanup_net()
...
(Second free of peer)
Also, put_net() on the right cpu may reorder with left's cpu
list_replace_init(&cleanup_list, ..), and then cleanup_list
will be corrupted.
Since cleanup_net() is executed in worker thread, while
put_net(peer) can happen everywhere, there should be
enough time for concurrent get_net_ns_by_id() to pick
the peer up, and the race does not seem to be unlikely.
The patch fixes the problem in standard way.
(Also, there is possible problem in peernet2id_alloc(), which requires
check for net::count under nsid_lock and maybe_get_net(peer), but
in current stable kernel it's used under rtnl_lock() and it has to be
safe. Openswitch begun to use peernet2id_alloc(), and possibly it should
be fixed too. While this is not in stable kernel yet, so I'll send
a separate message to netdev@ later).
Cc: Nicolas Dichtel <[email protected]>
Signed-off-by: Kirill Tkhai <[email protected]>
Fixes: 0c7aecd4bde4 "netns: add rtnl cmd to add and get peer netns ids"
Reviewed-by: Andrey Ryabinin <[email protected]>
Reviewed-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Eric W. Biederman <[email protected]>
Reviewed-by: Eric Dumazet <[email protected]>
Acked-by: Nicolas Dichtel <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | struct net *get_net_ns_by_id(struct net *net, int id)
{
struct net *peer;
if (id < 0)
return NULL;
rcu_read_lock();
spin_lock_bh(&net->nsid_lock);
peer = idr_find(&net->netns_ids, id);
if (peer)
peer = maybe_get_net(peer);
spin_unlock_bh(&net->nsid_lock);
rcu_read_unlock();
return peer;
}
| 169,427 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SocketStreamDispatcherHost::SocketStreamDispatcherHost(
int render_process_id,
ResourceMessageFilter::URLRequestContextSelector* selector,
content::ResourceContext* resource_context)
: ALLOW_THIS_IN_INITIALIZER_LIST(ssl_delegate_weak_factory_(this)),
render_process_id_(render_process_id),
url_request_context_selector_(selector),
resource_context_(resource_context) {
DCHECK(selector);
net::WebSocketJob::EnsureInit();
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | SocketStreamDispatcherHost::SocketStreamDispatcherHost(
int render_process_id,
ResourceMessageFilter::URLRequestContextSelector* selector,
content::ResourceContext* resource_context)
: render_process_id_(render_process_id),
url_request_context_selector_(selector),
resource_context_(resource_context) {
DCHECK(selector);
net::WebSocketJob::EnsureInit();
}
| 170,993 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper,
char *path,
char *mode,
int options,
char **opened_path,
php_stream_context *context STREAMS_DC TSRMLS_DC)
{
int path_len;
char *file_basename;
size_t file_basename_len;
char file_dirname[MAXPATHLEN];
struct zip *za;
struct zip_file *zf = NULL;
char *fragment;
int fragment_len;
int err;
php_stream *stream = NULL;
struct php_zip_stream_data_t *self;
fragment = strchr(path, '#');
if (!fragment) {
return NULL;
}
if (strncasecmp("zip://", path, 6) == 0) {
path += 6;
}
fragment_len = strlen(fragment);
if (fragment_len < 1) {
return NULL;
}
path_len = strlen(path);
if (path_len >= MAXPATHLEN || mode[0] != 'r') {
return NULL;
}
memcpy(file_dirname, path, path_len - fragment_len);
file_dirname[path_len - fragment_len] = '\0';
php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC);
fragment++;
if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) {
efree(file_basename);
return NULL;
}
za = zip_open(file_dirname, ZIP_CREATE, &err);
if (za) {
zf = zip_fopen(za, fragment, 0);
if (zf) {
self = emalloc(sizeof(*self));
self->za = za;
self->zf = zf;
self->stream = NULL;
self->cursor = 0;
stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);
if (opened_path) {
*opened_path = estrdup(path);
}
} else {
zip_close(za);
}
}
efree(file_basename);
if (!stream) {
return NULL;
} else {
return stream;
}
}
Commit Message:
CWE ID: CWE-119 | php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper,
char *path,
char *mode,
int options,
char **opened_path,
php_stream_context *context STREAMS_DC TSRMLS_DC)
{
size_t path_len;
char *file_basename;
size_t file_basename_len;
char file_dirname[MAXPATHLEN];
struct zip *za;
struct zip_file *zf = NULL;
char *fragment;
size_t fragment_len;
int err;
php_stream *stream = NULL;
struct php_zip_stream_data_t *self;
fragment = strchr(path, '#');
if (!fragment) {
return NULL;
}
if (strncasecmp("zip://", path, 6) == 0) {
path += 6;
}
fragment_len = strlen(fragment);
if (fragment_len < 1) {
return NULL;
}
path_len = strlen(path);
if (path_len >= MAXPATHLEN || mode[0] != 'r') {
return NULL;
}
memcpy(file_dirname, path, path_len - fragment_len);
file_dirname[path_len - fragment_len] = '\0';
php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC);
fragment++;
if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) {
efree(file_basename);
return NULL;
}
za = zip_open(file_dirname, ZIP_CREATE, &err);
if (za) {
zf = zip_fopen(za, fragment, 0);
if (zf) {
self = emalloc(sizeof(*self));
self->za = za;
self->zf = zf;
self->stream = NULL;
self->cursor = 0;
stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);
if (opened_path) {
*opened_path = estrdup(path);
}
} else {
zip_close(za);
}
}
efree(file_basename);
if (!stream) {
return NULL;
} else {
return stream;
}
}
| 164,969 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool InputHandler::shouldRequestSpellCheckingOptionsForPoint(Platform::IntPoint& point, const Element* touchedElement, imf_sp_text_t& spellCheckingOptionRequest)
{
if (!isActiveTextEdit())
return false;
Element* currentFocusElement = m_currentFocusElement.get();
if (!currentFocusElement || !currentFocusElement->isElementNode())
return false;
while (!currentFocusElement->isRootEditableElement()) {
Element* parentElement = currentFocusElement->parentElement();
if (!parentElement)
break;
currentFocusElement = parentElement;
}
if (touchedElement != currentFocusElement)
return false;
LayoutPoint contentPos(m_webPage->mapFromViewportToContents(point));
contentPos = DOMSupport::convertPointToFrame(m_webPage->mainFrame(), m_webPage->focusedOrMainFrame(), roundedIntPoint(contentPos));
Document* document = currentFocusElement->document();
ASSERT(document);
RenderedDocumentMarker* marker = document->markers()->renderedMarkerContainingPoint(contentPos, DocumentMarker::Spelling);
if (!marker)
return false;
m_didSpellCheckWord = true;
spellCheckingOptionRequest.startTextPosition = marker->startOffset();
spellCheckingOptionRequest.endTextPosition = marker->endOffset();
m_spellCheckingOptionsRequest.startTextPosition = 0;
m_spellCheckingOptionsRequest.endTextPosition = 0;
SpellingLog(LogLevelInfo, "InputHandler::shouldRequestSpellCheckingOptionsForPoint Found spelling marker at point %d, %d\nMarker start %d end %d",
point.x(), point.y(), spellCheckingOptionRequest.startTextPosition, spellCheckingOptionRequest.endTextPosition);
return true;
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | bool InputHandler::shouldRequestSpellCheckingOptionsForPoint(Platform::IntPoint& point, const Element* touchedElement, imf_sp_text_t& spellCheckingOptionRequest)
bool InputHandler::shouldRequestSpellCheckingOptionsForPoint(const Platform::IntPoint& documentContentPosition, const Element* touchedElement, imf_sp_text_t& spellCheckingOptionRequest)
{
if (!isActiveTextEdit())
return false;
Element* currentFocusElement = m_currentFocusElement.get();
if (!currentFocusElement || !currentFocusElement->isElementNode())
return false;
while (!currentFocusElement->isRootEditableElement()) {
Element* parentElement = currentFocusElement->parentElement();
if (!parentElement)
break;
currentFocusElement = parentElement;
}
if (touchedElement != currentFocusElement)
return false;
LayoutPoint contentPos(documentContentPosition);
contentPos = DOMSupport::convertPointToFrame(m_webPage->mainFrame(), m_webPage->focusedOrMainFrame(), roundedIntPoint(contentPos));
Document* document = currentFocusElement->document();
ASSERT(document);
RenderedDocumentMarker* marker = document->markers()->renderedMarkerContainingPoint(contentPos, DocumentMarker::Spelling);
if (!marker)
return false;
m_didSpellCheckWord = true;
spellCheckingOptionRequest.startTextPosition = marker->startOffset();
spellCheckingOptionRequest.endTextPosition = marker->endOffset();
m_spellCheckingOptionsRequest.startTextPosition = 0;
m_spellCheckingOptionsRequest.endTextPosition = 0;
SpellingLog(LogLevelInfo, "InputHandler::shouldRequestSpellCheckingOptionsForPoint Found spelling marker at point %d, %d\nMarker start %d end %d",
point.x(), point.y(), spellCheckingOptionRequest.startTextPosition, spellCheckingOptionRequest.endTextPosition);
return true;
}
| 170,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct bpf_map *bpf_map_get_with_uref(u32 ufd)
{
struct fd f = fdget(ufd);
struct bpf_map *map;
map = __bpf_map_get(f);
if (IS_ERR(map))
return map;
bpf_map_inc(map, true);
fdput(f);
return map;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | struct bpf_map *bpf_map_get_with_uref(u32 ufd)
{
struct fd f = fdget(ufd);
struct bpf_map *map;
map = __bpf_map_get(f);
if (IS_ERR(map))
return map;
map = bpf_map_inc(map, true);
fdput(f);
return map;
}
| 167,252 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BiquadDSPKernel::getFrequencyResponse(int nFrequencies,
const float* frequencyHz,
float* magResponse,
float* phaseResponse)
{
bool isGood = nFrequencies > 0 && frequencyHz && magResponse && phaseResponse;
ASSERT(isGood);
if (!isGood)
return;
Vector<float> frequency(nFrequencies);
double nyquist = this->nyquist();
for (int k = 0; k < nFrequencies; ++k)
frequency[k] = narrowPrecisionToFloat(frequencyHz[k] / nyquist);
updateCoefficientsIfNecessary(false, true);
m_biquad.getFrequencyResponse(nFrequencies, frequency.data(), magResponse, phaseResponse);
}
Commit Message: Initialize value since calculateFinalValues may fail to do so.
Fix threading issue where updateCoefficientsIfNecessary was not always
called from the audio thread. This causes the value not to be
initialized.
Thus,
o Initialize the variable to some value, just in case.
o Split updateCoefficientsIfNecessary into two functions with the code
that sets the coefficients pulled out in to the new function
updateCoefficients.
o Simplify updateCoefficientsIfNecessary since useSmoothing was always
true, and forceUpdate is not longer needed.
o Add process lock to prevent the audio thread from updating the
coefficients while they are being read in the main thread. The audio
thread will update them the next time around.
o Make getFrequencyResponse set the lock while reading the
coefficients of the biquad in preparation for computing the
frequency response.
BUG=389219
Review URL: https://codereview.chromium.org/354213002
git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void BiquadDSPKernel::getFrequencyResponse(int nFrequencies,
const float* frequencyHz,
float* magResponse,
float* phaseResponse)
{
bool isGood = nFrequencies > 0 && frequencyHz && magResponse && phaseResponse;
ASSERT(isGood);
if (!isGood)
return;
Vector<float> frequency(nFrequencies);
double nyquist = this->nyquist();
for (int k = 0; k < nFrequencies; ++k)
frequency[k] = narrowPrecisionToFloat(frequencyHz[k] / nyquist);
double cutoffFrequency;
double Q;
double gain;
double detune; // in Cents
{
// Get a copy of the current biquad filter coefficients so we can update the biquad with
// these values. We need to synchronize with process() to prevent process() from updating
// the filter coefficients while we're trying to access them. The process will update it
// next time around.
//
// The BiquadDSPKernel object here (along with it's Biquad object) is for querying the
// frequency response and is NOT the same as the one in process() which is used for
// performing the actual filtering. This one is is created in
// BiquadProcessor::getFrequencyResponse for this purpose. Both, however, point to the same
// BiquadProcessor object.
//
// FIXME: Simplify this: crbug.com/390266
MutexLocker processLocker(m_processLock);
cutoffFrequency = biquadProcessor()->parameter1()->value();
Q = biquadProcessor()->parameter2()->value();
gain = biquadProcessor()->parameter3()->value();
detune = biquadProcessor()->parameter4()->value();
}
updateCoefficients(cutoffFrequency, Q, gain, detune);
m_biquad.getFrequencyResponse(nFrequencies, frequency.data(), magResponse, phaseResponse);
}
| 171,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encoderow != NULL);
/* XXX horizontal differencing alters user's data XXX */
(*sp->encodepfunc)(tif, bp, cc);
return (*sp->encoderow)(tif, bp, cc, s);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
TIFFPredictorState *sp = PredictorState(tif);
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encoderow != NULL);
/* XXX horizontal differencing alters user's data XXX */
if( !(*sp->encodepfunc)(tif, bp, cc) )
return 0;
return (*sp->encoderow)(tif, bp, cc, s);
}
| 166,878 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TabStrip::ChangeTabGroup(int model_index,
base::Optional<int> old_group,
base::Optional<int> new_group) {
if (new_group.has_value() && !group_headers_[new_group.value()]) {
const TabGroupData* group_data =
controller_->GetDataForGroup(new_group.value());
auto header = std::make_unique<TabGroupHeader>(group_data->title());
header->set_owned_by_client();
AddChildView(header.get());
group_headers_[new_group.value()] = std::move(header);
}
if (old_group.has_value() &&
controller_->ListTabsInGroup(old_group.value()).size() == 0) {
group_headers_.erase(old_group.value());
}
UpdateIdealBounds();
AnimateToIdealBounds();
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20 | void TabStrip::ChangeTabGroup(int model_index,
base::Optional<int> old_group,
base::Optional<int> new_group) {
tab_at(model_index)->SetGroup(new_group);
if (new_group.has_value() && !group_headers_[new_group.value()]) {
auto header = std::make_unique<TabGroupHeader>(this, new_group.value());
header->set_owned_by_client();
AddChildView(header.get());
group_headers_[new_group.value()] = std::move(header);
}
if (old_group.has_value() &&
controller_->ListTabsInGroup(old_group.value()).size() == 0) {
group_headers_.erase(old_group.value());
}
UpdateIdealBounds();
AnimateToIdealBounds();
}
| 172,520 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, current)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!intern->u.file.current_line && !intern->u.file.current_zval) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
}
if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) {
RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);
} else if (intern->u.file.current_zval) {
RETURN_ZVAL(intern->u.file.current_zval, 1, 0);
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto int SplFileObject::key()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, current)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!intern->u.file.current_line && !intern->u.file.current_zval) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
}
if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) {
RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);
} else if (intern->u.file.current_zval) {
RETURN_ZVAL(intern->u.file.current_zval, 1, 0);
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto int SplFileObject::key()
| 167,055 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void Update(scoped_refptr<ClipPaintPropertyNode> node,
scoped_refptr<const ClipPaintPropertyNode> new_parent,
const FloatRoundedRect& new_clip_rect) {
node->Update(std::move(new_parent),
ClipPaintPropertyNode::State{nullptr, new_clip_rect});
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | static void Update(scoped_refptr<ClipPaintPropertyNode> node,
static void Update(std::unique_ptr<ClipPaintPropertyNode>& node,
const ClipPaintPropertyNode& new_parent,
const FloatRoundedRect& new_clip_rect) {
node->Update(new_parent,
ClipPaintPropertyNode::State{nullptr, new_clip_rect});
}
| 171,838 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client,
uint32_t port_index,
const std::vector<uint8>& data,
double timestamp) {
DCHECK_LT(port_index, output_streams_.size());
output_streams_[port_index]->Send(data);
client->AccumulateMidiBytesSent(data.size());
}
Commit Message: MidiManagerUsb should not trust indices provided by renderer.
MidiManagerUsb::DispatchSendMidiData takes |port_index| parameter. As it is
provided by a renderer possibly under the control of an attacker, we must
validate the given index before using it.
BUG=456516
Review URL: https://codereview.chromium.org/907793002
Cr-Commit-Position: refs/heads/master@{#315303}
CWE ID: CWE-119 | void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client,
uint32_t port_index,
const std::vector<uint8>& data,
double timestamp) {
if (port_index >= output_streams_.size()) {
// |port_index| is provided by a renderer so we can't believe that it is
// in the valid range.
// TODO(toyoshim): Move this check to MidiHost and kill the renderer when
// it fails.
return;
}
output_streams_[port_index]->Send(data);
client->AccumulateMidiBytesSent(data.size());
}
| 172,014 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_create_iv)
{
char *iv;
long source = RANDOM;
long size;
int n = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &size, &source) == FAILURE) {
return;
}
if (size <= 0 || size >= INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX);
RETURN_FALSE;
}
iv = ecalloc(size + 1, 1);
if (source == RANDOM || source == URANDOM) {
#if PHP_WIN32
/* random/urandom equivalent on Windows */
BYTE *iv_b = (BYTE *) iv;
if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
n = size;
#else
int *fd = &MCG(fd[source]);
size_t read_bytes = 0;
if (*fd < 0) {
*fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY);
if (*fd < 0) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot open source device");
RETURN_FALSE;
}
}
while (read_bytes < size) {
n = read(*fd, iv + read_bytes, size - read_bytes);
if (n < 0) {
break;
}
read_bytes += n;
}
n = read_bytes;
if (n < size) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
#endif
} else {
n = size;
while (size) {
iv[--size] = (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX);
}
}
RETURN_STRINGL(iv, n, 0);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_create_iv)
{
char *iv;
long source = RANDOM;
long size;
int n = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &size, &source) == FAILURE) {
return;
}
if (size <= 0 || size >= INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX);
RETURN_FALSE;
}
iv = ecalloc(size + 1, 1);
if (source == RANDOM || source == URANDOM) {
#if PHP_WIN32
/* random/urandom equivalent on Windows */
BYTE *iv_b = (BYTE *) iv;
if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
n = size;
#else
int *fd = &MCG(fd[source]);
size_t read_bytes = 0;
if (*fd < 0) {
*fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY);
if (*fd < 0) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot open source device");
RETURN_FALSE;
}
}
while (read_bytes < size) {
n = read(*fd, iv + read_bytes, size - read_bytes);
if (n < 0) {
break;
}
read_bytes += n;
}
n = read_bytes;
if (n < size) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
#endif
} else {
n = size;
while (size) {
iv[--size] = (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX);
}
}
RETURN_STRINGL(iv, n, 0);
}
| 167,111 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
{
RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable);
}
Commit Message: Remove SpeechSynthesis runtime flag (status=stable)
BUG=402536
Review URL: https://codereview.chromium.org/482273005
git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-94 | void WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
| 171,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int parse_exports_table(long long *table_start)
{
int res;
int indexes = SQUASHFS_LOOKUP_BLOCKS(sBlk.s.inodes);
long long export_index_table[indexes];
res = read_fs_bytes(fd, sBlk.s.lookup_table_start,
SQUASHFS_LOOKUP_BLOCK_BYTES(sBlk.s.inodes), export_index_table);
if(res == FALSE) {
ERROR("parse_exports_table: failed to read export index table\n");
return FALSE;
}
SQUASHFS_INSWAP_LOOKUP_BLOCKS(export_index_table, indexes);
/*
* export_index_table[0] stores the start of the compressed export blocks.
* This by definition is also the end of the previous filesystem
* table - the fragment table.
*/
*table_start = export_index_table[0];
return TRUE;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
CWE ID: CWE-190 | static int parse_exports_table(long long *table_start)
{
/*
* Note on overflow limits:
* Size of SBlk.s.inodes is 2^32 (unsigned int)
* Max indexes is (2^32*8)/8K or 2^22
* Max length is ((2^32*8)/8K)*8 or 2^25
*/
int res;
int indexes = SQUASHFS_LOOKUP_BLOCKS((long long) sBlk.s.inodes);
int length = SQUASHFS_LOOKUP_BLOCK_BYTES((long long) sBlk.s.inodes);
long long *export_index_table;
/*
* The size of the index table (length bytes) should match the
* table start and end points
*/
if(length != (*table_start - sBlk.s.lookup_table_start)) {
ERROR("parse_exports_table: Bad inode count in super block\n");
return FALSE;
}
export_index_table = alloc_index_table(indexes);
res = read_fs_bytes(fd, sBlk.s.lookup_table_start, length,
export_index_table);
if(res == FALSE) {
ERROR("parse_exports_table: failed to read export index table\n");
return FALSE;
}
SQUASHFS_INSWAP_LOOKUP_BLOCKS(export_index_table, indexes);
/*
* export_index_table[0] stores the start of the compressed export blocks.
* This by definition is also the end of the previous filesystem
* table - the fragment table.
*/
*table_start = export_index_table[0];
return TRUE;
}
| 168,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int nfc_llcp_send_cc(struct nfc_llcp_sock *sock)
{
struct nfc_llcp_local *local;
struct sk_buff *skb;
u8 *miux_tlv = NULL, miux_tlv_length;
u8 *rw_tlv = NULL, rw_tlv_length, rw;
int err;
u16 size = 0;
__be16 miux;
pr_debug("Sending CC\n");
local = sock->local;
if (local == NULL)
return -ENODEV;
/* If the socket parameters are not set, use the local ones */
miux = be16_to_cpu(sock->miux) > LLCP_MAX_MIUX ?
local->miux : sock->miux;
rw = sock->rw > LLCP_MAX_RW ? local->rw : sock->rw;
miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&miux, 0,
&miux_tlv_length);
size += miux_tlv_length;
rw_tlv = nfc_llcp_build_tlv(LLCP_TLV_RW, &rw, 0, &rw_tlv_length);
size += rw_tlv_length;
skb = llcp_allocate_pdu(sock, LLCP_PDU_CC, size);
if (skb == NULL) {
err = -ENOMEM;
goto error_tlv;
}
llcp_add_tlv(skb, miux_tlv, miux_tlv_length);
llcp_add_tlv(skb, rw_tlv, rw_tlv_length);
skb_queue_tail(&local->tx_queue, skb);
err = 0;
error_tlv:
if (err)
pr_err("error %d\n", err);
kfree(miux_tlv);
kfree(rw_tlv);
return err;
}
Commit Message: net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails
KASAN report this:
BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc]
Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401
CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
Call Trace:
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0xfa/0x1ce lib/dump_stack.c:113
kasan_report+0x171/0x18d mm/kasan/report.c:321
memcpy+0x1f/0x50 mm/kasan/common.c:130
nfc_llcp_build_gb+0x37f/0x540 [nfc]
nfc_llcp_register_device+0x6eb/0xb50 [nfc]
nfc_register_device+0x50/0x1d0 [nfc]
nfcsim_device_new+0x394/0x67d [nfcsim]
? 0xffffffffc1080000
nfcsim_init+0x6b/0x1000 [nfcsim]
do_one_initcall+0xfa/0x5ca init/main.c:887
do_init_module+0x204/0x5f6 kernel/module.c:3460
load_module+0x66b2/0x8570 kernel/module.c:3808
__do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003
RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc
R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004
nfc_llcp_build_tlv will return NULL on fails, caller should check it,
otherwise will trigger a NULL dereference.
Reported-by: Hulk Robot <[email protected]>
Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames")
Fixes: d646960f7986 ("NFC: Initial LLCP support")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | int nfc_llcp_send_cc(struct nfc_llcp_sock *sock)
{
struct nfc_llcp_local *local;
struct sk_buff *skb;
u8 *miux_tlv = NULL, miux_tlv_length;
u8 *rw_tlv = NULL, rw_tlv_length, rw;
int err;
u16 size = 0;
__be16 miux;
pr_debug("Sending CC\n");
local = sock->local;
if (local == NULL)
return -ENODEV;
/* If the socket parameters are not set, use the local ones */
miux = be16_to_cpu(sock->miux) > LLCP_MAX_MIUX ?
local->miux : sock->miux;
rw = sock->rw > LLCP_MAX_RW ? local->rw : sock->rw;
miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&miux, 0,
&miux_tlv_length);
if (!miux_tlv) {
err = -ENOMEM;
goto error_tlv;
}
size += miux_tlv_length;
rw_tlv = nfc_llcp_build_tlv(LLCP_TLV_RW, &rw, 0, &rw_tlv_length);
if (!rw_tlv) {
err = -ENOMEM;
goto error_tlv;
}
size += rw_tlv_length;
skb = llcp_allocate_pdu(sock, LLCP_PDU_CC, size);
if (skb == NULL) {
err = -ENOMEM;
goto error_tlv;
}
llcp_add_tlv(skb, miux_tlv, miux_tlv_length);
llcp_add_tlv(skb, rw_tlv, rw_tlv_length);
skb_queue_tail(&local->tx_queue, skb);
err = 0;
error_tlv:
if (err)
pr_err("error %d\n", err);
kfree(miux_tlv);
kfree(rw_tlv);
return err;
}
| 169,653 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Chapters::Atom::ParseDisplay(
IMkvReader* pReader,
long long pos,
long long size)
{
if (!ExpandDisplaysArray())
return -1;
Display& d = m_displays[m_displays_count++];
d.Init();
return d.Parse(pReader, pos, size);
}
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 | long Chapters::Atom::ParseDisplay(
| 174,422 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_inter_slice_data_cavlc(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD32 uc_more_data_flag;
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2, u1_mb_idx;
UWORD32 i2_mb_skip_run;
UWORD32 u1_read_mb_type;
UWORD32 u1_mbaff;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end = 0;
UWORD32 u1_tfr_n_mb = 0;
UWORD32 u1_decode_nmb = 0;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data = ps_dec->ps_parse_mb_data;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD32 u1_mb_threshold;
WORD32 ret = OK;
/******************************************************/
/* Initialisations specific to B or P slice */
/******************************************************/
if(ps_slice->u1_slice_type == P_SLICE)
{
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
u1_mb_threshold = 5;
}
else // B_SLICE
{
u1_inter_mb_type = B_MB;
u1_deblk_mb_type = D_B_SLICE;
u1_mb_threshold = 23;
}
/******************************************************/
/* Slice Level Initialisations */
/******************************************************/
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
u1_num_mbsNby2 = 0;
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
i2_mb_skip_run = 0;
uc_more_data_flag = 1;
u1_read_mb_type = 0;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
if((!i2_mb_skip_run) && (!u1_read_mb_type))
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
{
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
}
*pu4_bitstrm_ofst = u4_bitstream_offset;
i2_mb_skip_run = ((1 << u4_ldz) + u4_word - 1);
COPYTHECONTEXT("mb_skip_run", i2_mb_skip_run);
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
u1_read_mb_type = uc_more_data_flag;
}
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
if(i2_mb_skip_run)
{
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->u1_sub_mb_num = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16;
ps_cur_mb_info->u1_cbp = 0;
{
/* Storing Skip partition info */
parse_part_params_t *ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
}
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
i2_mb_skip_run--;
}
else
{
u1_read_mb_type = 0;
/**************************************************************/
/* Macroblock Layer Begins, Decode the u1_mb_type */
/**************************************************************/
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz, u4_temp;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
*pu4_bitstrm_ofst = u4_bitstream_offset;
u4_temp = ((1 << u4_ldz) + u4_word - 1);
if(u4_temp > (UWORD32)(25 + u1_mb_threshold))
return ERROR_MB_TYPE;
u1_mb_type = u4_temp;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
}
ps_cur_mb_info->u1_mb_type = u1_mb_type;
/**************************************************************/
/* Parse Macroblock data */
/**************************************************************/
if(u1_mb_type < u1_mb_threshold)
{
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ret = ps_dec->pf_parse_inter_mb(ps_dec, ps_cur_mb_info, u1_num_mbs,
u1_num_mbsNby2);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
}
else
{
/* Storing Intra partition info */
ps_parse_mb_data->u1_num_part = 0;
ps_parse_mb_data->u1_isI_mb = 1;
if((25 + u1_mb_threshold) == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_dec->u1_qp = 0;
}
else
{
ret = ih264d_parse_imb_cavlc(
ps_dec, ps_cur_mb_info, u1_num_mbs,
(UWORD8)(u1_mb_type - u1_mb_threshold));
if(ret != OK)
return ret;
}
ps_cur_deblk_mb->u1_mb_type |= D_INTRA_MB;
}
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
}
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
u1_num_mbs++;
ps_dec->u2_total_mbs_coded++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = (!(uc_more_data_flag || i2_mb_skip_run));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
/*u1_dma_nby2mb = u1_decode_nmb ||
(u1_num_mbsNby2 == ps_dec->u1_recon_mb_grp_pair);*/
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
{
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
}
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_decode_nmb: %d", u1_decode_nmb);*/
if(u1_decode_nmb)
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
Commit Message: Decoder Update mb count after mb map is set.
Bug: 25928803
Change-Id: Iccc58a7dd1c5c6ea656dfca332cfb8dddba4de37
CWE ID: CWE-119 | WORD32 ih264d_parse_inter_slice_data_cavlc(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD32 uc_more_data_flag;
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2, u1_mb_idx;
UWORD32 i2_mb_skip_run;
UWORD32 u1_read_mb_type;
UWORD32 u1_mbaff;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end = 0;
UWORD32 u1_tfr_n_mb = 0;
UWORD32 u1_decode_nmb = 0;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data = ps_dec->ps_parse_mb_data;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD32 u1_mb_threshold;
WORD32 ret = OK;
/******************************************************/
/* Initialisations specific to B or P slice */
/******************************************************/
if(ps_slice->u1_slice_type == P_SLICE)
{
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
u1_mb_threshold = 5;
}
else // B_SLICE
{
u1_inter_mb_type = B_MB;
u1_deblk_mb_type = D_B_SLICE;
u1_mb_threshold = 23;
}
/******************************************************/
/* Slice Level Initialisations */
/******************************************************/
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
u1_num_mbsNby2 = 0;
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
i2_mb_skip_run = 0;
uc_more_data_flag = 1;
u1_read_mb_type = 0;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
if((!i2_mb_skip_run) && (!u1_read_mb_type))
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
{
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
}
*pu4_bitstrm_ofst = u4_bitstream_offset;
i2_mb_skip_run = ((1 << u4_ldz) + u4_word - 1);
COPYTHECONTEXT("mb_skip_run", i2_mb_skip_run);
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
u1_read_mb_type = uc_more_data_flag;
}
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
if(i2_mb_skip_run)
{
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->u1_sub_mb_num = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16;
ps_cur_mb_info->u1_cbp = 0;
{
/* Storing Skip partition info */
parse_part_params_t *ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
}
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
i2_mb_skip_run--;
}
else
{
u1_read_mb_type = 0;
/**************************************************************/
/* Macroblock Layer Begins, Decode the u1_mb_type */
/**************************************************************/
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz, u4_temp;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
*pu4_bitstrm_ofst = u4_bitstream_offset;
u4_temp = ((1 << u4_ldz) + u4_word - 1);
if(u4_temp > (UWORD32)(25 + u1_mb_threshold))
return ERROR_MB_TYPE;
u1_mb_type = u4_temp;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
}
ps_cur_mb_info->u1_mb_type = u1_mb_type;
/**************************************************************/
/* Parse Macroblock data */
/**************************************************************/
if(u1_mb_type < u1_mb_threshold)
{
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ret = ps_dec->pf_parse_inter_mb(ps_dec, ps_cur_mb_info, u1_num_mbs,
u1_num_mbsNby2);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
}
else
{
/* Storing Intra partition info */
ps_parse_mb_data->u1_num_part = 0;
ps_parse_mb_data->u1_isI_mb = 1;
if((25 + u1_mb_threshold) == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_dec->u1_qp = 0;
}
else
{
ret = ih264d_parse_imb_cavlc(
ps_dec, ps_cur_mb_info, u1_num_mbs,
(UWORD8)(u1_mb_type - u1_mb_threshold));
if(ret != OK)
return ret;
}
ps_cur_deblk_mb->u1_mb_type |= D_INTRA_MB;
}
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
}
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
u1_num_mbs++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = (!(uc_more_data_flag || i2_mb_skip_run));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
/*u1_dma_nby2mb = u1_decode_nmb ||
(u1_num_mbsNby2 == ps_dec->u1_recon_mb_grp_pair);*/
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
{
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
}
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_decode_nmb: %d", u1_decode_nmb);*/
if(u1_decode_nmb)
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
| 173,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Cues::Find(
long long time_ns,
const Track* pTrack,
const CuePoint*& pCP,
const CuePoint::TrackPosition*& pTP) const
{
assert(time_ns >= 0);
assert(pTrack);
#if 0
LoadCuePoint(); //establish invariant
assert(m_cue_points);
assert(m_count > 0);
CuePoint** const ii = m_cue_points;
CuePoint** i = ii;
CuePoint** const jj = ii + m_count + m_preload_count;
CuePoint** j = jj;
pCP = *i;
assert(pCP);
if (time_ns <= pCP->GetTime(m_pSegment))
{
pTP = pCP->Find(pTrack);
return (pTP != NULL);
}
IMkvReader* const pReader = m_pSegment->m_pReader;
while (i < j)
{
CuePoint** const k = i + (j - i) / 2;
assert(k < jj);
CuePoint* const pCP = *k;
assert(pCP);
pCP->Load(pReader);
const long long t = pCP->GetTime(m_pSegment);
if (t <= time_ns)
i = k + 1;
else
j = k;
assert(i <= j);
}
assert(i == j);
assert(i <= jj);
assert(i > ii);
pCP = *--i;
assert(pCP);
assert(pCP->GetTime(m_pSegment) <= time_ns);
#else
if (m_cue_points == NULL)
return false;
if (m_count == 0)
return false;
CuePoint** const ii = m_cue_points;
CuePoint** i = ii;
CuePoint** const jj = ii + m_count;
CuePoint** j = jj;
pCP = *i;
assert(pCP);
if (time_ns <= pCP->GetTime(m_pSegment))
{
pTP = pCP->Find(pTrack);
return (pTP != NULL);
}
while (i < j)
{
CuePoint** const k = i + (j - i) / 2;
assert(k < jj);
CuePoint* const pCP = *k;
assert(pCP);
const long long t = pCP->GetTime(m_pSegment);
if (t <= time_ns)
i = k + 1;
else
j = k;
assert(i <= j);
}
assert(i == j);
assert(i <= jj);
assert(i > ii);
pCP = *--i;
assert(pCP);
assert(pCP->GetTime(m_pSegment) <= time_ns);
#endif
pTP = pCP->Find(pTrack);
return (pTP != NULL);
}
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 | bool Cues::Find(
bool Cues::Find(long long time_ns, const Track* pTrack, const CuePoint*& pCP,
const CuePoint::TrackPosition*& pTP) const {
assert(time_ns >= 0);
assert(pTrack);
#if 0
LoadCuePoint(); //establish invariant
assert(m_cue_points);
assert(m_count > 0);
CuePoint** const ii = m_cue_points;
CuePoint** i = ii;
CuePoint** const jj = ii + m_count + m_preload_count;
CuePoint** j = jj;
pCP = *i;
assert(pCP);
if (time_ns <= pCP->GetTime(m_pSegment))
{
pTP = pCP->Find(pTrack);
return (pTP != NULL);
}
IMkvReader* const pReader = m_pSegment->m_pReader;
while (i < j)
{
CuePoint** const k = i + (j - i) / 2;
assert(k < jj);
CuePoint* const pCP = *k;
assert(pCP);
pCP->Load(pReader);
const long long t = pCP->GetTime(m_pSegment);
if (t <= time_ns)
i = k + 1;
else
j = k;
assert(i <= j);
}
assert(i == j);
assert(i <= jj);
assert(i > ii);
pCP = *--i;
assert(pCP);
assert(pCP->GetTime(m_pSegment) <= time_ns);
#else
if (m_cue_points == NULL)
return false;
if (m_count == 0)
return false;
CuePoint** const ii = m_cue_points;
CuePoint** i = ii;
CuePoint** const jj = ii + m_count;
CuePoint** j = jj;
pCP = *i;
assert(pCP);
if (time_ns <= pCP->GetTime(m_pSegment)) {
pTP = pCP->Find(pTrack);
return (pTP != NULL);
| 174,277 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(source);
DCHECK(!sink_);
DCHECK(!source_);
sink_ = AudioDeviceFactory::NewOutputDevice();
DCHECK(sink_);
int sample_rate = GetAudioOutputSampleRate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate",
sample_rate, media::kUnexpectedAudioSampleRate);
if (std::find(&kValidOutputRates[0],
&kValidOutputRates[0] + arraysize(kValidOutputRates),
sample_rate) ==
&kValidOutputRates[arraysize(kValidOutputRates)]) {
DLOG(ERROR) << sample_rate << " is not a supported output rate.";
return false;
}
media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO;
int buffer_size = 0;
#if defined(OS_WIN)
channel_layout = media::CHANNEL_LAYOUT_STEREO;
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 2 * 440;
}
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
buffer_size = 3 * buffer_size;
DLOG(WARNING) << "Extending the output buffer size by a factor of three "
<< "since Windows XP has been detected.";
}
#elif defined(OS_MACOSX)
channel_layout = media::CHANNEL_LAYOUT_MONO;
if (sample_rate == 48000) {
buffer_size = 480;
} else {
buffer_size = 440;
}
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
channel_layout = media::CHANNEL_LAYOUT_MONO;
buffer_size = 480;
#else
DLOG(ERROR) << "Unsupported platform";
return false;
#endif
params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
sample_rate, 16, buffer_size);
buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]);
source_ = source;
source->SetRenderFormat(params_);
sink_->Initialize(params_, this);
sink_->SetSourceRenderView(source_render_view_id_);
sink_->Start();
state_ = PAUSED;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
buffer_size, kUnexpectedAudioBufferSize);
AddHistogramFramesPerBuffer(buffer_size);
return true;
}
Commit Message: Avoids crash in WebRTC audio clients for 96kHz render rate on Mac OSX.
TBR=xians
BUG=166523
TEST=Misc set of WebRTC audio clients on Mac.
Review URL: https://codereview.chromium.org/11773017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175323 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(source);
DCHECK(!sink_);
DCHECK(!source_);
sink_ = AudioDeviceFactory::NewOutputDevice();
DCHECK(sink_);
int sample_rate = GetAudioOutputSampleRate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate",
sample_rate, media::kUnexpectedAudioSampleRate);
if (std::find(&kValidOutputRates[0],
&kValidOutputRates[0] + arraysize(kValidOutputRates),
sample_rate) ==
&kValidOutputRates[arraysize(kValidOutputRates)]) {
DLOG(ERROR) << sample_rate << " is not a supported output rate.";
return false;
}
media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO;
int buffer_size = 0;
#if defined(OS_WIN)
channel_layout = media::CHANNEL_LAYOUT_STEREO;
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 2 * 440;
}
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
buffer_size = 3 * buffer_size;
DLOG(WARNING) << "Extending the output buffer size by a factor of three "
<< "since Windows XP has been detected.";
}
#elif defined(OS_MACOSX)
channel_layout = media::CHANNEL_LAYOUT_MONO;
// frame size to use for 96kHz, 48kHz and 44.1kHz.
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 440;
}
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
channel_layout = media::CHANNEL_LAYOUT_MONO;
buffer_size = 480;
#else
DLOG(ERROR) << "Unsupported platform";
return false;
#endif
params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
sample_rate, 16, buffer_size);
buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]);
source_ = source;
source->SetRenderFormat(params_);
sink_->Initialize(params_, this);
sink_->SetSourceRenderView(source_render_view_id_);
sink_->Start();
state_ = PAUSED;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
buffer_size, kUnexpectedAudioBufferSize);
AddHistogramFramesPerBuffer(buffer_size);
return true;
}
| 171,502 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PluginChannel::OnChannelConnected(int32 peer_pid) {
base::ProcessHandle handle;
if (!base::OpenProcessHandle(peer_pid, &handle)) {
NOTREACHED();
}
renderer_handle_ = handle;
NPChannelBase::OnChannelConnected(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 PluginChannel::OnChannelConnected(int32 peer_pid) {
| 170,948 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Cluster::GetElementSize() const
{
return m_element_size;
}
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 | long long Cluster::GetElementSize() const
| 174,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 16;
fwd_txfm_ref = fht16x16_ref;
}
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() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
bit_depth_ = GET_PARAM(3);
pitch_ = 16;
fwd_txfm_ref = fht16x16_ref;
inv_txfm_ref = iht16x16_ref;
mask_ = (1 << bit_depth_) - 1;
#if CONFIG_VP9_HIGHBITDEPTH
switch (bit_depth_) {
case VPX_BITS_10:
inv_txfm_ref = iht16x16_10;
break;
case VPX_BITS_12:
inv_txfm_ref = iht16x16_12;
break;
default:
inv_txfm_ref = iht16x16_ref;
break;
}
#else
inv_txfm_ref = iht16x16_ref;
#endif
}
| 174,528 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionTtsController::Stop() {
if (current_utterance_ && !current_utterance_->extension_id().empty()) {
current_utterance_->profile()->GetExtensionEventRouter()->
DispatchEventToExtension(
current_utterance_->extension_id(),
events::kOnStop,
"[]",
current_utterance_->profile(),
GURL());
} else {
GetPlatformImpl()->clear_error();
GetPlatformImpl()->StopSpeaking();
}
if (current_utterance_)
current_utterance_->set_error(kSpeechInterruptedError);
FinishCurrentUtterance();
ClearUtteranceQueue();
}
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 ExtensionTtsController::Stop() {
double volume = 1.0;
if (options->HasKey(constants::kVolumeKey)) {
EXTENSION_FUNCTION_VALIDATE(
options->GetDouble(constants::kVolumeKey, &volume));
if (volume < 0.0 || volume > 1.0) {
error_ = constants::kErrorInvalidVolume;
return false;
}
}
| 170,391 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin;
if (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) {
return NULL;
}
memset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t));
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new();
if (!r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
Commit Message: Fix #12374 - oobread crash in truncated dyldcache ##bin
CWE ID: CWE-125 | struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin = R_NEW0 (struct r_bin_dyldcache_obj_t);
if (!bin) {
return NULL;
}
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new ();
if (!bin->b || !r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
| 168,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
unsigned char *pt;
unsigned char l, lg, n = 0;
int fac_national_digis_received = 0;
do {
switch (*p & 0xC0) {
case 0x00:
p += 2;
n += 2;
len -= 2;
break;
case 0x40:
if (*p == FAC_NATIONAL_RAND)
facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);
p += 3;
n += 3;
len -= 3;
break;
case 0x80:
p += 4;
n += 4;
len -= 4;
break;
case 0xC0:
l = p[1];
if (*p == FAC_NATIONAL_DEST_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);
facilities->source_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_SRC_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);
facilities->dest_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_FAIL_CALL) {
memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_FAIL_ADD) {
memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_DIGIS) {
fac_national_digis_received = 1;
facilities->source_ndigis = 0;
facilities->dest_ndigis = 0;
for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {
if (pt[6] & AX25_HBIT)
memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);
else
memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);
}
}
p += l + 2;
n += l + 2;
len -= l + 2;
break;
}
} while (*p != 0x00 && len > 0);
return n;
}
Commit Message: ROSE: prevent heap corruption with bad facilities
When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for
a remote host to provide more digipeaters than expected, resulting in
heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and
abort facilities parsing on failure.
Additionally, when parsing the FAC_CCITT_DEST_NSAP and
FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length
of less than 10, resulting in an underflow in a memcpy size, causing a
kernel panic due to massive heap corruption. A length of greater than
20 results in a stack overflow of the callsign array. Abort facilities
parsing on these invalid length values.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
unsigned char *pt;
unsigned char l, lg, n = 0;
int fac_national_digis_received = 0;
do {
switch (*p & 0xC0) {
case 0x00:
p += 2;
n += 2;
len -= 2;
break;
case 0x40:
if (*p == FAC_NATIONAL_RAND)
facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);
p += 3;
n += 3;
len -= 3;
break;
case 0x80:
p += 4;
n += 4;
len -= 4;
break;
case 0xC0:
l = p[1];
if (*p == FAC_NATIONAL_DEST_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);
facilities->source_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_SRC_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);
facilities->dest_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_FAIL_CALL) {
memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_FAIL_ADD) {
memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_DIGIS) {
fac_national_digis_received = 1;
facilities->source_ndigis = 0;
facilities->dest_ndigis = 0;
for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {
if (pt[6] & AX25_HBIT) {
if (facilities->dest_ndigis >= ROSE_MAX_DIGIS)
return -1;
memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);
} else {
if (facilities->source_ndigis >= ROSE_MAX_DIGIS)
return -1;
memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);
}
}
}
p += l + 2;
n += l + 2;
len -= l + 2;
break;
}
} while (*p != 0x00 && len > 0);
return n;
}
| 165,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mptsas_process_scsi_io_request(MPTSASState *s,
MPIMsgSCSIIORequest *scsi_io,
hwaddr addr)
{
MPTSASRequest *req;
MPIMsgSCSIIOReply reply;
SCSIDevice *sdev;
int status;
mptsas_fix_scsi_io_endianness(scsi_io);
trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN[1], scsi_io->DataLength);
status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN, &sdev);
if (status) {
goto bad;
}
req = g_new(MPTSASRequest, 1);
QTAILQ_INSERT_TAIL(&s->pending, req, next);
req->scsi_io = *scsi_io;
req->dev = s;
status = mptsas_build_sgl(s, req, addr);
if (status) {
goto free_bad;
}
if (req->qsg.size < scsi_io->DataLength) {
trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength,
req->qsg.size);
status = MPI_IOCSTATUS_INVALID_SGL;
goto free_bad;
}
req->sreq = scsi_req_new(sdev, scsi_io->MsgContext,
scsi_io->LUN[1], scsi_io->CDB, req);
if (req->sreq->cmd.xfer > scsi_io->DataLength) {
goto overrun;
}
switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) {
case MPI_SCSIIO_CONTROL_NODATATRANSFER:
if (req->sreq->cmd.mode != SCSI_XFER_NONE) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_WRITE:
if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_READ:
if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) {
goto overrun;
}
break;
}
if (scsi_req_enqueue(req->sreq)) {
scsi_req_continue(req->sreq);
}
return 0;
overrun:
trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer,
scsi_io->DataLength);
status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN;
free_bad:
mptsas_free_request(req);
bad:
memset(&reply, 0, sizeof(reply));
reply.TargetID = scsi_io->TargetID;
reply.Bus = scsi_io->Bus;
reply.MsgLength = sizeof(reply) / 4;
reply.Function = scsi_io->Function;
reply.CDBLength = scsi_io->CDBLength;
reply.SenseBufferLength = scsi_io->SenseBufferLength;
reply.MsgContext = scsi_io->MsgContext;
reply.SCSIState = MPI_SCSI_STATE_NO_SCSI_STATUS;
reply.IOCStatus = status;
mptsas_fix_scsi_io_reply_endianness(&reply);
mptsas_reply(s, (MPIDefaultReply *)&reply);
return 0;
}
Commit Message:
CWE ID: CWE-787 | static int mptsas_process_scsi_io_request(MPTSASState *s,
MPIMsgSCSIIORequest *scsi_io,
hwaddr addr)
{
MPTSASRequest *req;
MPIMsgSCSIIOReply reply;
SCSIDevice *sdev;
int status;
mptsas_fix_scsi_io_endianness(scsi_io);
trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN[1], scsi_io->DataLength);
status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN, &sdev);
if (status) {
goto bad;
}
req = g_new0(MPTSASRequest, 1);
QTAILQ_INSERT_TAIL(&s->pending, req, next);
req->scsi_io = *scsi_io;
req->dev = s;
status = mptsas_build_sgl(s, req, addr);
if (status) {
goto free_bad;
}
if (req->qsg.size < scsi_io->DataLength) {
trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength,
req->qsg.size);
status = MPI_IOCSTATUS_INVALID_SGL;
goto free_bad;
}
req->sreq = scsi_req_new(sdev, scsi_io->MsgContext,
scsi_io->LUN[1], scsi_io->CDB, req);
if (req->sreq->cmd.xfer > scsi_io->DataLength) {
goto overrun;
}
switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) {
case MPI_SCSIIO_CONTROL_NODATATRANSFER:
if (req->sreq->cmd.mode != SCSI_XFER_NONE) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_WRITE:
if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_READ:
if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) {
goto overrun;
}
break;
}
if (scsi_req_enqueue(req->sreq)) {
scsi_req_continue(req->sreq);
}
return 0;
overrun:
trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer,
scsi_io->DataLength);
status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN;
free_bad:
mptsas_free_request(req);
bad:
memset(&reply, 0, sizeof(reply));
reply.TargetID = scsi_io->TargetID;
reply.Bus = scsi_io->Bus;
reply.MsgLength = sizeof(reply) / 4;
reply.Function = scsi_io->Function;
reply.CDBLength = scsi_io->CDBLength;
reply.SenseBufferLength = scsi_io->SenseBufferLength;
reply.MsgContext = scsi_io->MsgContext;
reply.SCSIState = MPI_SCSI_STATE_NO_SCSI_STATUS;
reply.IOCStatus = status;
mptsas_fix_scsi_io_reply_endianness(&reply);
mptsas_reply(s, (MPIDefaultReply *)&reply);
return 0;
}
| 164,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintSettingsInitializerWin::InitPrintSettings(
HDC hdc,
const DEVMODE& dev_mode,
const PageRanges& new_ranges,
const std::wstring& new_device_name,
bool print_selection_only,
PrintSettings* print_settings) {
DCHECK(hdc);
DCHECK(print_settings);
print_settings->set_printer_name(dev_mode.dmDeviceName);
print_settings->set_device_name(new_device_name);
print_settings->ranges = new_ranges;
print_settings->set_landscape(dev_mode.dmOrientation == DMORIENT_LANDSCAPE);
print_settings->selection_only = print_selection_only;
int dpi = GetDeviceCaps(hdc, LOGPIXELSX);
print_settings->set_dpi(dpi);
const int kAlphaCaps = SB_CONST_ALPHA | SB_PIXEL_ALPHA;
print_settings->set_supports_alpha_blend(
(GetDeviceCaps(hdc, SHADEBLENDCAPS) & kAlphaCaps) == kAlphaCaps);
DCHECK_EQ(dpi, GetDeviceCaps(hdc, LOGPIXELSY));
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0);
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0);
gfx::Size physical_size_device_units(GetDeviceCaps(hdc, PHYSICALWIDTH),
GetDeviceCaps(hdc, PHYSICALHEIGHT));
gfx::Rect printable_area_device_units(GetDeviceCaps(hdc, PHYSICALOFFSETX),
GetDeviceCaps(hdc, PHYSICALOFFSETY),
GetDeviceCaps(hdc, HORZRES),
GetDeviceCaps(hdc, VERTRES));
print_settings->SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PrintSettingsInitializerWin::InitPrintSettings(
HDC hdc,
const DEVMODE& dev_mode,
const PageRanges& new_ranges,
const std::wstring& new_device_name,
bool print_selection_only,
PrintSettings* print_settings) {
DCHECK(hdc);
DCHECK(print_settings);
print_settings->set_printer_name(dev_mode.dmDeviceName);
print_settings->set_device_name(new_device_name);
print_settings->ranges = const_cast<PageRanges&>(new_ranges);
print_settings->set_landscape(dev_mode.dmOrientation == DMORIENT_LANDSCAPE);
print_settings->selection_only = print_selection_only;
int dpi = GetDeviceCaps(hdc, LOGPIXELSX);
print_settings->set_dpi(dpi);
const int kAlphaCaps = SB_CONST_ALPHA | SB_PIXEL_ALPHA;
print_settings->set_supports_alpha_blend(
(GetDeviceCaps(hdc, SHADEBLENDCAPS) & kAlphaCaps) == kAlphaCaps);
DCHECK_EQ(dpi, GetDeviceCaps(hdc, LOGPIXELSY));
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0);
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0);
gfx::Size physical_size_device_units(GetDeviceCaps(hdc, PHYSICALWIDTH),
GetDeviceCaps(hdc, PHYSICALHEIGHT));
gfx::Rect printable_area_device_units(GetDeviceCaps(hdc, PHYSICALOFFSETX),
GetDeviceCaps(hdc, PHYSICALOFFSETY),
GetDeviceCaps(hdc, HORZRES),
GetDeviceCaps(hdc, VERTRES));
print_settings->SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
}
| 170,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE omx_video::allocate_input_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned i = 0;
DEBUG_PRINT_HIGH("allocate_input_buffer()::");
if (bytes != m_sInPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]",
(unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_inp_mem_ptr) {
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual);
m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \
calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual);
if (m_inp_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr");
return OMX_ErrorInsufficientResources;
}
DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr);
m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual);
if (m_pInput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual);
if (m_pInput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
m_pInput_pmem[i].fd = -1;
#ifdef USE_ION
m_pInput_ion[i].ion_device_fd =-1;
m_pInput_ion[i].fd_ion_data.fd =-1;
m_pInput_ion[i].ion_alloc_data.handle = 0;
#endif
}
}
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_inp_bm_count,i)) {
break;
}
}
if (i < m_sInPortDef.nBufferCountActual) {
*bufferHdr = (m_inp_mem_ptr + i);
(*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE);
(*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION;
(*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize;
(*bufferHdr)->pAppPrivate = appData;
(*bufferHdr)->nInputPortIndex = PORT_INDEX_IN;
(*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i];
#ifdef USE_ION
#ifdef _MSM8974_
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,0);
#else
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pInput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd;
#else
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pInput_pmem[i].fd == 0) {
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pInput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pInput_pmem[i].size = m_sInPortDef.nBufferSize;
m_pInput_pmem[i].offset = 0;
m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pInput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pInput_pmem[i].fd,0);
if (m_pInput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno);
close(m_pInput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
} else {
m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
(*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*);
}
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer;
DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer);
BITMASK_SET(&m_inp_bm_count,i);
if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call"
"for index [%d]", i);
eRet = OMX_ErrorInsufficientResources;
}
return eRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200 | OMX_ERRORTYPE omx_video::allocate_input_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned i = 0;
DEBUG_PRINT_HIGH("allocate_input_buffer()::");
if (bytes != m_sInPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]",
(unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_inp_mem_ptr) {
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual);
m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \
calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual);
if (m_inp_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr");
return OMX_ErrorInsufficientResources;
}
DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr);
m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual);
if (m_pInput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual);
if (m_pInput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
m_pInput_pmem[i].fd = -1;
#ifdef USE_ION
m_pInput_ion[i].ion_device_fd =-1;
m_pInput_ion[i].fd_ion_data.fd =-1;
m_pInput_ion[i].ion_alloc_data.handle = 0;
#endif
}
}
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_inp_bm_count,i)) {
break;
}
}
if (i < m_sInPortDef.nBufferCountActual) {
*bufferHdr = (m_inp_mem_ptr + i);
(*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE);
(*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION;
(*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize;
(*bufferHdr)->pAppPrivate = appData;
(*bufferHdr)->nInputPortIndex = PORT_INDEX_IN;
(*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i];
#ifdef USE_ION
#ifdef _MSM8974_
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,0);
#else
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pInput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd;
#else
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pInput_pmem[i].fd == 0) {
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pInput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pInput_pmem[i].size = m_sInPortDef.nBufferSize;
m_pInput_pmem[i].offset = 0;
m_pInput_pmem[i].buffer = NULL;
if(!secure_session) {
m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pInput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pInput_pmem[i].fd,0);
if (m_pInput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno);
m_pInput_pmem[i].buffer = NULL;
close(m_pInput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
} else {
m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
if (m_pInput_pmem[i].buffer == NULL) {
DEBUG_PRINT_ERROR("%s: failed to allocate native-handle", __func__);
return OMX_ErrorInsufficientResources;
}
(*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*);
}
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer;
DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer);
BITMASK_SET(&m_inp_bm_count,i);
if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call"
"for index [%d]", i);
eRet = OMX_ErrorInsufficientResources;
}
return eRet;
}
| 173,501 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PropertyTreeState LayerState() {
DEFINE_STATIC_REF(
TransformPaintPropertyNode, transform,
CreateTransform(TransformPaintPropertyNode::Root(),
TransformationMatrix().Translate(123, 456),
FloatPoint3D(1, 2, 3)));
DEFINE_STATIC_REF(ClipPaintPropertyNode, clip,
CreateClip(ClipPaintPropertyNode::Root(), transform,
FloatRoundedRect(12, 34, 56, 78)));
DEFINE_STATIC_REF(
EffectPaintPropertyNode, effect,
EffectPaintPropertyNode::Create(
EffectPaintPropertyNode::Root(),
EffectPaintPropertyNode::State{
transform, clip, kColorFilterLuminanceToAlpha,
CompositorFilterOperations(), 0.789f, SkBlendMode::kSrcIn}));
return PropertyTreeState(transform, clip, effect);
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | PropertyTreeState LayerState() {
if (!layer_transform_) {
layer_transform_ =
CreateTransform(t0(), TransformationMatrix().Translate(123, 456),
FloatPoint3D(1, 2, 3));
layer_clip_ = CreateClip(c0(), layer_transform_.get(),
FloatRoundedRect(12, 34, 56, 78));
layer_effect_ = EffectPaintPropertyNode::Create(
e0(), EffectPaintPropertyNode::State{
layer_transform_.get(), layer_clip_.get(),
kColorFilterLuminanceToAlpha, CompositorFilterOperations(),
0.789f, SkBlendMode::kSrcIn});
}
return PropertyTreeState(layer_transform_.get(), layer_clip_.get(),
layer_effect_.get());
}
| 171,809 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(snmp, __construct)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1, *a2;
int a1_len, a2_len;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
long version = SNMP_DEFAULT_VERSION;
int argc = ZEND_NUM_ARGS();
zend_error_handling error_handling;
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
switch(version) {
case SNMP_VERSION_1:
case SNMP_VERSION_2c:
case SNMP_VERSION_3:
break;
default:
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC);
return;
}
/* handle re-open of snmp session */
if (snmp_object->session) {
netsnmp_session_free(&(snmp_object->session));
}
if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) {
return;
}
snmp_object->max_oids = 0;
snmp_object->valueretrieval = SNMP_G(valueretrieval);
snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
snmp_object->oid_increasing_check = TRUE;
snmp_object->exceptions_enabled = 0;
}
Commit Message:
CWE ID: CWE-416 | PHP_METHOD(snmp, __construct)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1, *a2;
int a1_len, a2_len;
long timeout = SNMP_DEFAULT_TIMEOUT;
long retries = SNMP_DEFAULT_RETRIES;
long version = SNMP_DEFAULT_VERSION;
int argc = ZEND_NUM_ARGS();
zend_error_handling error_handling;
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
switch(version) {
case SNMP_VERSION_1:
case SNMP_VERSION_2c:
case SNMP_VERSION_3:
break;
default:
zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC);
return;
}
/* handle re-open of snmp session */
if (snmp_object->session) {
netsnmp_session_free(&(snmp_object->session));
}
if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) {
return;
}
snmp_object->max_oids = 0;
snmp_object->valueretrieval = SNMP_G(valueretrieval);
snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
snmp_object->oid_increasing_check = TRUE;
snmp_object->exceptions_enabled = 0;
}
| 164,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RTCSessionDescriptionRequestFailedTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCSessionDescriptionRequest& request)
: MethodTask<MockWebRTCPeerConnectionHandler>(object)
, m_request(request)
{
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | RTCSessionDescriptionRequestFailedTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCSessionDescriptionRequest& request)
| 170,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
do {
entry = entry->next();
} while (entry != lru_list_.end() && entry->value()->parent() == to_doom);
if (!to_doom->InUse())
to_doom->Doom();
}
}
Commit Message: [MemCache] Fix bug while iterating LRU list in range doom
This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919
but on explicit mass-erase rather than eviction.
Thanks to nedwilliamson@ (on gmail) for the report and testcase.
Bug: 831963
Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102
Reviewed-on: https://chromium-review.googlesource.com/1014023
Commit-Queue: Maks Orlovich <[email protected]>
Reviewed-by: Josh Karlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#551205}
CWE ID: CWE-416 | void MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
entry = NextSkippingChildren(lru_list_, entry);
if (!to_doom->InUse())
to_doom->Doom();
}
}
| 173,258 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len, i;
int insn_processed = 0;
bool do_print_state = false;
env->prev_linfo = NULL;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
state->curframe = 0;
state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
if (!state->frame[0]) {
kfree(state);
return -ENOMEM;
}
env->cur_state = state;
init_func_state(env, state->frame[0],
BPF_MAIN_FUNC /* callsite */,
0 /* frameno */,
0 /* subprogno, zero == main subprog */);
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (env->insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
env->insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[env->insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, env->insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d: safe\n",
env->prev_insn_idx, env->insn_idx);
else
verbose(env, "%d: safe\n", env->insn_idx);
}
goto process_bpf_exit;
}
if (signal_pending(current))
return -EAGAIN;
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", env->insn_idx);
else
verbose(env, "\nfrom %d to %d:",
env->prev_insn_idx, env->insn_idx);
print_verifier_state(env, state->frame[state->curframe]);
do_print_state = false;
}
if (env->log.level) {
const struct bpf_insn_cbs cbs = {
.cb_print = verbose,
.private_data = env,
};
verbose_linfo(env, env->insn_idx, "; ");
verbose(env, "%d: ", env->insn_idx);
print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
}
if (bpf_prog_is_dev_bound(env->prog->aux)) {
err = bpf_prog_offload_verify_insn(env, env->insn_idx,
env->prev_insn_idx);
if (err)
return err;
}
regs = cur_regs(env);
env->insn_aux_data[env->insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, env->insn_idx, insn->src_reg,
insn->off, BPF_SIZE(insn->code),
BPF_READ, insn->dst_reg, false);
if (err)
return err;
prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, env->insn_idx, insn);
if (err)
return err;
env->insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, env->insn_idx, insn->dst_reg,
insn->off, BPF_SIZE(insn->code),
BPF_WRITE, insn->src_reg, false);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_ctx_reg(env, insn->dst_reg)) {
verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
insn->dst_reg,
reg_type_str[reg_state(env, insn->dst_reg)->type]);
return -EACCES;
}
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, env->insn_idx, insn->dst_reg,
insn->off, BPF_SIZE(insn->code),
BPF_WRITE, -1, false);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
(insn->src_reg != BPF_REG_0 &&
insn->src_reg != BPF_PSEUDO_CALL) ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
if (insn->src_reg == BPF_PSEUDO_CALL)
err = check_func_call(env, insn, &env->insn_idx);
else
err = check_helper_call(env, insn->imm, env->insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
env->insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
if (state->curframe) {
/* exit from nested function */
env->prev_insn_idx = env->insn_idx;
err = prepare_func_exit(env, &env->insn_idx);
if (err)
return err;
do_print_state = true;
continue;
}
err = check_reference_leak(env);
if (err)
return err;
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &env->prev_insn_idx,
&env->insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &env->insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
env->insn_idx++;
env->insn_aux_data[env->insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
env->insn_idx++;
}
verbose(env, "processed %d insns (limit %d), stack depth ",
insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
for (i = 0; i < env->subprog_cnt; i++) {
u32 depth = env->subprog_info[i].stack_depth;
verbose(env, "%d", depth);
if (i + 1 < env->subprog_cnt)
verbose(env, "+");
}
verbose(env, "\n");
env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
return 0;
}
Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic
Jann reported that the original commit back in b2157399cc98
("bpf: prevent out-of-bounds speculation") was not sufficient
to stop CPU from speculating out of bounds memory access:
While b2157399cc98 only focussed on masking array map access
for unprivileged users for tail calls and data access such
that the user provided index gets sanitized from BPF program
and syscall side, there is still a more generic form affected
from BPF programs that applies to most maps that hold user
data in relation to dynamic map access when dealing with
unknown scalars or "slow" known scalars as access offset, for
example:
- Load a map value pointer into R6
- Load an index into R7
- Do a slow computation (e.g. with a memory dependency) that
loads a limit into R8 (e.g. load the limit from a map for
high latency, then mask it to make the verifier happy)
- Exit if R7 >= R8 (mispredicted branch)
- Load R0 = R6[R7]
- Load R0 = R6[R0]
For unknown scalars there are two options in the BPF verifier
where we could derive knowledge from in order to guarantee
safe access to the memory: i) While </>/<=/>= variants won't
allow to derive any lower or upper bounds from the unknown
scalar where it would be safe to add it to the map value
pointer, it is possible through ==/!= test however. ii) another
option is to transform the unknown scalar into a known scalar,
for example, through ALU ops combination such as R &= <imm>
followed by R |= <imm> or any similar combination where the
original information from the unknown scalar would be destroyed
entirely leaving R with a constant. The initial slow load still
precedes the latter ALU ops on that register, so the CPU
executes speculatively from that point. Once we have the known
scalar, any compare operation would work then. A third option
only involving registers with known scalars could be crafted
as described in [0] where a CPU port (e.g. Slow Int unit)
would be filled with many dependent computations such that
the subsequent condition depending on its outcome has to wait
for evaluation on its execution port and thereby executing
speculatively if the speculated code can be scheduled on a
different execution port, or any other form of mistraining
as described in [1], for example. Given this is not limited
to only unknown scalars, not only map but also stack access
is affected since both is accessible for unprivileged users
and could potentially be used for out of bounds access under
speculation.
In order to prevent any of these cases, the verifier is now
sanitizing pointer arithmetic on the offset such that any
out of bounds speculation would be masked in a way where the
pointer arithmetic result in the destination register will
stay unchanged, meaning offset masked into zero similar as
in array_index_nospec() case. With regards to implementation,
there are three options that were considered: i) new insn
for sanitation, ii) push/pop insn and sanitation as inlined
BPF, iii) reuse of ax register and sanitation as inlined BPF.
Option i) has the downside that we end up using from reserved
bits in the opcode space, but also that we would require
each JIT to emit masking as native arch opcodes meaning
mitigation would have slow adoption till everyone implements
it eventually which is counter-productive. Option ii) and iii)
have both in common that a temporary register is needed in
order to implement the sanitation as inlined BPF since we
are not allowed to modify the source register. While a push /
pop insn in ii) would be useful to have in any case, it
requires once again that every JIT needs to implement it
first. While possible, amount of changes needed would also
be unsuitable for a -stable patch. Therefore, the path which
has fewer changes, less BPF instructions for the mitigation
and does not require anything to be changed in the JITs is
option iii) which this work is pursuing. The ax register is
already mapped to a register in all JITs (modulo arm32 where
it's mapped to stack as various other BPF registers there)
and used in constant blinding for JITs-only so far. It can
be reused for verifier rewrites under certain constraints.
The interpreter's tmp "register" has therefore been remapped
into extending the register set with hidden ax register and
reusing that for a number of instructions that needed the
prior temporary variable internally (e.g. div, mod). This
allows for zero increase in stack space usage in the interpreter,
and enables (restricted) generic use in rewrites otherwise as
long as such a patchlet does not make use of these instructions.
The sanitation mask is dynamic and relative to the offset the
map value or stack pointer currently holds.
There are various cases that need to be taken under consideration
for the masking, e.g. such operation could look as follows:
ptr += val or val += ptr or ptr -= val. Thus, the value to be
sanitized could reside either in source or in destination
register, and the limit is different depending on whether
the ALU op is addition or subtraction and depending on the
current known and bounded offset. The limit is derived as
follows: limit := max_value_size - (smin_value + off). For
subtraction: limit := umax_value + off. This holds because
we do not allow any pointer arithmetic that would
temporarily go out of bounds or would have an unknown
value with mixed signed bounds where it is unclear at
verification time whether the actual runtime value would
be either negative or positive. For example, we have a
derived map pointer value with constant offset and bounded
one, so limit based on smin_value works because the verifier
requires that statically analyzed arithmetic on the pointer
must be in bounds, and thus it checks if resulting
smin_value + off and umax_value + off is still within map
value bounds at time of arithmetic in addition to time of
access. Similarly, for the case of stack access we derive
the limit as follows: MAX_BPF_STACK + off for subtraction
and -off for the case of addition where off := ptr_reg->off +
ptr_reg->var_off.value. Subtraction is a special case for
the masking which can be in form of ptr += -val, ptr -= -val,
or ptr -= val. In the first two cases where we know that
the value is negative, we need to temporarily negate the
value in order to do the sanitation on a positive value
where we later swap the ALU op, and restore original source
register if the value was in source.
The sanitation of pointer arithmetic alone is still not fully
sufficient as is, since a scenario like the following could
happen ...
PTR += 0x1000 (e.g. K-based imm)
PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON
PTR += 0x1000
PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON
[...]
... which under speculation could end up as ...
PTR += 0x1000
PTR -= 0 [ truncated by mitigation ]
PTR += 0x1000
PTR -= 0 [ truncated by mitigation ]
[...]
... and therefore still access out of bounds. To prevent such
case, the verifier is also analyzing safety for potential out
of bounds access under speculative execution. Meaning, it is
also simulating pointer access under truncation. We therefore
"branch off" and push the current verification state after the
ALU operation with known 0 to the verification stack for later
analysis. Given the current path analysis succeeded it is
likely that the one under speculation can be pruned. In any
case, it is also subject to existing complexity limits and
therefore anything beyond this point will be rejected. In
terms of pruning, it needs to be ensured that the verification
state from speculative execution simulation must never prune
a non-speculative execution path, therefore, we mark verifier
state accordingly at the time of push_stack(). If verifier
detects out of bounds access under speculative execution from
one of the possible paths that includes a truncation, it will
reject such program.
Given we mask every reg-based pointer arithmetic for
unprivileged programs, we've been looking into how it could
affect real-world programs in terms of size increase. As the
majority of programs are targeted for privileged-only use
case, we've unconditionally enabled masking (with its alu
restrictions on top of it) for privileged programs for the
sake of testing in order to check i) whether they get rejected
in its current form, and ii) by how much the number of
instructions and size will increase. We've tested this by
using Katran, Cilium and test_l4lb from the kernel selftests.
For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o
and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb
we've used test_l4lb.o as well as test_l4lb_noinline.o. We
found that none of the programs got rejected by the verifier
with this change, and that impact is rather minimal to none.
balancer_kern.o had 13,904 bytes (1,738 insns) xlated and
7,797 bytes JITed before and after the change. Most complex
program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated
and 18,538 bytes JITed before and after and none of the other
tail call programs in bpf_lxc.o had any changes either. For
the older bpf_lxc_opt_-DUNKNOWN.o object we found a small
increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed
before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed
after the change. Other programs from that object file had
similar small increase. Both test_l4lb.o had no change and
remained at 6,544 bytes (817 insns) xlated and 3,401 bytes
JITed and for test_l4lb_noinline.o constant at 5,080 bytes
(634 insns) xlated and 3,313 bytes JITed. This can be explained
in that LLVM typically optimizes stack based pointer arithmetic
by using K-based operations and that use of dynamic map access
is not overly frequent. However, in future we may decide to
optimize the algorithm further under known guarantees from
branch and value speculation. Latter seems also unclear in
terms of prediction heuristics that today's CPUs apply as well
as whether there could be collisions in e.g. the predictor's
Value History/Pattern Table for triggering out of bounds access,
thus masking is performed unconditionally at this point but could
be subject to relaxation later on. We were generally also
brainstorming various other approaches for mitigation, but the
blocker was always lack of available registers at runtime and/or
overhead for runtime tracking of limits belonging to a specific
pointer. Thus, we found this to be minimally intrusive under
given constraints.
With that in place, a simple example with sanitized access on
unprivileged load at post-verification time looks as follows:
# bpftool prog dump xlated id 282
[...]
28: (79) r1 = *(u64 *)(r7 +0)
29: (79) r2 = *(u64 *)(r7 +8)
30: (57) r1 &= 15
31: (79) r3 = *(u64 *)(r0 +4608)
32: (57) r3 &= 1
33: (47) r3 |= 1
34: (2d) if r2 > r3 goto pc+19
35: (b4) (u32) r11 = (u32) 20479 |
36: (1f) r11 -= r2 | Dynamic sanitation for pointer
37: (4f) r11 |= r2 | arithmetic with registers
38: (87) r11 = -r11 | containing bounded or known
39: (c7) r11 s>>= 63 | scalars in order to prevent
40: (5f) r11 &= r2 | out of bounds speculation.
41: (0f) r4 += r11 |
42: (71) r4 = *(u8 *)(r4 +0)
43: (6f) r4 <<= r1
[...]
For the case where the scalar sits in the destination register
as opposed to the source register, the following code is emitted
for the above example:
[...]
16: (b4) (u32) r11 = (u32) 20479
17: (1f) r11 -= r2
18: (4f) r11 |= r2
19: (87) r11 = -r11
20: (c7) r11 s>>= 63
21: (5f) r2 &= r11
22: (0f) r2 += r0
23: (61) r0 = *(u32 *)(r2 +0)
[...]
JIT blinding example with non-conflicting use of r10:
[...]
d5: je 0x0000000000000106 _
d7: mov 0x0(%rax),%edi |
da: mov $0xf153246,%r10d | Index load from map value and
e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f.
e7: and %r10,%rdi |_
ea: mov $0x2f,%r10d |
f0: sub %rdi,%r10 | Sanitized addition. Both use r10
f3: or %rdi,%r10 | but do not interfere with each
f6: neg %r10 | other. (Neither do these instructions
f9: sar $0x3f,%r10 | interfere with the use of ax as temp
fd: and %r10,%rdi | in interpreter.)
100: add %rax,%rdi |_
103: mov 0x0(%rdi),%eax
[...]
Tested that it fixes Jann's reproducer, and also checked that test_verifier
and test_progs suite with interpreter, JIT and JIT with hardening enabled
on x86-64 and arm64 runs successfully.
[0] Speculose: Analyzing the Security Implications of Speculative
Execution in CPUs, Giorgi Maisuradze and Christian Rossow,
https://arxiv.org/pdf/1801.04084.pdf
[1] A Systematic Evaluation of Transient Execution Attacks and
Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz,
Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens,
Dmitry Evtyushkin, Daniel Gruss,
https://arxiv.org/pdf/1811.05441.pdf
Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
CWE ID: CWE-189 | static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len, i;
int insn_processed = 0;
bool do_print_state = false;
env->prev_linfo = NULL;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
state->curframe = 0;
state->speculative = false;
state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
if (!state->frame[0]) {
kfree(state);
return -ENOMEM;
}
env->cur_state = state;
init_func_state(env, state->frame[0],
BPF_MAIN_FUNC /* callsite */,
0 /* frameno */,
0 /* subprogno, zero == main subprog */);
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (env->insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
env->insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[env->insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, env->insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d%s: safe\n",
env->prev_insn_idx, env->insn_idx,
env->cur_state->speculative ?
" (speculative execution)" : "");
else
verbose(env, "%d: safe\n", env->insn_idx);
}
goto process_bpf_exit;
}
if (signal_pending(current))
return -EAGAIN;
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", env->insn_idx);
else
verbose(env, "\nfrom %d to %d%s:",
env->prev_insn_idx, env->insn_idx,
env->cur_state->speculative ?
" (speculative execution)" : "");
print_verifier_state(env, state->frame[state->curframe]);
do_print_state = false;
}
if (env->log.level) {
const struct bpf_insn_cbs cbs = {
.cb_print = verbose,
.private_data = env,
};
verbose_linfo(env, env->insn_idx, "; ");
verbose(env, "%d: ", env->insn_idx);
print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
}
if (bpf_prog_is_dev_bound(env->prog->aux)) {
err = bpf_prog_offload_verify_insn(env, env->insn_idx,
env->prev_insn_idx);
if (err)
return err;
}
regs = cur_regs(env);
env->insn_aux_data[env->insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, env->insn_idx, insn->src_reg,
insn->off, BPF_SIZE(insn->code),
BPF_READ, insn->dst_reg, false);
if (err)
return err;
prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, env->insn_idx, insn);
if (err)
return err;
env->insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, env->insn_idx, insn->dst_reg,
insn->off, BPF_SIZE(insn->code),
BPF_WRITE, insn->src_reg, false);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_ctx_reg(env, insn->dst_reg)) {
verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
insn->dst_reg,
reg_type_str[reg_state(env, insn->dst_reg)->type]);
return -EACCES;
}
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, env->insn_idx, insn->dst_reg,
insn->off, BPF_SIZE(insn->code),
BPF_WRITE, -1, false);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
(insn->src_reg != BPF_REG_0 &&
insn->src_reg != BPF_PSEUDO_CALL) ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
if (insn->src_reg == BPF_PSEUDO_CALL)
err = check_func_call(env, insn, &env->insn_idx);
else
err = check_helper_call(env, insn->imm, env->insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
env->insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
if (state->curframe) {
/* exit from nested function */
env->prev_insn_idx = env->insn_idx;
err = prepare_func_exit(env, &env->insn_idx);
if (err)
return err;
do_print_state = true;
continue;
}
err = check_reference_leak(env);
if (err)
return err;
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &env->prev_insn_idx,
&env->insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &env->insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
env->insn_idx++;
env->insn_aux_data[env->insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
env->insn_idx++;
}
verbose(env, "processed %d insns (limit %d), stack depth ",
insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
for (i = 0; i < env->subprog_cnt; i++) {
u32 depth = env->subprog_info[i].stack_depth;
verbose(env, "%d", depth);
if (i + 1 < env->subprog_cnt)
verbose(env, "+");
}
verbose(env, "\n");
env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
return 0;
}
| 170,242 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: __init int intel_pmu_init(void)
{
union cpuid10_edx edx;
union cpuid10_eax eax;
union cpuid10_ebx ebx;
struct event_constraint *c;
unsigned int unused;
int version;
if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON)) {
switch (boot_cpu_data.x86) {
case 0x6:
return p6_pmu_init();
case 0xb:
return knc_pmu_init();
case 0xf:
return p4_pmu_init();
}
return -ENODEV;
}
/*
* Check whether the Architectural PerfMon supports
* Branch Misses Retired hw_event or not.
*/
cpuid(10, &eax.full, &ebx.full, &unused, &edx.full);
if (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT)
return -ENODEV;
version = eax.split.version_id;
if (version < 2)
x86_pmu = core_pmu;
else
x86_pmu = intel_pmu;
x86_pmu.version = version;
x86_pmu.num_counters = eax.split.num_counters;
x86_pmu.cntval_bits = eax.split.bit_width;
x86_pmu.cntval_mask = (1ULL << eax.split.bit_width) - 1;
x86_pmu.events_maskl = ebx.full;
x86_pmu.events_mask_len = eax.split.mask_length;
x86_pmu.max_pebs_events = min_t(unsigned, MAX_PEBS_EVENTS, x86_pmu.num_counters);
/*
* Quirk: v2 perfmon does not report fixed-purpose events, so
* assume at least 3 events:
*/
if (version > 1)
x86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, 3);
/*
* v2 and above have a perf capabilities MSR
*/
if (version > 1) {
u64 capabilities;
rdmsrl(MSR_IA32_PERF_CAPABILITIES, capabilities);
x86_pmu.intel_cap.capabilities = capabilities;
}
intel_ds_init();
x86_add_quirk(intel_arch_events_quirk); /* Install first, so it runs last */
/*
* Install the hw-cache-events table:
*/
switch (boot_cpu_data.x86_model) {
case 14: /* 65 nm core solo/duo, "Yonah" */
pr_cont("Core events, ");
break;
case 15: /* original 65 nm celeron/pentium/core2/xeon, "Merom"/"Conroe" */
x86_add_quirk(intel_clovertown_quirk);
case 22: /* single-core 65 nm celeron/core2solo "Merom-L"/"Conroe-L" */
case 23: /* current 45 nm celeron/core2/xeon "Penryn"/"Wolfdale" */
case 29: /* six-core 45 nm xeon "Dunnington" */
memcpy(hw_cache_event_ids, core2_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_core();
x86_pmu.event_constraints = intel_core2_event_constraints;
x86_pmu.pebs_constraints = intel_core2_pebs_event_constraints;
pr_cont("Core2 events, ");
break;
case 26: /* 45 nm nehalem, "Bloomfield" */
case 30: /* 45 nm nehalem, "Lynnfield" */
case 46: /* 45 nm nehalem-ex, "Beckton" */
memcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_nehalem_event_constraints;
x86_pmu.pebs_constraints = intel_nehalem_pebs_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.extra_regs = intel_nehalem_extra_regs;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
x86_add_quirk(intel_nehalem_quirk);
pr_cont("Nehalem events, ");
break;
case 28: /* Atom */
case 38: /* Lincroft */
case 39: /* Penwell */
case 53: /* Cloverview */
case 54: /* Cedarview */
memcpy(hw_cache_event_ids, atom_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_atom();
x86_pmu.event_constraints = intel_gen_event_constraints;
x86_pmu.pebs_constraints = intel_atom_pebs_event_constraints;
pr_cont("Atom events, ");
break;
case 37: /* 32 nm nehalem, "Clarkdale" */
case 44: /* 32 nm nehalem, "Gulftown" */
case 47: /* 32 nm Xeon E7 */
memcpy(hw_cache_event_ids, westmere_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_westmere_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.pebs_constraints = intel_westmere_pebs_event_constraints;
x86_pmu.extra_regs = intel_westmere_extra_regs;
x86_pmu.er_flags |= ERF_HAS_RSP_1;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
pr_cont("Westmere events, ");
break;
case 42: /* SandyBridge */
case 45: /* SandyBridge, "Romely-EP" */
x86_add_quirk(intel_sandybridge_quirk);
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_snb_event_constraints;
x86_pmu.pebs_constraints = intel_snb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_DISPATCHED.THREAD,c=1,i=1 to count stall cycles*/
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x01, .inv=1, .cmask=1);
pr_cont("SandyBridge events, ");
break;
case 58: /* IvyBridge */
case 62: /* IvyBridge EP */
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_ivb_event_constraints;
x86_pmu.pebs_constraints = intel_ivb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
pr_cont("IvyBridge events, ");
break;
default:
switch (x86_pmu.version) {
case 1:
x86_pmu.event_constraints = intel_v1_event_constraints;
pr_cont("generic architected perfmon v1, ");
break;
default:
/*
* default constraints for v2 and up
*/
x86_pmu.event_constraints = intel_gen_event_constraints;
pr_cont("generic architected perfmon, ");
break;
}
}
if (x86_pmu.num_counters > INTEL_PMC_MAX_GENERIC) {
WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
x86_pmu.num_counters, INTEL_PMC_MAX_GENERIC);
x86_pmu.num_counters = INTEL_PMC_MAX_GENERIC;
}
x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
if (x86_pmu.num_counters_fixed > INTEL_PMC_MAX_FIXED) {
WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
x86_pmu.num_counters_fixed, INTEL_PMC_MAX_FIXED);
x86_pmu.num_counters_fixed = INTEL_PMC_MAX_FIXED;
}
x86_pmu.intel_ctrl |=
((1LL << x86_pmu.num_counters_fixed)-1) << INTEL_PMC_IDX_FIXED;
if (x86_pmu.event_constraints) {
/*
* event on fixed counter2 (REF_CYCLES) only works on this
* counter, so do not extend mask to generic counters
*/
for_each_event_constraint(c, x86_pmu.event_constraints) {
if (c->cmask != X86_RAW_EVENT_MASK
|| c->idxmsk64 == INTEL_PMC_MSK_FIXED_REF_CYCLES) {
continue;
}
c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
c->weight += x86_pmu.num_counters;
}
}
return 0;
}
Commit Message: perf/x86: Fix offcore_rsp valid mask for SNB/IVB
The valid mask for both offcore_response_0 and
offcore_response_1 was wrong for SNB/SNB-EP,
IVB/IVB-EP. It was possible to write to
reserved bit and cause a GP fault crashing
the kernel.
This patch fixes the problem by correctly marking the
reserved bits in the valid mask for all the processors
mentioned above.
A distinction between desktop and server parts is introduced
because bits 24-30 are only available on the server parts.
This version of the patch is just a rebase to perf/urgent tree
and should apply to older kernels as well.
Signed-off-by: Stephane Eranian <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-20 | __init int intel_pmu_init(void)
{
union cpuid10_edx edx;
union cpuid10_eax eax;
union cpuid10_ebx ebx;
struct event_constraint *c;
unsigned int unused;
int version;
if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON)) {
switch (boot_cpu_data.x86) {
case 0x6:
return p6_pmu_init();
case 0xb:
return knc_pmu_init();
case 0xf:
return p4_pmu_init();
}
return -ENODEV;
}
/*
* Check whether the Architectural PerfMon supports
* Branch Misses Retired hw_event or not.
*/
cpuid(10, &eax.full, &ebx.full, &unused, &edx.full);
if (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT)
return -ENODEV;
version = eax.split.version_id;
if (version < 2)
x86_pmu = core_pmu;
else
x86_pmu = intel_pmu;
x86_pmu.version = version;
x86_pmu.num_counters = eax.split.num_counters;
x86_pmu.cntval_bits = eax.split.bit_width;
x86_pmu.cntval_mask = (1ULL << eax.split.bit_width) - 1;
x86_pmu.events_maskl = ebx.full;
x86_pmu.events_mask_len = eax.split.mask_length;
x86_pmu.max_pebs_events = min_t(unsigned, MAX_PEBS_EVENTS, x86_pmu.num_counters);
/*
* Quirk: v2 perfmon does not report fixed-purpose events, so
* assume at least 3 events:
*/
if (version > 1)
x86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, 3);
/*
* v2 and above have a perf capabilities MSR
*/
if (version > 1) {
u64 capabilities;
rdmsrl(MSR_IA32_PERF_CAPABILITIES, capabilities);
x86_pmu.intel_cap.capabilities = capabilities;
}
intel_ds_init();
x86_add_quirk(intel_arch_events_quirk); /* Install first, so it runs last */
/*
* Install the hw-cache-events table:
*/
switch (boot_cpu_data.x86_model) {
case 14: /* 65 nm core solo/duo, "Yonah" */
pr_cont("Core events, ");
break;
case 15: /* original 65 nm celeron/pentium/core2/xeon, "Merom"/"Conroe" */
x86_add_quirk(intel_clovertown_quirk);
case 22: /* single-core 65 nm celeron/core2solo "Merom-L"/"Conroe-L" */
case 23: /* current 45 nm celeron/core2/xeon "Penryn"/"Wolfdale" */
case 29: /* six-core 45 nm xeon "Dunnington" */
memcpy(hw_cache_event_ids, core2_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_core();
x86_pmu.event_constraints = intel_core2_event_constraints;
x86_pmu.pebs_constraints = intel_core2_pebs_event_constraints;
pr_cont("Core2 events, ");
break;
case 26: /* 45 nm nehalem, "Bloomfield" */
case 30: /* 45 nm nehalem, "Lynnfield" */
case 46: /* 45 nm nehalem-ex, "Beckton" */
memcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_nehalem_event_constraints;
x86_pmu.pebs_constraints = intel_nehalem_pebs_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.extra_regs = intel_nehalem_extra_regs;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
x86_add_quirk(intel_nehalem_quirk);
pr_cont("Nehalem events, ");
break;
case 28: /* Atom */
case 38: /* Lincroft */
case 39: /* Penwell */
case 53: /* Cloverview */
case 54: /* Cedarview */
memcpy(hw_cache_event_ids, atom_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_atom();
x86_pmu.event_constraints = intel_gen_event_constraints;
x86_pmu.pebs_constraints = intel_atom_pebs_event_constraints;
pr_cont("Atom events, ");
break;
case 37: /* 32 nm nehalem, "Clarkdale" */
case 44: /* 32 nm nehalem, "Gulftown" */
case 47: /* 32 nm Xeon E7 */
memcpy(hw_cache_event_ids, westmere_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_westmere_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.pebs_constraints = intel_westmere_pebs_event_constraints;
x86_pmu.extra_regs = intel_westmere_extra_regs;
x86_pmu.er_flags |= ERF_HAS_RSP_1;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
pr_cont("Westmere events, ");
break;
case 42: /* SandyBridge */
case 45: /* SandyBridge, "Romely-EP" */
x86_add_quirk(intel_sandybridge_quirk);
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_snb_event_constraints;
x86_pmu.pebs_constraints = intel_snb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
if (boot_cpu_data.x86_model == 45)
x86_pmu.extra_regs = intel_snbep_extra_regs;
else
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_DISPATCHED.THREAD,c=1,i=1 to count stall cycles*/
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x01, .inv=1, .cmask=1);
pr_cont("SandyBridge events, ");
break;
case 58: /* IvyBridge */
case 62: /* IvyBridge EP */
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_ivb_event_constraints;
x86_pmu.pebs_constraints = intel_ivb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
if (boot_cpu_data.x86_model == 62)
x86_pmu.extra_regs = intel_snbep_extra_regs;
else
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
pr_cont("IvyBridge events, ");
break;
default:
switch (x86_pmu.version) {
case 1:
x86_pmu.event_constraints = intel_v1_event_constraints;
pr_cont("generic architected perfmon v1, ");
break;
default:
/*
* default constraints for v2 and up
*/
x86_pmu.event_constraints = intel_gen_event_constraints;
pr_cont("generic architected perfmon, ");
break;
}
}
if (x86_pmu.num_counters > INTEL_PMC_MAX_GENERIC) {
WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
x86_pmu.num_counters, INTEL_PMC_MAX_GENERIC);
x86_pmu.num_counters = INTEL_PMC_MAX_GENERIC;
}
x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
if (x86_pmu.num_counters_fixed > INTEL_PMC_MAX_FIXED) {
WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
x86_pmu.num_counters_fixed, INTEL_PMC_MAX_FIXED);
x86_pmu.num_counters_fixed = INTEL_PMC_MAX_FIXED;
}
x86_pmu.intel_ctrl |=
((1LL << x86_pmu.num_counters_fixed)-1) << INTEL_PMC_IDX_FIXED;
if (x86_pmu.event_constraints) {
/*
* event on fixed counter2 (REF_CYCLES) only works on this
* counter, so do not extend mask to generic counters
*/
for_each_event_constraint(c, x86_pmu.event_constraints) {
if (c->cmask != X86_RAW_EVENT_MASK
|| c->idxmsk64 == INTEL_PMC_MSK_FIXED_REF_CYCLES) {
continue;
}
c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
c->weight += x86_pmu.num_counters;
}
}
return 0;
}
| 166,081 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
struct dev_pagemap *pgmap = NULL;
int nr_start = *nr, ret = 0;
pte_t *ptep, *ptem;
ptem = ptep = pte_offset_map(&pmd, addr);
do {
pte_t pte = gup_get_pte(ptep);
struct page *head, *page;
/*
* Similar to the PMD case below, NUMA hinting must take slow
* path using the pte_protnone check.
*/
if (pte_protnone(pte))
goto pte_unmap;
if (!pte_access_permitted(pte, write))
goto pte_unmap;
if (pte_devmap(pte)) {
pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
if (unlikely(!pgmap)) {
undo_dev_pagemap(nr, nr_start, pages);
goto pte_unmap;
}
} else if (pte_special(pte))
goto pte_unmap;
VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
page = pte_page(pte);
head = compound_head(page);
if (!page_cache_get_speculative(head))
goto pte_unmap;
if (unlikely(pte_val(pte) != pte_val(*ptep))) {
put_page(head);
goto pte_unmap;
}
VM_BUG_ON_PAGE(compound_head(page) != head, page);
SetPageReferenced(page);
pages[*nr] = page;
(*nr)++;
} while (ptep++, addr += PAGE_SIZE, addr != end);
ret = 1;
pte_unmap:
if (pgmap)
put_dev_pagemap(pgmap);
pte_unmap(ptem);
return ret;
}
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_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
struct dev_pagemap *pgmap = NULL;
int nr_start = *nr, ret = 0;
pte_t *ptep, *ptem;
ptem = ptep = pte_offset_map(&pmd, addr);
do {
pte_t pte = gup_get_pte(ptep);
struct page *head, *page;
/*
* Similar to the PMD case below, NUMA hinting must take slow
* path using the pte_protnone check.
*/
if (pte_protnone(pte))
goto pte_unmap;
if (!pte_access_permitted(pte, write))
goto pte_unmap;
if (pte_devmap(pte)) {
pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
if (unlikely(!pgmap)) {
undo_dev_pagemap(nr, nr_start, pages);
goto pte_unmap;
}
} else if (pte_special(pte))
goto pte_unmap;
VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
page = pte_page(pte);
head = try_get_compound_head(page, 1);
if (!head)
goto pte_unmap;
if (unlikely(pte_val(pte) != pte_val(*ptep))) {
put_page(head);
goto pte_unmap;
}
VM_BUG_ON_PAGE(compound_head(page) != head, page);
SetPageReferenced(page);
pages[*nr] = page;
(*nr)++;
} while (ptep++, addr += PAGE_SIZE, addr != end);
ret = 1;
pte_unmap:
if (pgmap)
put_dev_pagemap(pgmap);
pte_unmap(ptem);
return ret;
}
| 170,228 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool BaseSettingChange::Init(Profile* profile) {
DCHECK(profile);
profile_ = profile;
return true;
}
Commit Message: [protector] Refactoring of --no-protector code.
*) On DSE change, new provider is not pushed to Sync.
*) Simplified code in BrowserInit.
BUG=None
TEST=protector.py
Review URL: http://codereview.chromium.org/10065016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132398 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool BaseSettingChange::Init(Profile* profile) {
DCHECK(profile && !profile_);
profile_ = profile;
return true;
}
| 170,756 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadJPEGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
value[MaxTextExtent];
const char
*option;
ErrorManager
error_manager;
Image
*image;
IndexPacket
index;
JSAMPLE
*volatile jpeg_pixels;
JSAMPROW
scanline[1];
MagickBooleanType
debug,
status;
MagickSizeType
number_pixels;
MemoryInfo
*memory_info;
register ssize_t
i;
struct jpeg_decompress_struct
jpeg_info;
struct jpeg_error_mgr
jpeg_error;
register JSAMPLE
*p;
size_t
units;
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);
debug=IsEventLogging();
(void) debug;
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JPEG parameters.
*/
(void) ResetMagickMemory(&error_manager,0,sizeof(error_manager));
(void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info));
(void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error));
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
memory_info=(MemoryInfo *) NULL;
error_manager.image=image;
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_decompress(&jpeg_info);
if (error_manager.profile != (StringInfo *) NULL)
error_manager.profile=DestroyStringInfo(error_manager.profile);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
InheritException(exception,&image->exception);
return(DestroyImage(image));
}
jpeg_info.client_data=(void *) &error_manager;
jpeg_create_decompress(&jpeg_info);
JPEGSourceManager(&jpeg_info,image);
jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment);
option=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile);
if (IsOptionMember("IPTC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile);
for (i=1; i < 16; i++)
if ((i != 2) && (i != 13) && (i != 14))
if (IsOptionMember("APP",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile);
i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE);
if ((image_info->colorspace == YCbCrColorspace) ||
(image_info->colorspace == Rec601YCbCrColorspace) ||
(image_info->colorspace == Rec709YCbCrColorspace))
jpeg_info.out_color_space=JCS_YCbCr;
/*
Set image resolution.
*/
units=0;
if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) &&
(jpeg_info.Y_density != 1))
{
image->x_resolution=(double) jpeg_info.X_density;
image->y_resolution=(double) jpeg_info.Y_density;
units=(size_t) jpeg_info.density_unit;
}
if (units == 1)
image->units=PixelsPerInchResolution;
if (units == 2)
image->units=PixelsPerCentimeterResolution;
number_pixels=(MagickSizeType) image->columns*image->rows;
option=GetImageOption(image_info,"jpeg:size");
if ((option != (const char *) NULL) &&
(jpeg_info.out_color_space != JCS_YCbCr))
{
double
scale_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
/*
Scale the image.
*/
flags=ParseGeometry(option,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
jpeg_calc_output_dimensions(&jpeg_info);
image->magick_columns=jpeg_info.output_width;
image->magick_rows=jpeg_info.output_height;
scale_factor=1.0;
if (geometry_info.rho != 0.0)
scale_factor=jpeg_info.output_width/geometry_info.rho;
if ((geometry_info.sigma != 0.0) &&
(scale_factor > (jpeg_info.output_height/geometry_info.sigma)))
scale_factor=jpeg_info.output_height/geometry_info.sigma;
jpeg_info.scale_num=1U;
jpeg_info.scale_denom=(unsigned int) scale_factor;
jpeg_calc_output_dimensions(&jpeg_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Scale factor: %.20g",(double) scale_factor);
}
#if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED)
#if defined(D_LOSSLESS_SUPPORTED)
image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ?
JPEGInterlace : NoInterlace;
image->compression=jpeg_info.process == JPROC_LOSSLESS ?
LosslessJPEGCompression : JPEGCompression;
if (jpeg_info.data_precision > 8)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'",
image->filename);
if (jpeg_info.data_precision == 16)
jpeg_info.data_precision=12;
#else
image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace :
NoInterlace;
image->compression=JPEGCompression;
#endif
#else
image->compression=JPEGCompression;
image->interlace=JPEGInterlace;
#endif
option=GetImageOption(image_info,"jpeg:colors");
if (option != (const char *) NULL)
{
/*
Let the JPEG library quantize for us.
*/
jpeg_info.quantize_colors=TRUE;
jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option);
}
option=GetImageOption(image_info,"jpeg:block-smoothing");
if (option != (const char *) NULL)
jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
jpeg_info.dct_method=JDCT_FLOAT;
option=GetImageOption(image_info,"jpeg:dct-method");
if (option != (const char *) NULL)
switch (*option)
{
case 'D':
case 'd':
{
if (LocaleCompare(option,"default") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(option,"fastest") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
if (LocaleCompare(option,"float") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(option,"ifast") == 0)
jpeg_info.dct_method=JDCT_IFAST;
if (LocaleCompare(option,"islow") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
break;
}
}
option=GetImageOption(image_info,"jpeg:fancy-upsampling");
if (option != (const char *) NULL)
jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
(void) jpeg_start_decompress(&jpeg_info);
image->columns=jpeg_info.output_width;
image->rows=jpeg_info.output_height;
image->depth=(size_t) jpeg_info.data_precision;
switch (jpeg_info.out_color_space)
{
case JCS_RGB:
default:
{
(void) SetImageColorspace(image,sRGBColorspace);
break;
}
case JCS_GRAYSCALE:
{
(void) SetImageColorspace(image,GRAYColorspace);
break;
}
case JCS_YCbCr:
{
(void) SetImageColorspace(image,YCbCrColorspace);
break;
}
case JCS_CMYK:
{
(void) SetImageColorspace(image,CMYKColorspace);
break;
}
}
if (IsITUFaxImage(image) != MagickFalse)
{
(void) SetImageColorspace(image,LabColorspace);
jpeg_info.out_color_space=JCS_YCbCr;
}
if (option != (const char *) NULL)
if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((jpeg_info.output_components == 1) &&
(jpeg_info.quantize_colors == 0))
{
size_t
colors;
colors=(size_t) GetQuantumRange(image->depth)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (image->debug != MagickFalse)
{
if (image->interlace != NoInterlace)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d",
(int) jpeg_info.data_precision);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d",
(int) jpeg_info.output_width,(int) jpeg_info.output_height);
}
JPEGSetImageQuality(&jpeg_info,image);
JPEGSetImageSamplingFactor(&jpeg_info,image);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
jpeg_info.out_color_space);
(void) SetImageProperty(image,"jpeg:colorspace",value);
if (image_info->ping != MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((jpeg_info.output_components != 1) &&
(jpeg_info.output_components != 3) && (jpeg_info.output_components != 4))
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
memory_info=AcquireVirtualMemory((size_t) image->columns,
jpeg_info.output_components*sizeof(*jpeg_pixels));
if (memory_info == (MemoryInfo *) NULL)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info);
/*
Convert JPEG pixels to pixel packets.
*/
if (setjmp(error_manager.error_recovery) != 0)
{
if (memory_info != (MemoryInfo *) NULL)
memory_info=RelinquishVirtualMemory(memory_info);
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
return(DestroyImage(image));
}
if (jpeg_info.quantize_colors != 0)
{
image->colors=(size_t) jpeg_info.actual_number_of_colors;
if (jpeg_info.out_color_space == JCS_GRAYSCALE)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=image->colormap[i].red;
image->colormap[i].blue=image->colormap[i].red;
image->colormap[i].opacity=OpaqueOpacity;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]);
image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]);
image->colormap[i].opacity=OpaqueOpacity;
}
}
scanline[0]=(JSAMPROW) jpeg_pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
continue;
}
p=jpeg_pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (jpeg_info.data_precision > 8)
{
unsigned short
scale;
scale=65535/(unsigned short) GetQuantumRange((size_t)
jpeg_info.data_precision);
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
size_t
pixel;
pixel=(size_t) (scale*GETJSAMPLE(*p));
index=ConstrainColormapIndex(image,pixel);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelYellow(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
else
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum(
(unsigned char) GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
{
jpeg_abort_decompress(&jpeg_info);
break;
}
}
if (status != MagickFalse)
{
error_manager.finished=MagickTrue;
if (setjmp(error_manager.error_recovery) == 0)
(void) jpeg_finish_decompress(&jpeg_info);
}
/*
Free jpeg resources.
*/
jpeg_destroy_decompress(&jpeg_info);
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: ...
CWE ID: CWE-119 | static Image *ReadJPEGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
value[MaxTextExtent];
const char
*option;
ErrorManager
error_manager;
Image
*image;
IndexPacket
index;
JSAMPLE
*volatile jpeg_pixels;
JSAMPROW
scanline[1];
MagickBooleanType
debug,
status;
MagickSizeType
number_pixels;
MemoryInfo
*memory_info;
register ssize_t
i;
struct jpeg_decompress_struct
jpeg_info;
struct jpeg_error_mgr
jpeg_error;
register JSAMPLE
*p;
size_t
units;
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);
debug=IsEventLogging();
(void) debug;
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JPEG parameters.
*/
(void) ResetMagickMemory(&error_manager,0,sizeof(error_manager));
(void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info));
(void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error));
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
memory_info=(MemoryInfo *) NULL;
error_manager.image=image;
if (setjmp(error_manager.error_recovery) != 0)
{
jpeg_destroy_decompress(&jpeg_info);
if (error_manager.profile != (StringInfo *) NULL)
error_manager.profile=DestroyStringInfo(error_manager.profile);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
InheritException(exception,&image->exception);
return(DestroyImage(image));
}
jpeg_info.client_data=(void *) &error_manager;
jpeg_create_decompress(&jpeg_info);
JPEGSourceManager(&jpeg_info,image);
jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment);
option=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile);
if (IsOptionMember("IPTC",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile);
for (i=1; i < 16; i++)
if ((i != 2) && (i != 13) && (i != 14))
if (IsOptionMember("APP",option) == MagickFalse)
jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile);
i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE);
if ((image_info->colorspace == YCbCrColorspace) ||
(image_info->colorspace == Rec601YCbCrColorspace) ||
(image_info->colorspace == Rec709YCbCrColorspace))
jpeg_info.out_color_space=JCS_YCbCr;
/*
Set image resolution.
*/
units=0;
if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) &&
(jpeg_info.Y_density != 1))
{
image->x_resolution=(double) jpeg_info.X_density;
image->y_resolution=(double) jpeg_info.Y_density;
units=(size_t) jpeg_info.density_unit;
}
if (units == 1)
image->units=PixelsPerInchResolution;
if (units == 2)
image->units=PixelsPerCentimeterResolution;
number_pixels=(MagickSizeType) image->columns*image->rows;
option=GetImageOption(image_info,"jpeg:size");
if ((option != (const char *) NULL) &&
(jpeg_info.out_color_space != JCS_YCbCr))
{
double
scale_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
/*
Scale the image.
*/
flags=ParseGeometry(option,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
jpeg_calc_output_dimensions(&jpeg_info);
image->magick_columns=jpeg_info.output_width;
image->magick_rows=jpeg_info.output_height;
scale_factor=1.0;
if (geometry_info.rho != 0.0)
scale_factor=jpeg_info.output_width/geometry_info.rho;
if ((geometry_info.sigma != 0.0) &&
(scale_factor > (jpeg_info.output_height/geometry_info.sigma)))
scale_factor=jpeg_info.output_height/geometry_info.sigma;
jpeg_info.scale_num=1U;
jpeg_info.scale_denom=(unsigned int) scale_factor;
jpeg_calc_output_dimensions(&jpeg_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Scale factor: %.20g",(double) scale_factor);
}
#if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED)
#if defined(D_LOSSLESS_SUPPORTED)
image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ?
JPEGInterlace : NoInterlace;
image->compression=jpeg_info.process == JPROC_LOSSLESS ?
LosslessJPEGCompression : JPEGCompression;
if (jpeg_info.data_precision > 8)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'",
image->filename);
if (jpeg_info.data_precision == 16)
jpeg_info.data_precision=12;
#else
image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace :
NoInterlace;
image->compression=JPEGCompression;
#endif
#else
image->compression=JPEGCompression;
image->interlace=JPEGInterlace;
#endif
option=GetImageOption(image_info,"jpeg:colors");
if (option != (const char *) NULL)
{
/*
Let the JPEG library quantize for us.
*/
jpeg_info.quantize_colors=TRUE;
jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option);
}
option=GetImageOption(image_info,"jpeg:block-smoothing");
if (option != (const char *) NULL)
jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
jpeg_info.dct_method=JDCT_FLOAT;
option=GetImageOption(image_info,"jpeg:dct-method");
if (option != (const char *) NULL)
switch (*option)
{
case 'D':
case 'd':
{
if (LocaleCompare(option,"default") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(option,"fastest") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
if (LocaleCompare(option,"float") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(option,"ifast") == 0)
jpeg_info.dct_method=JDCT_IFAST;
if (LocaleCompare(option,"islow") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
break;
}
}
option=GetImageOption(image_info,"jpeg:fancy-upsampling");
if (option != (const char *) NULL)
jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE :
FALSE;
(void) jpeg_start_decompress(&jpeg_info);
image->columns=jpeg_info.output_width;
image->rows=jpeg_info.output_height;
image->depth=(size_t) jpeg_info.data_precision;
switch (jpeg_info.out_color_space)
{
case JCS_RGB:
default:
{
(void) SetImageColorspace(image,sRGBColorspace);
break;
}
case JCS_GRAYSCALE:
{
(void) SetImageColorspace(image,GRAYColorspace);
break;
}
case JCS_YCbCr:
{
(void) SetImageColorspace(image,YCbCrColorspace);
break;
}
case JCS_CMYK:
{
(void) SetImageColorspace(image,CMYKColorspace);
break;
}
}
if (IsITUFaxImage(image) != MagickFalse)
{
(void) SetImageColorspace(image,LabColorspace);
jpeg_info.out_color_space=JCS_YCbCr;
}
if (option != (const char *) NULL)
if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0))
{
size_t
colors;
colors=(size_t) GetQuantumRange(image->depth)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (image->debug != MagickFalse)
{
if (image->interlace != NoInterlace)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d",
(int) jpeg_info.data_precision);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d",
(int) jpeg_info.output_width,(int) jpeg_info.output_height);
}
JPEGSetImageQuality(&jpeg_info,image);
JPEGSetImageSamplingFactor(&jpeg_info,image);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
jpeg_info.out_color_space);
(void) SetImageProperty(image,"jpeg:colorspace",value);
if (image_info->ping != MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
jpeg_destroy_decompress(&jpeg_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((jpeg_info.output_components != 1) &&
(jpeg_info.output_components != 3) && (jpeg_info.output_components != 4))
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
memory_info=AcquireVirtualMemory((size_t) image->columns,
jpeg_info.output_components*sizeof(*jpeg_pixels));
if (memory_info == (MemoryInfo *) NULL)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info);
/*
Convert JPEG pixels to pixel packets.
*/
if (setjmp(error_manager.error_recovery) != 0)
{
if (memory_info != (MemoryInfo *) NULL)
memory_info=RelinquishVirtualMemory(memory_info);
jpeg_destroy_decompress(&jpeg_info);
(void) CloseBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (number_pixels != 0)
return(GetFirstImageInList(image));
return(DestroyImage(image));
}
if (jpeg_info.quantize_colors != 0)
{
image->colors=(size_t) jpeg_info.actual_number_of_colors;
if (jpeg_info.out_color_space == JCS_GRAYSCALE)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=image->colormap[i].red;
image->colormap[i].blue=image->colormap[i].red;
image->colormap[i].opacity=OpaqueOpacity;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]);
image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]);
image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]);
image->colormap[i].opacity=OpaqueOpacity;
}
}
scanline[0]=(JSAMPROW) jpeg_pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
continue;
}
p=jpeg_pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (jpeg_info.data_precision > 8)
{
unsigned short
scale;
scale=65535/(unsigned short) GetQuantumRange((size_t)
jpeg_info.data_precision);
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
size_t
pixel;
pixel=(size_t) (scale*GETJSAMPLE(*p));
index=ConstrainColormapIndex(image,pixel);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short)
(scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelYellow(q,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum(
(unsigned short) (scale*GETJSAMPLE(*p++))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
else
if (jpeg_info.output_components == 1)
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
else
if (image->colorspace != CMYKColorspace)
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char)
GETJSAMPLE(*p++)));
SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum(
(unsigned char) GETJSAMPLE(*p++)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
{
jpeg_abort_decompress(&jpeg_info);
break;
}
}
if (status != MagickFalse)
{
error_manager.finished=MagickTrue;
if (setjmp(error_manager.error_recovery) == 0)
(void) jpeg_finish_decompress(&jpeg_info);
}
/*
Free jpeg resources.
*/
jpeg_destroy_decompress(&jpeg_info);
memory_info=RelinquishVirtualMemory(memory_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,629 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: scoped_refptr<Image> CSSPaintValue::GetImage(
const ImageResourceObserver& client,
const Document& document,
const ComputedStyle&,
const FloatSize& target_size) {
if (!generator_) {
generator_ = CSSPaintImageGenerator::Create(
GetName(), document, paint_image_generator_observer_);
}
if (!ParseInputArguments(document))
return nullptr;
return generator_->Paint(client, RoundedIntSize(target_size),
parsed_input_arguments_);
}
Commit Message: [PaintWorklet] Do not paint when paint target is associated with a link
When the target element of a paint worklet has an associated link, then
the 'paint' function will be invoked when the link's href is changed
from a visited URL to an unvisited URL (or vice versa).
This CL changes the behavior by detecting whether the target element
of a paint worklet has an associated link or not. If it does, then don't
paint.
[email protected]
Bug: 835589
Change-Id: I5fdf85685f863c960a6f48cc9a345dda787bece1
Reviewed-on: https://chromium-review.googlesource.com/1035524
Reviewed-by: Xida Chen <[email protected]>
Reviewed-by: Ian Kilpatrick <[email protected]>
Reviewed-by: Stephen McGruer <[email protected]>
Commit-Queue: Xida Chen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#555788}
CWE ID: CWE-200 | scoped_refptr<Image> CSSPaintValue::GetImage(
const ImageResourceObserver& client,
const Document& document,
const ComputedStyle& style,
const FloatSize& target_size) {
// https://crbug.com/835589: early exit when paint target is associated with
// a link.
if (style.InsideLink() != EInsideLink::kNotInsideLink)
return nullptr;
if (!generator_) {
generator_ = CSSPaintImageGenerator::Create(
GetName(), document, paint_image_generator_observer_);
}
if (!ParseInputArguments(document))
return nullptr;
return generator_->Paint(client, RoundedIntSize(target_size),
parsed_input_arguments_);
}
| 173,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AddChunk(sk_sp<PaintRecord> record,
const TransformPaintPropertyNode* t,
const ClipPaintPropertyNode* c,
const EffectPaintPropertyNode* e,
const FloatRect& bounds = FloatRect(0, 0, 100, 100)) {
size_t i = items.size();
items.AllocateAndConstruct<DrawingDisplayItem>(
DefaultId().client, DefaultId().type, std::move(record));
chunks.emplace_back(i, i + 1, DefaultId(), PropertyTreeState(t, c, e));
chunks.back().bounds = bounds;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void AddChunk(sk_sp<PaintRecord> record,
const TransformPaintPropertyNode& t,
const ClipPaintPropertyNode& c,
const EffectPaintPropertyNode& e,
const FloatRect& bounds = FloatRect(0, 0, 100, 100)) {
size_t i = items.size();
items.AllocateAndConstruct<DrawingDisplayItem>(
DefaultId().client, DefaultId().type, std::move(record));
chunks.emplace_back(i, i + 1, DefaultId(), PropertyTreeState(&t, &c, &e));
chunks.back().bounds = bounds;
}
| 171,826 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t MPEG4Source::read(
MediaBuffer **out, const ReadOptions *options) {
Mutex::Autolock autoLock(mLock);
CHECK(mStarted);
if (mFirstMoofOffset > 0) {
return fragmentedRead(out, options);
}
*out = NULL;
int64_t targetSampleTimeUs = -1;
int64_t seekTimeUs;
ReadOptions::SeekMode mode;
if (options && options->getSeekTo(&seekTimeUs, &mode)) {
uint32_t findFlags = 0;
switch (mode) {
case ReadOptions::SEEK_PREVIOUS_SYNC:
findFlags = SampleTable::kFlagBefore;
break;
case ReadOptions::SEEK_NEXT_SYNC:
findFlags = SampleTable::kFlagAfter;
break;
case ReadOptions::SEEK_CLOSEST_SYNC:
case ReadOptions::SEEK_CLOSEST:
findFlags = SampleTable::kFlagClosest;
break;
default:
CHECK(!"Should not be here.");
break;
}
uint32_t sampleIndex;
status_t err = mSampleTable->findSampleAtTime(
seekTimeUs, 1000000, mTimescale,
&sampleIndex, findFlags);
if (mode == ReadOptions::SEEK_CLOSEST) {
findFlags = SampleTable::kFlagBefore;
}
uint32_t syncSampleIndex;
if (err == OK) {
err = mSampleTable->findSyncSampleNear(
sampleIndex, &syncSampleIndex, findFlags);
}
uint32_t sampleTime;
if (err == OK) {
err = mSampleTable->getMetaDataForSample(
sampleIndex, NULL, NULL, &sampleTime);
}
if (err != OK) {
if (err == ERROR_OUT_OF_RANGE) {
err = ERROR_END_OF_STREAM;
}
ALOGV("end of stream");
return err;
}
if (mode == ReadOptions::SEEK_CLOSEST) {
targetSampleTimeUs = (sampleTime * 1000000ll) / mTimescale;
}
#if 0
uint32_t syncSampleTime;
CHECK_EQ(OK, mSampleTable->getMetaDataForSample(
syncSampleIndex, NULL, NULL, &syncSampleTime));
ALOGI("seek to time %lld us => sample at time %lld us, "
"sync sample at time %lld us",
seekTimeUs,
sampleTime * 1000000ll / mTimescale,
syncSampleTime * 1000000ll / mTimescale);
#endif
mCurrentSampleIndex = syncSampleIndex;
if (mBuffer != NULL) {
mBuffer->release();
mBuffer = NULL;
}
}
off64_t offset;
size_t size;
uint32_t cts, stts;
bool isSyncSample;
bool newBuffer = false;
if (mBuffer == NULL) {
newBuffer = true;
status_t err =
mSampleTable->getMetaDataForSample(
mCurrentSampleIndex, &offset, &size, &cts, &isSyncSample, &stts);
if (err != OK) {
return err;
}
err = mGroup->acquire_buffer(&mBuffer);
if (err != OK) {
CHECK(mBuffer == NULL);
return err;
}
if (size > mBuffer->size()) {
ALOGE("buffer too small: %zu > %zu", size, mBuffer->size());
return ERROR_BUFFER_TOO_SMALL;
}
}
if ((!mIsAVC && !mIsHEVC) || mWantsNALFragments) {
if (newBuffer) {
ssize_t num_bytes_read =
mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size);
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
return ERROR_IO;
}
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
mBuffer->meta_data()->clear();
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)stts * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
}
if (!mIsAVC && !mIsHEVC) {
*out = mBuffer;
mBuffer = NULL;
return OK;
}
CHECK(mBuffer->range_length() >= mNALLengthSize);
const uint8_t *src =
(const uint8_t *)mBuffer->data() + mBuffer->range_offset();
size_t nal_size = parseNALSize(src);
if (mNALLengthSize > SIZE_MAX - nal_size) {
ALOGE("b/24441553, b/24445122");
}
if (mBuffer->range_length() - mNALLengthSize < nal_size) {
ALOGE("incomplete NAL unit.");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
MediaBuffer *clone = mBuffer->clone();
CHECK(clone != NULL);
clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size);
CHECK(mBuffer != NULL);
mBuffer->set_range(
mBuffer->range_offset() + mNALLengthSize + nal_size,
mBuffer->range_length() - mNALLengthSize - nal_size);
if (mBuffer->range_length() == 0) {
mBuffer->release();
mBuffer = NULL;
}
*out = clone;
return OK;
} else {
ssize_t num_bytes_read = 0;
int32_t drm = 0;
bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0);
if (usesDRM) {
num_bytes_read =
mDataSource->readAt(offset, (uint8_t*)mBuffer->data(), size);
} else {
num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size);
}
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
return ERROR_IO;
}
if (usesDRM) {
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
} else {
uint8_t *dstData = (uint8_t *)mBuffer->data();
size_t srcOffset = 0;
size_t dstOffset = 0;
while (srcOffset < size) {
bool isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize);
size_t nalLength = 0;
if (!isMalFormed) {
nalLength = parseNALSize(&mSrcBuffer[srcOffset]);
srcOffset += mNALLengthSize;
isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength);
}
if (isMalFormed) {
ALOGE("Video is malformed");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
CHECK(dstOffset + 4 <= mBuffer->size());
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, size);
CHECK(mBuffer != NULL);
mBuffer->set_range(0, dstOffset);
}
mBuffer->meta_data()->clear();
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)stts * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
*out = mBuffer;
mBuffer = NULL;
return OK;
}
}
Commit Message: Also fix out of bounds access for normal read
Previous fix accidentally only fixed the fragmented read case.
Bug: 27208621
Change-Id: Ie16f1920b84c8aba613842659238fcd5925694ad
CWE ID: CWE-119 | status_t MPEG4Source::read(
MediaBuffer **out, const ReadOptions *options) {
Mutex::Autolock autoLock(mLock);
CHECK(mStarted);
if (mFirstMoofOffset > 0) {
return fragmentedRead(out, options);
}
*out = NULL;
int64_t targetSampleTimeUs = -1;
int64_t seekTimeUs;
ReadOptions::SeekMode mode;
if (options && options->getSeekTo(&seekTimeUs, &mode)) {
uint32_t findFlags = 0;
switch (mode) {
case ReadOptions::SEEK_PREVIOUS_SYNC:
findFlags = SampleTable::kFlagBefore;
break;
case ReadOptions::SEEK_NEXT_SYNC:
findFlags = SampleTable::kFlagAfter;
break;
case ReadOptions::SEEK_CLOSEST_SYNC:
case ReadOptions::SEEK_CLOSEST:
findFlags = SampleTable::kFlagClosest;
break;
default:
CHECK(!"Should not be here.");
break;
}
uint32_t sampleIndex;
status_t err = mSampleTable->findSampleAtTime(
seekTimeUs, 1000000, mTimescale,
&sampleIndex, findFlags);
if (mode == ReadOptions::SEEK_CLOSEST) {
findFlags = SampleTable::kFlagBefore;
}
uint32_t syncSampleIndex;
if (err == OK) {
err = mSampleTable->findSyncSampleNear(
sampleIndex, &syncSampleIndex, findFlags);
}
uint32_t sampleTime;
if (err == OK) {
err = mSampleTable->getMetaDataForSample(
sampleIndex, NULL, NULL, &sampleTime);
}
if (err != OK) {
if (err == ERROR_OUT_OF_RANGE) {
err = ERROR_END_OF_STREAM;
}
ALOGV("end of stream");
return err;
}
if (mode == ReadOptions::SEEK_CLOSEST) {
targetSampleTimeUs = (sampleTime * 1000000ll) / mTimescale;
}
#if 0
uint32_t syncSampleTime;
CHECK_EQ(OK, mSampleTable->getMetaDataForSample(
syncSampleIndex, NULL, NULL, &syncSampleTime));
ALOGI("seek to time %lld us => sample at time %lld us, "
"sync sample at time %lld us",
seekTimeUs,
sampleTime * 1000000ll / mTimescale,
syncSampleTime * 1000000ll / mTimescale);
#endif
mCurrentSampleIndex = syncSampleIndex;
if (mBuffer != NULL) {
mBuffer->release();
mBuffer = NULL;
}
}
off64_t offset;
size_t size;
uint32_t cts, stts;
bool isSyncSample;
bool newBuffer = false;
if (mBuffer == NULL) {
newBuffer = true;
status_t err =
mSampleTable->getMetaDataForSample(
mCurrentSampleIndex, &offset, &size, &cts, &isSyncSample, &stts);
if (err != OK) {
return err;
}
err = mGroup->acquire_buffer(&mBuffer);
if (err != OK) {
CHECK(mBuffer == NULL);
return err;
}
if (size > mBuffer->size()) {
ALOGE("buffer too small: %zu > %zu", size, mBuffer->size());
return ERROR_BUFFER_TOO_SMALL;
}
}
if ((!mIsAVC && !mIsHEVC) || mWantsNALFragments) {
if (newBuffer) {
ssize_t num_bytes_read =
mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size);
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
return ERROR_IO;
}
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
mBuffer->meta_data()->clear();
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)stts * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
}
if (!mIsAVC && !mIsHEVC) {
*out = mBuffer;
mBuffer = NULL;
return OK;
}
CHECK(mBuffer->range_length() >= mNALLengthSize);
const uint8_t *src =
(const uint8_t *)mBuffer->data() + mBuffer->range_offset();
size_t nal_size = parseNALSize(src);
if (mNALLengthSize > SIZE_MAX - nal_size) {
ALOGE("b/24441553, b/24445122");
}
if (mBuffer->range_length() - mNALLengthSize < nal_size) {
ALOGE("incomplete NAL unit.");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
MediaBuffer *clone = mBuffer->clone();
CHECK(clone != NULL);
clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size);
CHECK(mBuffer != NULL);
mBuffer->set_range(
mBuffer->range_offset() + mNALLengthSize + nal_size,
mBuffer->range_length() - mNALLengthSize - nal_size);
if (mBuffer->range_length() == 0) {
mBuffer->release();
mBuffer = NULL;
}
*out = clone;
return OK;
} else {
ssize_t num_bytes_read = 0;
int32_t drm = 0;
bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0);
if (usesDRM) {
num_bytes_read =
mDataSource->readAt(offset, (uint8_t*)mBuffer->data(), size);
} else {
num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size);
}
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
return ERROR_IO;
}
if (usesDRM) {
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
} else {
uint8_t *dstData = (uint8_t *)mBuffer->data();
size_t srcOffset = 0;
size_t dstOffset = 0;
while (srcOffset < size) {
bool isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize);
size_t nalLength = 0;
if (!isMalFormed) {
nalLength = parseNALSize(&mSrcBuffer[srcOffset]);
srcOffset += mNALLengthSize;
isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength);
}
if (isMalFormed) {
ALOGE("Video is malformed");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
if (dstOffset > SIZE_MAX - 4 ||
dstOffset + 4 > SIZE_MAX - nalLength ||
dstOffset + 4 + nalLength > mBuffer->size()) {
ALOGE("b/27208621 : %zu %zu", dstOffset, mBuffer->size());
android_errorWriteLog(0x534e4554, "27208621");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, size);
CHECK(mBuffer != NULL);
mBuffer->set_range(0, dstOffset);
}
mBuffer->meta_data()->clear();
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)stts * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
*out = mBuffer;
mBuffer = NULL;
return OK;
}
}
| 173,924 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_scale_16_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_scale_16(pp);
this->next->set(this->next, that, pp, pi);
}
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_scale_16_set(PNG_CONST image_transform *this,
image_transform_png_set_scale_16_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_scale_16(pp);
# if PNG_LIBPNG_VER < 10700
/* libpng will limit the gamma table size: */
that->max_gamma_8 = PNG_MAX_GAMMA_8;
# endif
this->next->set(this->next, that, pp, pi);
}
| 173,647 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
ContentSecurityPolicy* policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
if (IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
}
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732 | void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
// Plugin documents inherit their parent/opener's 'plugin-types' directive
// regardless of URL.
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
| 172,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache */
if ((level == 2) && (s->session != NULL))
SSL_CTX_remove_session(s->session_ctx, s->session);
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
Commit Message:
CWE ID: CWE-200 | int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache and go into the error state */
if (level == SSL3_AL_FATAL) {
if (s->session != NULL)
SSL_CTX_remove_session(s->session_ctx, s->session);
s->state = SSL_ST_ERR;
}
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
| 165,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_setup_env(Session *s, const char *shell)
{
struct ssh *ssh = active_state; /* XXX */
char buf[256];
u_int i, envsize;
char **env, *laddr;
struct passwd *pw = s->pw;
#if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
char *path = NULL;
#endif
/* Initialize the environment. */
envsize = 100;
env = xcalloc(envsize, sizeof(char *));
env[0] = NULL;
#ifdef HAVE_CYGWIN
/*
* The Windows environment contains some setting which are
* important for a running system. They must not be dropped.
*/
{
char **p;
p = fetch_windows_environment();
copy_environment(p, &env, &envsize);
free_windows_environment(p);
}
#endif
#ifdef GSSAPI
/* Allow any GSSAPI methods that we've used to alter
* the childs environment as they see fit
*/
ssh_gssapi_do_child(&env, &envsize);
#endif
if (!options.use_login) {
/* Set basic environment. */
for (i = 0; i < s->num_env; i++)
child_set_env(&env, &envsize, s->env[i].name,
s->env[i].val);
child_set_env(&env, &envsize, "USER", pw->pw_name);
child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
#ifdef _AIX
child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
#endif
child_set_env(&env, &envsize, "HOME", pw->pw_dir);
#ifdef HAVE_LOGIN_CAP
if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
else
child_set_env(&env, &envsize, "PATH", getenv("PATH"));
#else /* HAVE_LOGIN_CAP */
# ifndef HAVE_CYGWIN
/*
* There's no standard path on Windows. The path contains
* important components pointing to the system directories,
* needed for loading shared libraries. So the path better
* remains intact here.
*/
# ifdef HAVE_ETC_DEFAULT_LOGIN
read_etc_default_login(&env, &envsize, pw->pw_uid);
path = child_get_env(env, "PATH");
# endif /* HAVE_ETC_DEFAULT_LOGIN */
if (path == NULL || *path == '\0') {
child_set_env(&env, &envsize, "PATH",
s->pw->pw_uid == 0 ?
SUPERUSER_PATH : _PATH_STDPATH);
}
# endif /* HAVE_CYGWIN */
#endif /* HAVE_LOGIN_CAP */
snprintf(buf, sizeof buf, "%.200s/%.50s",
_PATH_MAILDIR, pw->pw_name);
child_set_env(&env, &envsize, "MAIL", buf);
/* Normal systems set SHELL by default. */
child_set_env(&env, &envsize, "SHELL", shell);
}
if (getenv("TZ"))
child_set_env(&env, &envsize, "TZ", getenv("TZ"));
/* Set custom environment options from RSA authentication. */
if (!options.use_login) {
while (custom_environment) {
struct envstring *ce = custom_environment;
char *str = ce->s;
for (i = 0; str[i] != '=' && str[i]; i++)
;
if (str[i] == '=') {
str[i] = 0;
child_set_env(&env, &envsize, str, str + i + 1);
}
custom_environment = ce->next;
free(ce->s);
free(ce);
}
}
/* SSH_CLIENT deprecated */
snprintf(buf, sizeof buf, "%.50s %d %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
ssh_local_port(ssh));
child_set_env(&env, &envsize, "SSH_CLIENT", buf);
laddr = get_local_ipaddr(packet_get_connection_in());
snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
laddr, ssh_local_port(ssh));
free(laddr);
child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
if (s->ttyfd != -1)
child_set_env(&env, &envsize, "SSH_TTY", s->tty);
if (s->term)
child_set_env(&env, &envsize, "TERM", s->term);
if (s->display)
child_set_env(&env, &envsize, "DISPLAY", s->display);
if (original_command)
child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
original_command);
#ifdef _UNICOS
if (cray_tmpdir[0] != '\0')
child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
#endif /* _UNICOS */
/*
* Since we clear KRB5CCNAME at startup, if it's set now then it
* must have been set by a native authentication method (eg AIX or
* SIA), so copy it to the child.
*/
{
char *cp;
if ((cp = getenv("KRB5CCNAME")) != NULL)
child_set_env(&env, &envsize, "KRB5CCNAME", cp);
}
#ifdef _AIX
{
char *cp;
if ((cp = getenv("AUTHSTATE")) != NULL)
child_set_env(&env, &envsize, "AUTHSTATE", cp);
read_environment_file(&env, &envsize, "/etc/environment");
}
#endif
#ifdef KRB5
if (s->authctxt->krb5_ccname)
child_set_env(&env, &envsize, "KRB5CCNAME",
s->authctxt->krb5_ccname);
#endif
#ifdef USE_PAM
/*
* Pull in any environment variables that may have
* been set by PAM.
*/
if (options.use_pam) {
char **p;
p = fetch_pam_child_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
p = fetch_pam_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
}
#endif /* USE_PAM */
if (auth_sock_name != NULL)
child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
auth_sock_name);
/* read $HOME/.ssh/environment. */
if (options.permit_user_env && !options.use_login) {
snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
read_environment_file(&env, &envsize, buf);
}
if (debug_flag) {
/* dump the environment */
fprintf(stderr, "Environment:\n");
for (i = 0; env[i]; i++)
fprintf(stderr, " %.200s\n", env[i]);
}
return env;
}
Commit Message:
CWE ID: CWE-264 | do_setup_env(Session *s, const char *shell)
{
struct ssh *ssh = active_state; /* XXX */
char buf[256];
u_int i, envsize;
char **env, *laddr;
struct passwd *pw = s->pw;
#if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
char *path = NULL;
#endif
/* Initialize the environment. */
envsize = 100;
env = xcalloc(envsize, sizeof(char *));
env[0] = NULL;
#ifdef HAVE_CYGWIN
/*
* The Windows environment contains some setting which are
* important for a running system. They must not be dropped.
*/
{
char **p;
p = fetch_windows_environment();
copy_environment(p, &env, &envsize);
free_windows_environment(p);
}
#endif
#ifdef GSSAPI
/* Allow any GSSAPI methods that we've used to alter
* the childs environment as they see fit
*/
ssh_gssapi_do_child(&env, &envsize);
#endif
if (!options.use_login) {
/* Set basic environment. */
for (i = 0; i < s->num_env; i++)
child_set_env(&env, &envsize, s->env[i].name,
s->env[i].val);
child_set_env(&env, &envsize, "USER", pw->pw_name);
child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
#ifdef _AIX
child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
#endif
child_set_env(&env, &envsize, "HOME", pw->pw_dir);
#ifdef HAVE_LOGIN_CAP
if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
else
child_set_env(&env, &envsize, "PATH", getenv("PATH"));
#else /* HAVE_LOGIN_CAP */
# ifndef HAVE_CYGWIN
/*
* There's no standard path on Windows. The path contains
* important components pointing to the system directories,
* needed for loading shared libraries. So the path better
* remains intact here.
*/
# ifdef HAVE_ETC_DEFAULT_LOGIN
read_etc_default_login(&env, &envsize, pw->pw_uid);
path = child_get_env(env, "PATH");
# endif /* HAVE_ETC_DEFAULT_LOGIN */
if (path == NULL || *path == '\0') {
child_set_env(&env, &envsize, "PATH",
s->pw->pw_uid == 0 ?
SUPERUSER_PATH : _PATH_STDPATH);
}
# endif /* HAVE_CYGWIN */
#endif /* HAVE_LOGIN_CAP */
snprintf(buf, sizeof buf, "%.200s/%.50s",
_PATH_MAILDIR, pw->pw_name);
child_set_env(&env, &envsize, "MAIL", buf);
/* Normal systems set SHELL by default. */
child_set_env(&env, &envsize, "SHELL", shell);
}
if (getenv("TZ"))
child_set_env(&env, &envsize, "TZ", getenv("TZ"));
/* Set custom environment options from RSA authentication. */
if (!options.use_login) {
while (custom_environment) {
struct envstring *ce = custom_environment;
char *str = ce->s;
for (i = 0; str[i] != '=' && str[i]; i++)
;
if (str[i] == '=') {
str[i] = 0;
child_set_env(&env, &envsize, str, str + i + 1);
}
custom_environment = ce->next;
free(ce->s);
free(ce);
}
}
/* SSH_CLIENT deprecated */
snprintf(buf, sizeof buf, "%.50s %d %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
ssh_local_port(ssh));
child_set_env(&env, &envsize, "SSH_CLIENT", buf);
laddr = get_local_ipaddr(packet_get_connection_in());
snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
laddr, ssh_local_port(ssh));
free(laddr);
child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
if (s->ttyfd != -1)
child_set_env(&env, &envsize, "SSH_TTY", s->tty);
if (s->term)
child_set_env(&env, &envsize, "TERM", s->term);
if (s->display)
child_set_env(&env, &envsize, "DISPLAY", s->display);
if (original_command)
child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
original_command);
#ifdef _UNICOS
if (cray_tmpdir[0] != '\0')
child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
#endif /* _UNICOS */
/*
* Since we clear KRB5CCNAME at startup, if it's set now then it
* must have been set by a native authentication method (eg AIX or
* SIA), so copy it to the child.
*/
{
char *cp;
if ((cp = getenv("KRB5CCNAME")) != NULL)
child_set_env(&env, &envsize, "KRB5CCNAME", cp);
}
#ifdef _AIX
{
char *cp;
if ((cp = getenv("AUTHSTATE")) != NULL)
child_set_env(&env, &envsize, "AUTHSTATE", cp);
read_environment_file(&env, &envsize, "/etc/environment");
}
#endif
#ifdef KRB5
if (s->authctxt->krb5_ccname)
child_set_env(&env, &envsize, "KRB5CCNAME",
s->authctxt->krb5_ccname);
#endif
#ifdef USE_PAM
/*
* Pull in any environment variables that may have
* been set by PAM.
*/
if (options.use_pam && !options.use_login) {
char **p;
p = fetch_pam_child_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
p = fetch_pam_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
}
#endif /* USE_PAM */
if (auth_sock_name != NULL)
child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
auth_sock_name);
/* read $HOME/.ssh/environment. */
if (options.permit_user_env && !options.use_login) {
snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
read_environment_file(&env, &envsize, buf);
}
if (debug_flag) {
/* dump the environment */
fprintf(stderr, "Environment:\n");
for (i = 0; env[i]; i++)
fprintf(stderr, " %.200s\n", env[i]);
}
return env;
}
| 165,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: crm_send_remote_msg(void *session, xmlNode * msg, gboolean encrypted)
{
if (encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
cib_send_tls(session, msg);
#else
CRM_ASSERT(encrypted == FALSE);
#endif
} else {
cib_send_plaintext(GPOINTER_TO_INT(session), msg);
}
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | crm_send_remote_msg(void *session, xmlNode * msg, gboolean encrypted)
static int
crm_send_remote_msg_raw(void *session, const char *buf, size_t len, gboolean encrypted)
{
int rc = -1;
if (encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
rc = crm_send_tls(session, buf, len);
#else
CRM_ASSERT(encrypted == FALSE);
#endif
} else {
rc = crm_send_plaintext(GPOINTER_TO_INT(session), buf, len);
}
return rc;
}
| 166,164 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int Downmix_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
downmix_module_t *pDwmModule = (downmix_module_t *) self;
downmix_object_t *pDownmixer;
if (pDwmModule == NULL || pDwmModule->context.state == DOWNMIX_STATE_UNINITIALIZED) {
return -EINVAL;
}
pDownmixer = (downmix_object_t*) &pDwmModule->context;
ALOGV("Downmix_Command command %" PRIu32 " cmdSize %" PRIu32, cmdCode, cmdSize);
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Init(pDwmModule);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Configure(pDwmModule,
(effect_config_t *)pCmdData, false);
break;
case EFFECT_CMD_RESET:
Downmix_Reset(pDownmixer, false);
break;
case EFFECT_CMD_GET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM pCmdData %p, *replySize %" PRIu32 ", pReplyData: %p",
pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (int) sizeof(effect_param_t) + 2 * sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *rep = (effect_param_t *) pReplyData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(int32_t));
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM param %" PRId32 ", replySize %" PRIu32,
*(int32_t *)rep->data, rep->vsize);
rep->status = Downmix_getParameter(pDownmixer, *(int32_t *)rep->data, &rep->vsize,
rep->data + sizeof(int32_t));
*replySize = sizeof(effect_param_t) + sizeof(int32_t) + rep->vsize;
break;
case EFFECT_CMD_SET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_SET_PARAM cmdSize %d pCmdData %p, *replySize %" PRIu32
", pReplyData %p", cmdSize, pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || replySize == NULL || *replySize != (int)sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *cmd = (effect_param_t *) pCmdData;
*(int *)pReplyData = Downmix_setParameter(pDownmixer, *(int32_t *)cmd->data,
cmd->vsize, cmd->data + sizeof(int32_t));
break;
case EFFECT_CMD_SET_PARAM_DEFERRED:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_DEFERRED not supported, FIXME");
break;
case EFFECT_CMD_SET_PARAM_COMMIT:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_COMMIT not supported, FIXME");
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_INITIALIZED) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_ACTIVE) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_SET_DEVICE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_DEVICE: 0x%08" PRIx32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_VOLUME: {
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t) * 2) {
return -EINVAL;
}
ALOGW("Downmix_Command command EFFECT_CMD_SET_VOLUME not supported, FIXME");
float left = (float)(*(uint32_t *)pCmdData) / (1 << 24);
float right = (float)(*((uint32_t *)pCmdData + 1)) / (1 << 24);
ALOGV("Downmix_Command EFFECT_CMD_SET_VOLUME: left %f, right %f ", left, right);
break;
}
case EFFECT_CMD_SET_AUDIO_MODE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_AUDIO_MODE: %" PRIu32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_CONFIG_REVERSE:
case EFFECT_CMD_SET_INPUT_DEVICE:
break;
default:
ALOGW("Downmix_Command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking to Downmix and Reverb
Bug: 63662938
Bug: 63526567
Test: Added CTS tests
Change-Id: I8ed398cd62a9f461b0590e37f593daa3d8e4dbc4
(cherry picked from commit 804632afcdda6e80945bf27c384757bda50560cb)
CWE ID: CWE-200 | static int Downmix_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
downmix_module_t *pDwmModule = (downmix_module_t *) self;
downmix_object_t *pDownmixer;
if (pDwmModule == NULL || pDwmModule->context.state == DOWNMIX_STATE_UNINITIALIZED) {
return -EINVAL;
}
pDownmixer = (downmix_object_t*) &pDwmModule->context;
ALOGV("Downmix_Command command %" PRIu32 " cmdSize %" PRIu32, cmdCode, cmdSize);
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Init(pDwmModule);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Configure(pDwmModule,
(effect_config_t *)pCmdData, false);
break;
case EFFECT_CMD_RESET:
Downmix_Reset(pDownmixer, false);
break;
case EFFECT_CMD_GET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM pCmdData %p, *replySize %" PRIu32 ", pReplyData: %p",
pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (int) sizeof(effect_param_t) + 2 * sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *rep = (effect_param_t *) pReplyData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(int32_t));
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM param %" PRId32 ", replySize %" PRIu32,
*(int32_t *)rep->data, rep->vsize);
rep->status = Downmix_getParameter(pDownmixer, *(int32_t *)rep->data, &rep->vsize,
rep->data + sizeof(int32_t));
*replySize = sizeof(effect_param_t) + sizeof(int32_t) + rep->vsize;
break;
case EFFECT_CMD_SET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_SET_PARAM cmdSize %d pCmdData %p, *replySize %" PRIu32
", pReplyData %p", cmdSize, pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || replySize == NULL || *replySize != (int)sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *cmd = (effect_param_t *) pCmdData;
if (cmd->psize != sizeof(int32_t)) {
android_errorWriteLog(0x534e4554, "63662938");
return -EINVAL;
}
*(int *)pReplyData = Downmix_setParameter(pDownmixer, *(int32_t *)cmd->data,
cmd->vsize, cmd->data + sizeof(int32_t));
break;
case EFFECT_CMD_SET_PARAM_DEFERRED:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_DEFERRED not supported, FIXME");
break;
case EFFECT_CMD_SET_PARAM_COMMIT:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_COMMIT not supported, FIXME");
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_INITIALIZED) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_ACTIVE) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_SET_DEVICE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_DEVICE: 0x%08" PRIx32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_VOLUME: {
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t) * 2) {
return -EINVAL;
}
ALOGW("Downmix_Command command EFFECT_CMD_SET_VOLUME not supported, FIXME");
float left = (float)(*(uint32_t *)pCmdData) / (1 << 24);
float right = (float)(*((uint32_t *)pCmdData + 1)) / (1 << 24);
ALOGV("Downmix_Command EFFECT_CMD_SET_VOLUME: left %f, right %f ", left, right);
break;
}
case EFFECT_CMD_SET_AUDIO_MODE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_AUDIO_MODE: %" PRIu32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_CONFIG_REVERSE:
case EFFECT_CMD_SET_INPUT_DEVICE:
break;
default:
ALOGW("Downmix_Command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
| 173,978 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
quic::QuicSession* session)
: quic::QuicStream(id, session, /*is_static=*/false, quic::BIDIRECTIONAL) {}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284 | P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
| 172,263 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.