instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vp8_remove_decoder_instances(struct frame_buffers *fb)
{
if(!fb->use_frame_threads)
{
VP8D_COMP *pbi = fb->pbi[0];
if (!pbi)
return VPX_CODEC_ERROR;
#if CONFIG_MULTITHREAD
if (pbi->b_multithreaded_rd)
vp8mt_de_alloc_temp_buffers(pbi, pbi->common.mb_rows);
vp8_decoder_remove_threads(pbi);
#endif
/* decoder instance for single thread mode */
remove_decompressor(pbi);
}
else
{
/* TODO : remove frame threads and decoder instances for each
* thread here */
}
return VPX_CODEC_OK;
}
Commit Message: vp8:fix threading issues
1 - stops de allocating before threads are closed.
2 - limits threads to mb_rows when mb_rows < partitions
BUG=webm:851
Bug: 30436808
Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b
(cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e)
CWE ID: | int vp8_remove_decoder_instances(struct frame_buffers *fb)
{
if(!fb->use_frame_threads)
{
VP8D_COMP *pbi = fb->pbi[0];
if (!pbi)
return VPX_CODEC_ERROR;
#if CONFIG_MULTITHREAD
vp8_decoder_remove_threads(pbi);
#endif
/* decoder instance for single thread mode */
remove_decompressor(pbi);
}
else
{
/* TODO : remove frame threads and decoder instances for each
* thread here */
}
return VPX_CODEC_OK;
}
| 174,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void Np_toString(js_State *J)
{
char buf[32];
js_Object *self = js_toobject(J, 0);
int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);
if (self->type != JS_CNUMBER)
js_typeerror(J, "not a number");
if (radix == 10) {
js_pushstring(J, jsV_numbertostring(J, buf, self->u.number));
return;
}
if (radix < 2 || radix > 36)
js_rangeerror(J, "invalid radix");
/* lame number to string conversion for any radix from 2 to 36 */
{
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[100];
double number = self->u.number;
int sign = self->u.number < 0;
js_Buffer *sb = NULL;
uint64_t u, limit = ((uint64_t)1<<52);
int ndigits, exp, point;
if (number == 0) { js_pushstring(J, "0"); return; }
if (isnan(number)) { js_pushstring(J, "NaN"); return; }
if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; }
if (sign)
number = -number;
/* fit as many digits as we want in an int */
exp = 0;
while (number * pow(radix, exp) > limit)
--exp;
while (number * pow(radix, exp+1) < limit)
++exp;
u = number * pow(radix, exp) + 0.5;
/* trim trailing zeros */
while (u > 0 && (u % radix) == 0) {
u /= radix;
--exp;
}
/* serialize digits */
ndigits = 0;
while (u > 0) {
buf[ndigits++] = digits[u % radix];
u /= radix;
}
point = ndigits - exp;
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
if (sign)
js_putc(J, &sb, '-');
if (point <= 0) {
js_putc(J, &sb, '0');
js_putc(J, &sb, '.');
while (point++ < 0)
js_putc(J, &sb, '0');
while (ndigits-- > 0)
js_putc(J, &sb, buf[ndigits]);
} else {
while (ndigits-- > 0) {
js_putc(J, &sb, buf[ndigits]);
if (--point == 0 && ndigits > 0)
js_putc(J, &sb, '.');
}
while (point-- > 0)
js_putc(J, &sb, '0');
}
js_putc(J, &sb, 0);
js_pushstring(J, sb->s);
js_endtry(J);
js_free(J, sb);
}
}
Commit Message: Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed().
32 is not enough to fit sprintf("%.20f", 1e20).
We need at least 43 bytes to fit that format.
Bump the static buffer size.
CWE ID: CWE-119 | static void Np_toString(js_State *J)
{
char buf[100];
js_Object *self = js_toobject(J, 0);
int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);
if (self->type != JS_CNUMBER)
js_typeerror(J, "not a number");
if (radix == 10) {
js_pushstring(J, jsV_numbertostring(J, buf, self->u.number));
return;
}
if (radix < 2 || radix > 36)
js_rangeerror(J, "invalid radix");
/* lame number to string conversion for any radix from 2 to 36 */
{
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
double number = self->u.number;
int sign = self->u.number < 0;
js_Buffer *sb = NULL;
uint64_t u, limit = ((uint64_t)1<<52);
int ndigits, exp, point;
if (number == 0) { js_pushstring(J, "0"); return; }
if (isnan(number)) { js_pushstring(J, "NaN"); return; }
if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; }
if (sign)
number = -number;
/* fit as many digits as we want in an int */
exp = 0;
while (number * pow(radix, exp) > limit)
--exp;
while (number * pow(radix, exp+1) < limit)
++exp;
u = number * pow(radix, exp) + 0.5;
/* trim trailing zeros */
while (u > 0 && (u % radix) == 0) {
u /= radix;
--exp;
}
/* serialize digits */
ndigits = 0;
while (u > 0) {
buf[ndigits++] = digits[u % radix];
u /= radix;
}
point = ndigits - exp;
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
if (sign)
js_putc(J, &sb, '-');
if (point <= 0) {
js_putc(J, &sb, '0');
js_putc(J, &sb, '.');
while (point++ < 0)
js_putc(J, &sb, '0');
while (ndigits-- > 0)
js_putc(J, &sb, buf[ndigits]);
} else {
while (ndigits-- > 0) {
js_putc(J, &sb, buf[ndigits]);
if (--point == 0 && ndigits > 0)
js_putc(J, &sb, '.');
}
while (point-- > 0)
js_putc(J, &sb, '0');
}
js_putc(J, &sb, 0);
js_pushstring(J, sb->s);
js_endtry(J);
js_free(J, sb);
}
}
| 169,703 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: store_image_check(PNG_CONST png_store* ps, png_const_structp pp, int iImage)
{
png_const_bytep image = ps->image;
if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
png_error(pp, "image overwrite");
else
{
png_size_t cbRow = ps->cb_row;
png_uint_32 rows = ps->image_h;
image += iImage * (cbRow+5) * ps->image_h;
image += 2; /* skip image first row markers */
while (rows-- > 0)
{
if (image[-2] != 190 || image[-1] != 239)
png_error(pp, "row start overwritten");
if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
image[cbRow+2] != 17)
png_error(pp, "row end overwritten");
image += cbRow+5;
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | store_image_check(PNG_CONST png_store* ps, png_const_structp pp, int iImage)
store_image_check(const png_store* ps, png_const_structp pp, int iImage)
{
png_const_bytep image = ps->image;
if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
png_error(pp, "image overwrite");
else
{
png_size_t cbRow = ps->cb_row;
png_uint_32 rows = ps->image_h;
image += iImage * (cbRow+5) * ps->image_h;
image += 2; /* skip image first row markers */
while (rows-- > 0)
{
if (image[-2] != 190 || image[-1] != 239)
png_error(pp, "row start overwritten");
if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
image[cbRow+2] != 17)
png_error(pp, "row end overwritten");
image += cbRow+5;
}
}
}
| 173,704 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strcat(line, buf);
strcat(line, " ");
e = e->next;
}
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strncat(line, buf, sizeof line);
strncat(line, " ", sizeof line);
e = e->next;
}
line[(sizeof line)-1] = '\0'; /* make sure it's NUL terminated */
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
| 169,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_error_quark (void)
{
static GQuark quark = 0;
if (!quark)
quark = g_quark_from_static_string ("my_object_error");
return quark;
}
Commit Message:
CWE ID: CWE-264 | my_object_error_quark (void)
| 165,098 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_png(struct control *control)
/* Read a PNG, return 0 on success else an error (status) code; a bit mask as
* defined for file::status_code as above.
*/
{
png_structp png_ptr;
png_infop info_ptr = NULL;
volatile png_bytep row = NULL, display = NULL;
volatile int rc;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
error_handler, warning_handler);
if (png_ptr == NULL)
{
/* This is not really expected. */
log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
control->file.status_code |= INTERNAL_ERROR;
return LIBPNG_ERROR_CODE;
}
rc = setjmp(control->file.jmpbuf);
if (rc == 0)
{
png_set_read_fn(png_ptr, control, read_callback);
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
png_error(png_ptr, "OOM allocating info structure");
if (control->file.global->verbose)
fprintf(stderr, " INFO\n");
png_read_info(png_ptr, info_ptr);
{
png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
row = png_voidcast(png_byte*, malloc(rowbytes));
display = png_voidcast(png_byte*, malloc(rowbytes));
if (row == NULL || display == NULL)
png_error(png_ptr, "OOM allocating row buffers");
{
png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
int passes = png_set_interlace_handling(png_ptr);
int pass;
png_start_read_image(png_ptr);
for (pass = 0; pass < passes; ++pass)
{
png_uint_32 y = height;
/* NOTE: this trashes the row each time; interlace handling won't
* work, but this avoids memory thrashing for speed testing.
*/
while (y-- > 0)
png_read_row(png_ptr, row, display);
}
}
}
if (control->file.global->verbose)
fprintf(stderr, " END\n");
/* Make sure to read to the end of the file: */
png_read_end(png_ptr, info_ptr);
}
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
if (row != NULL) free(row);
if (display != NULL) free(display);
return rc;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | read_png(struct control *control)
/* Read a PNG, return 0 on success else an error (status) code; a bit mask as
* defined for file::status_code as above.
*/
{
png_structp png_ptr;
png_infop info_ptr = NULL;
volatile int rc;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
error_handler, warning_handler);
if (png_ptr == NULL)
{
/* This is not really expected. */
log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
control->file.status_code |= INTERNAL_ERROR;
return LIBPNG_ERROR_CODE;
}
rc = setjmp(control->file.jmpbuf);
if (rc == 0)
{
# ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Remove any limits on the size of PNG files that can be read,
* without this we may reject files based on built-in safety
* limits.
*/
png_set_user_limits(png_ptr, 0x7fffffff, 0x7fffffff);
png_set_chunk_cache_max(png_ptr, 0);
png_set_chunk_malloc_max(png_ptr, 0);
# endif
png_set_read_fn(png_ptr, control, read_callback);
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
png_error(png_ptr, "OOM allocating info structure");
if (control->file.global->verbose)
fprintf(stderr, " INFO\n");
png_read_info(png_ptr, info_ptr);
{
png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
int passes = png_set_interlace_handling(png_ptr);
int pass;
png_start_read_image(png_ptr);
for (pass = 0; pass < passes; ++pass)
{
png_uint_32 y = height;
/* NOTE: this skips asking libpng to return either version of
* the image row, but libpng still reads the rows.
*/
while (y-- > 0)
png_read_row(png_ptr, NULL, NULL);
}
}
if (control->file.global->verbose)
fprintf(stderr, " END\n");
/* Make sure to read to the end of the file: */
png_read_end(png_ptr, info_ptr);
}
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return rc;
}
| 173,738 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::prepareForAdaptivePlayback(
OMX_U32 portIndex, OMX_BOOL enable, OMX_U32 maxFrameWidth,
OMX_U32 maxFrameHeight) {
Mutex::Autolock autolock(mLock);
CLOG_CONFIG(prepareForAdaptivePlayback, "%s:%u en=%d max=%ux%u",
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.prepareForAdaptivePlayback");
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err != OMX_ErrorNone) {
CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name);
return StatusFromOMXError(err);
}
PrepareForAdaptivePlaybackParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.bEnable = enable;
params.nMaxFrameWidth = maxFrameWidth;
params.nMaxFrameHeight = maxFrameHeight;
err = OMX_SetParameter(mHandle, index, ¶ms);
CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d max=%ux%u", name, index,
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::prepareForAdaptivePlayback(
OMX_U32 portIndex, OMX_BOOL enable, OMX_U32 maxFrameWidth,
OMX_U32 maxFrameHeight) {
Mutex::Autolock autolock(mLock);
if (mSailed) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
CLOG_CONFIG(prepareForAdaptivePlayback, "%s:%u en=%d max=%ux%u",
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.prepareForAdaptivePlayback");
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err != OMX_ErrorNone) {
CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name);
return StatusFromOMXError(err);
}
PrepareForAdaptivePlaybackParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.bEnable = enable;
params.nMaxFrameWidth = maxFrameWidth;
params.nMaxFrameHeight = maxFrameHeight;
err = OMX_SetParameter(mHandle, index, ¶ms);
CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d max=%ux%u", name, index,
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
return StatusFromOMXError(err);
}
| 174,136 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add confusability mapping entries for Myanmar and Georgian
U+10D5 (ვ), U+1012 (ဒ) => 3
Bug: 847242, 849398
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I9abb8560cf1c9e8e5e8d89980780b89461f7be52
Reviewed-on: https://chromium-review.googlesource.com/1091430
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565709}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+0437 (з), U+0499 (ҙ), U+04E1 (ӡ), U+10D5 (ვ), U+1012 (ဒ)} => 3
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,152 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RegisterProperties(IBusPropList* ibus_prop_list) {
DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
RegisterProperties(NULL);
return;
}
}
register_ime_properties_(language_library_, prop_list);
}
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 RegisterProperties(IBusPropList* ibus_prop_list) {
void DoRegisterProperties(IBusPropList* ibus_prop_list) {
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
DoRegisterProperties(NULL);
return;
}
}
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
| 170,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport void RemoveDuplicateLayers(Image **images,
ExceptionInfo *exception)
{
register Image
*curr,
*next;
RectangleInfo
bounds;
assert((*images) != (const Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
curr=GetFirstImageInList(*images);
for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next)
{
if ( curr->columns != next->columns || curr->rows != next->rows
|| curr->page.x != next->page.x || curr->page.y != next->page.y )
continue;
bounds=CompareImageBounds(curr,next,CompareAnyLayer,exception);
if ( bounds.x < 0 ) {
/*
the two images are the same, merge time delays and delete one.
*/
size_t time;
time = curr->delay*1000/curr->ticks_per_second;
time += next->delay*1000/next->ticks_per_second;
next->ticks_per_second = 100L;
next->delay = time*curr->ticks_per_second/1000;
next->iterations = curr->iterations;
*images = curr;
(void) DeleteImageFromList(images);
}
}
*images = GetFirstImageInList(*images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629
CWE ID: CWE-369 | MagickExport void RemoveDuplicateLayers(Image **images,
MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception)
{
RectangleInfo
bounds;
register Image
*image,
*next;
assert((*images) != (const Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=GetFirstImageInList(*images);
for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next)
{
if ((image->columns != next->columns) || (image->rows != next->rows) ||
(image->page.x != next->page.x) || (image->page.y != next->page.y))
continue;
bounds=CompareImageBounds(image,next,CompareAnyLayer,exception);
if (bounds.x < 0)
{
/*
Two images are the same, merge time delays and delete one.
*/
size_t
time;
time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second);
time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second);
next->ticks_per_second=100L;
next->delay=time*image->ticks_per_second/1000;
next->iterations=image->iterations;
*images=image;
(void) DeleteImageFromList(images);
}
}
*images=GetFirstImageInList(*images);
}
| 169,588 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool BaseSessionService::RestoreUpdateTabNavigationCommand(
const SessionCommand& command,
TabNavigation* navigation,
SessionID::id_type* tab_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
std::string url_spec;
if (!pickle->ReadInt(&iterator, tab_id) ||
!pickle->ReadInt(&iterator, &(navigation->index_)) ||
!pickle->ReadString(&iterator, &url_spec) ||
!pickle->ReadString16(&iterator, &(navigation->title_)) ||
!pickle->ReadString(&iterator, &(navigation->state_)) ||
!pickle->ReadInt(&iterator,
reinterpret_cast<int*>(&(navigation->transition_))))
return false;
bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_));
if (has_type_mask) {
std::string referrer_spec;
pickle->ReadString(&iterator, &referrer_spec);
int policy_int;
WebReferrerPolicy policy;
if (pickle->ReadInt(&iterator, &policy_int))
policy = static_cast<WebReferrerPolicy>(policy_int);
else
policy = WebKit::WebReferrerPolicyDefault;
navigation->referrer_ = content::Referrer(
referrer_spec.empty() ? GURL() : GURL(referrer_spec),
policy);
std::string content_state;
if (CompressDataHelper::ReadAndDecompressStringFromPickle(
*pickle.get(), &iterator, &content_state) &&
!content_state.empty()) {
navigation->state_ = content_state;
}
}
navigation->virtual_url_ = GURL(url_spec);
return true;
}
Commit Message: Metrics for measuring how much overhead reading compressed content states adds.
BUG=104293
TEST=NONE
Review URL: https://chromiumcodereview.appspot.com/9426039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@123733 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool BaseSessionService::RestoreUpdateTabNavigationCommand(
const SessionCommand& command,
TabNavigation* navigation,
SessionID::id_type* tab_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
std::string url_spec;
if (!pickle->ReadInt(&iterator, tab_id) ||
!pickle->ReadInt(&iterator, &(navigation->index_)) ||
!pickle->ReadString(&iterator, &url_spec) ||
!pickle->ReadString16(&iterator, &(navigation->title_)) ||
!pickle->ReadString(&iterator, &(navigation->state_)) ||
!pickle->ReadInt(&iterator,
reinterpret_cast<int*>(&(navigation->transition_))))
return false;
bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_));
if (has_type_mask) {
std::string referrer_spec;
pickle->ReadString(&iterator, &referrer_spec);
int policy_int;
WebReferrerPolicy policy;
if (pickle->ReadInt(&iterator, &policy_int))
policy = static_cast<WebReferrerPolicy>(policy_int);
else
policy = WebKit::WebReferrerPolicyDefault;
navigation->referrer_ = content::Referrer(
referrer_spec.empty() ? GURL() : GURL(referrer_spec),
policy);
base::TimeTicks start_time_ = base::TimeTicks::Now();
std::string content_state;
if (CompressDataHelper::ReadAndDecompressStringFromPickle(
*pickle.get(), &iterator, &content_state) &&
!content_state.empty()) {
navigation->state_ = content_state;
}
base::TimeDelta total_time = base::TimeTicks::Now() - start_time_;
time_spent_reading_compressed_content_states += total_time;
}
navigation->virtual_url_ = GURL(url_spec);
return true;
}
| 171,050 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: psf_close (SF_PRIVATE *psf)
{ uint32_t k ;
int error = 0 ;
if (psf->codec_close)
{ error = psf->codec_close (psf) ;
/* To prevent it being called in psf->container_close(). */
psf->codec_close = NULL ;
} ;
if (psf->container_close)
error = psf->container_close (psf) ;
error = psf_fclose (psf) ;
psf_close_rsrc (psf) ;
/* For an ISO C compliant implementation it is ok to free a NULL pointer. */
free (psf->container_data) ;
free (psf->codec_data) ;
free (psf->interleave) ;
free (psf->dither) ;
free (psf->peak_info) ;
free (psf->broadcast_16k) ;
free (psf->loop_info) ;
free (psf->instrument) ;
free (psf->cues) ;
free (psf->channel_map) ;
free (psf->format_desc) ;
free (psf->strings.storage) ;
if (psf->wchunks.chunks)
for (k = 0 ; k < psf->wchunks.used ; k++)
free (psf->wchunks.chunks [k].data) ;
free (psf->rchunks.chunks) ;
free (psf->wchunks.chunks) ;
free (psf->iterator) ;
free (psf->cart_16k) ;
memset (psf, 0, sizeof (SF_PRIVATE)) ;
free (psf) ;
return error ;
} /* psf_close */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | psf_close (SF_PRIVATE *psf)
{ uint32_t k ;
int error = 0 ;
if (psf->codec_close)
{ error = psf->codec_close (psf) ;
/* To prevent it being called in psf->container_close(). */
psf->codec_close = NULL ;
} ;
if (psf->container_close)
error = psf->container_close (psf) ;
error = psf_fclose (psf) ;
psf_close_rsrc (psf) ;
/* For an ISO C compliant implementation it is ok to free a NULL pointer. */
free (psf->header.ptr) ;
free (psf->container_data) ;
free (psf->codec_data) ;
free (psf->interleave) ;
free (psf->dither) ;
free (psf->peak_info) ;
free (psf->broadcast_16k) ;
free (psf->loop_info) ;
free (psf->instrument) ;
free (psf->cues) ;
free (psf->channel_map) ;
free (psf->format_desc) ;
free (psf->strings.storage) ;
if (psf->wchunks.chunks)
for (k = 0 ; k < psf->wchunks.used ; k++)
free (psf->wchunks.chunks [k].data) ;
free (psf->rchunks.chunks) ;
free (psf->wchunks.chunks) ;
free (psf->iterator) ;
free (psf->cart_16k) ;
memset (psf, 0, sizeof (SF_PRIVATE)) ;
free (psf) ;
return error ;
} /* psf_close */
| 170,066 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len,
unsigned char *iccsn, size_t *iccsn_len,
unsigned char *chn, size_t *chn_len)
{
int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0;
const unsigned char *p = gdo;
size_t left = gdo_len;
while (left >= 2) {
unsigned int cla, tag;
size_t tag_len;
r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len);
if (r != SC_SUCCESS) {
if (r == SC_ERROR_ASN1_END_OF_CONTENTS) {
/* not enough data */
r = SC_SUCCESS;
}
break;
}
if (p == NULL) {
/* done parsing */
break;
}
if (cla == SC_ASN1_TAG_APPLICATION) {
switch (tag) {
case 0x1A:
iccsn_found = 1;
if (iccsn && iccsn_len) {
memcpy(iccsn, p, MIN(tag_len, *iccsn_len));
*iccsn_len = MIN(tag_len, *iccsn_len);
}
break;
case 0x1F20:
chn_found = 1;
if (chn && chn_len) {
memcpy(chn, p, MIN(tag_len, *chn_len));
*chn_len = MIN(tag_len, *chn_len);
}
break;
}
}
p += tag_len;
left -= (p - gdo);
}
if (!iccsn_found && iccsn_len)
*iccsn_len = 0;
if (!chn_found && chn_len)
*chn_len = 0;
return r;
}
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 | sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len,
unsigned char *iccsn, size_t *iccsn_len,
unsigned char *chn, size_t *chn_len)
{
int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0;
const unsigned char *p = gdo;
size_t left = gdo_len;
while (left >= 2) {
unsigned int cla, tag;
size_t tag_len;
r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len);
if (r != SC_SUCCESS) {
if (r == SC_ERROR_ASN1_END_OF_CONTENTS) {
/* not enough data */
r = SC_SUCCESS;
}
break;
}
if (p == NULL) {
/* done parsing */
break;
}
if (cla == SC_ASN1_TAG_APPLICATION) {
switch (tag) {
case 0x1A:
iccsn_found = 1;
if (iccsn && iccsn_len) {
memcpy(iccsn, p, MIN(tag_len, *iccsn_len));
*iccsn_len = MIN(tag_len, *iccsn_len);
}
break;
case 0x1F20:
chn_found = 1;
if (chn && chn_len) {
memcpy(chn, p, MIN(tag_len, *chn_len));
*chn_len = MIN(tag_len, *chn_len);
}
break;
}
}
p += tag_len;
left = gdo_len - (p - gdo);
}
if (!iccsn_found && iccsn_len)
*iccsn_len = 0;
if (!chn_found && chn_len)
*chn_len = 0;
return r;
}
| 169,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev,
struct nci_rf_intf_activated_ntf *ntf, __u8 *data)
{
struct activation_params_nfca_poll_iso_dep *nfca_poll;
struct activation_params_nfcb_poll_iso_dep *nfcb_poll;
switch (ntf->activation_rf_tech_and_mode) {
case NCI_NFC_A_PASSIVE_POLL_MODE:
nfca_poll = &ntf->activation_params.nfca_poll_iso_dep;
nfca_poll->rats_res_len = *data++;
pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len);
if (nfca_poll->rats_res_len > 0) {
memcpy(nfca_poll->rats_res,
data, nfca_poll->rats_res_len);
}
break;
case NCI_NFC_B_PASSIVE_POLL_MODE:
nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep;
nfcb_poll->attrib_res_len = *data++;
pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len);
if (nfcb_poll->attrib_res_len > 0) {
memcpy(nfcb_poll->attrib_res,
data, nfcb_poll->attrib_res_len);
}
break;
default:
pr_err("unsupported activation_rf_tech_and_mode 0x%x\n",
ntf->activation_rf_tech_and_mode);
return NCI_STATUS_RF_PROTOCOL_ERROR;
}
return NCI_STATUS_OK;
}
Commit Message: NFC: Prevent multiple buffer overflows in NCI
Fix multiple remotely-exploitable stack-based buffer overflows due to
the NCI code pulling length fields directly from incoming frames and
copying too much data into statically-sized arrays.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: Lauro Ramos Venancio <[email protected]>
Cc: Aloisio Almeida Jr <[email protected]>
Cc: Samuel Ortiz <[email protected]>
Cc: David S. Miller <[email protected]>
Acked-by: Ilan Elias <[email protected]>
Signed-off-by: Samuel Ortiz <[email protected]>
CWE ID: CWE-119 | static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev,
struct nci_rf_intf_activated_ntf *ntf, __u8 *data)
{
struct activation_params_nfca_poll_iso_dep *nfca_poll;
struct activation_params_nfcb_poll_iso_dep *nfcb_poll;
switch (ntf->activation_rf_tech_and_mode) {
case NCI_NFC_A_PASSIVE_POLL_MODE:
nfca_poll = &ntf->activation_params.nfca_poll_iso_dep;
nfca_poll->rats_res_len = min_t(__u8, *data++, 20);
pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len);
if (nfca_poll->rats_res_len > 0) {
memcpy(nfca_poll->rats_res,
data, nfca_poll->rats_res_len);
}
break;
case NCI_NFC_B_PASSIVE_POLL_MODE:
nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep;
nfcb_poll->attrib_res_len = min_t(__u8, *data++, 50);
pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len);
if (nfcb_poll->attrib_res_len > 0) {
memcpy(nfcb_poll->attrib_res,
data, nfcb_poll->attrib_res_len);
}
break;
default:
pr_err("unsupported activation_rf_tech_and_mode 0x%x\n",
ntf->activation_rf_tech_and_mode);
return NCI_STATUS_RF_PROTOCOL_ERROR;
}
return NCI_STATUS_OK;
}
| 166,200 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static char* cJSON_strdup( const char* str )
{
size_t len;
char* copy;
len = strlen( str ) + 1;
if ( ! ( copy = (char*) cJSON_malloc( len ) ) )
return 0;
memcpy( copy, str, len );
return copy;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static char* cJSON_strdup( const char* str )
void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (!hooks) { /* Reset hooks */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}
| 167,298 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
int id,
const GURL& image_url,
image_downloader::DownloadResultPtr result) {
DCHECK(result);
const std::vector<SkBitmap> images =
result->images.To<std::vector<SkBitmap>>();
const std::vector<gfx::Size> original_image_sizes =
result->original_image_sizes.To<std::vector<gfx::Size>>();
callback.Run(id, result->http_status_code, image_url, images,
original_image_sizes);
}
Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted
BUG=583718
Review URL: https://codereview.chromium.org/1685343004
Cr-Commit-Position: refs/heads/master@{#375700}
CWE ID: | static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
| 172,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END 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_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
/* high 32 bits are known zero. */
regs[insn->dst_reg].var_off = tnum_cast(
regs[insn->dst_reg].var_off, 4);
__update_reg_bounds(®s[insn->dst_reg]);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
Commit Message: bpf: fix incorrect tracking of register size truncation
Properly handle register truncation to a smaller size.
The old code first mirrors the clearing of the high 32 bits in the bitwise
tristate representation, which is correct. But then, it computes the new
arithmetic bounds as the intersection between the old arithmetic bounds and
the bounds resulting from the bitwise tristate representation. Therefore,
when coerce_reg_to_32() is called on a number with bounds
[0xffff'fff8, 0x1'0000'0007], the verifier computes
[0xffff'fff8, 0xffff'ffff] as bounds of the truncated number.
This is incorrect: The truncated number could also be in the range [0, 7],
and no meaningful arithmetic bounds can be computed in that case apart from
the obvious [0, 0xffff'ffff].
Starting with v4.14, this is exploitable by unprivileged users as long as
the unprivileged_bpf_disabled sysctl isn't set.
Debian assigned CVE-2017-16996 for this issue.
v2:
- flip the mask during arithmetic bounds calculation (Ben Hutchings)
v3:
- add CVE number (Ben Hutchings)
Fixes: b03c9f9fdc37 ("bpf/verifier: track signed and unsigned min/max values")
Signed-off-by: Jann Horn <[email protected]>
Acked-by: Edward Cree <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-119 | static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END 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_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
coerce_reg_to_size(®s[insn->dst_reg], 4);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
| 167,658 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out)
{
#if 0
jp2_pclr_t *pclr = &box->data.pclr;
#endif
/* Eliminate warning about unused variable. */
box = 0;
out = 0;
return -1;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476 | static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out)
{
#if 0
jp2_pclr_t *pclr = &box->data.pclr;
#endif
/* Eliminate warning about unused variable. */
box = 0;
out = 0;
return -1;
}
| 168,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int btpan_tap_open()
{
struct ifreq ifr;
int fd, err;
const char *clonedev = "/dev/tun";
/* open the clone device */
if ((fd = open(clonedev, O_RDWR)) < 0)
{
BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
return fd;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
/* try to create the device */
if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0)
{
BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
close(fd);
return err;
}
if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0)
{
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
return fd;
}
BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME);
close(fd);
return INVALID_FD;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | int btpan_tap_open()
{
struct ifreq ifr;
int fd, err;
const char *clonedev = "/dev/tun";
/* open the clone device */
if ((fd = TEMP_FAILURE_RETRY(open(clonedev, O_RDWR))) < 0)
{
BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
return fd;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
/* try to create the device */
if ((err = TEMP_FAILURE_RETRY(ioctl(fd, TUNSETIFF, (void *) &ifr))) < 0)
{
BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
close(fd);
return err;
}
if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0)
{
int flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL, 0));
TEMP_FAILURE_RETRY(fcntl(fd, F_SETFL, flags | O_NONBLOCK));
return fd;
}
BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME);
close(fd);
return INVALID_FD;
}
| 173,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OomInterventionTabHelper::StartDetectionInRenderer() {
auto* config = OomInterventionConfig::GetInstance();
bool renderer_pause_enabled = config->is_renderer_pause_enabled();
bool navigate_ads_enabled = config->is_navigate_ads_enabled();
if ((renderer_pause_enabled || navigate_ads_enabled) && decider_) {
DCHECK(!web_contents()->GetBrowserContext()->IsOffTheRecord());
const std::string& host = web_contents()->GetVisibleURL().host();
if (!decider_->CanTriggerIntervention(host)) {
renderer_pause_enabled = false;
navigate_ads_enabled = false;
}
}
content::RenderFrameHost* main_frame = web_contents()->GetMainFrame();
DCHECK(main_frame);
content::RenderProcessHost* render_process_host = main_frame->GetProcess();
DCHECK(render_process_host);
content::BindInterface(render_process_host,
mojo::MakeRequest(&intervention_));
DCHECK(!binding_.is_bound());
blink::mojom::OomInterventionHostPtr host;
binding_.Bind(mojo::MakeRequest(&host));
blink::mojom::DetectionArgsPtr detection_args =
config->GetRendererOomDetectionArgs();
intervention_->StartDetection(std::move(host), std::move(detection_args),
renderer_pause_enabled, navigate_ads_enabled);
}
Commit Message: OomIntervention opt-out should work properly with 'show original'
OomIntervention should not be re-triggered on the same page if the user declines the intervention once.
This CL fixes the bug.
Bug: 889131, 887119
Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8
Reviewed-on: https://chromium-review.googlesource.com/1245019
Commit-Queue: Yuzu Saijo <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#594574}
CWE ID: CWE-119 | void OomInterventionTabHelper::StartDetectionInRenderer() {
auto* config = OomInterventionConfig::GetInstance();
bool renderer_pause_enabled = config->is_renderer_pause_enabled();
bool navigate_ads_enabled = config->is_navigate_ads_enabled();
if ((renderer_pause_enabled || navigate_ads_enabled) && decider_) {
DCHECK(!web_contents()->GetBrowserContext()->IsOffTheRecord());
const std::string& host = web_contents()->GetVisibleURL().host();
if (!decider_->CanTriggerIntervention(host)) {
renderer_pause_enabled = false;
navigate_ads_enabled = false;
}
}
if (!renderer_pause_enabled && !navigate_ads_enabled)
return;
content::RenderFrameHost* main_frame = web_contents()->GetMainFrame();
DCHECK(main_frame);
content::RenderProcessHost* render_process_host = main_frame->GetProcess();
DCHECK(render_process_host);
content::BindInterface(render_process_host,
mojo::MakeRequest(&intervention_));
DCHECK(!binding_.is_bound());
blink::mojom::OomInterventionHostPtr host;
binding_.Bind(mojo::MakeRequest(&host));
blink::mojom::DetectionArgsPtr detection_args =
config->GetRendererOomDetectionArgs();
intervention_->StartDetection(std::move(host), std::move(detection_args),
renderer_pause_enabled, navigate_ads_enabled);
}
| 172,114 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zend_bool use_include_path = 0;
zval *arg1, *arg2;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
switch (source->type) {
case SPL_FS_INFO:
case SPL_FS_FILE:
break;
case SPL_FS_DIR:
if (!source->u.dir.entry.d_name[0]) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file");
zend_restore_error_handling(&error_handling TSRMLS_CC);
return NULL;
}
}
switch (type) {
case SPL_FS_INFO:
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
spl_filesystem_object_get_file_name(source TSRMLS_CC);
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
intern->file_name = estrndup(source->file_name, source->file_name_len);
intern->file_name_len = source->file_name_len;
intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);
intern->_path = estrndup(intern->_path, intern->_path_len);
}
break;
case SPL_FS_FILE:
ce = ce ? ce : source->file_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
spl_filesystem_object_get_file_name(source TSRMLS_CC);
if (ce->constructor->common.scope != spl_ce_SplFileObject) {
MAKE_STD_ZVAL(arg1);
MAKE_STD_ZVAL(arg2);
ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);
ZVAL_STRINGL(arg2, "r", 1, 1);
zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2);
zval_ptr_dtor(&arg1);
zval_ptr_dtor(&arg2);
} else {
intern->file_name = source->file_name;
intern->file_name_len = source->file_name_len;
intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);
intern->_path = estrndup(intern->_path, intern->_path_len);
intern->u.file.open_mode = "r";
intern->u.file.open_mode_len = 1;
if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr",
&intern->u.file.open_mode, &intern->u.file.open_mode_len,
&use_include_path, &intern->u.file.zcontext) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
intern->u.file.open_mode = NULL;
intern->file_name = NULL;
zval_dtor(return_value);
Z_TYPE_P(return_value) = IS_NULL;
return NULL;
}
if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
zval_dtor(return_value);
Z_TYPE_P(return_value) = IS_NULL;
return NULL;
}
}
break;
case SPL_FS_DIR:
zend_restore_error_handling(&error_handling TSRMLS_CC);
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported");
return NULL;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return NULL;
} /* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zend_bool use_include_path = 0;
zval *arg1, *arg2;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
switch (source->type) {
case SPL_FS_INFO:
case SPL_FS_FILE:
break;
case SPL_FS_DIR:
if (!source->u.dir.entry.d_name[0]) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file");
zend_restore_error_handling(&error_handling TSRMLS_CC);
return NULL;
}
}
switch (type) {
case SPL_FS_INFO:
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
spl_filesystem_object_get_file_name(source TSRMLS_CC);
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
intern->file_name = estrndup(source->file_name, source->file_name_len);
intern->file_name_len = source->file_name_len;
intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);
intern->_path = estrndup(intern->_path, intern->_path_len);
}
break;
case SPL_FS_FILE:
ce = ce ? ce : source->file_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
spl_filesystem_object_get_file_name(source TSRMLS_CC);
if (ce->constructor->common.scope != spl_ce_SplFileObject) {
MAKE_STD_ZVAL(arg1);
MAKE_STD_ZVAL(arg2);
ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);
ZVAL_STRINGL(arg2, "r", 1, 1);
zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2);
zval_ptr_dtor(&arg1);
zval_ptr_dtor(&arg2);
} else {
intern->file_name = source->file_name;
intern->file_name_len = source->file_name_len;
intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);
intern->_path = estrndup(intern->_path, intern->_path_len);
intern->u.file.open_mode = "r";
intern->u.file.open_mode_len = 1;
if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr",
&intern->u.file.open_mode, &intern->u.file.open_mode_len,
&use_include_path, &intern->u.file.zcontext) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
intern->u.file.open_mode = NULL;
intern->file_name = NULL;
zval_dtor(return_value);
Z_TYPE_P(return_value) = IS_NULL;
return NULL;
}
if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
zval_dtor(return_value);
Z_TYPE_P(return_value) = IS_NULL;
return NULL;
}
}
break;
case SPL_FS_DIR:
zend_restore_error_handling(&error_handling TSRMLS_CC);
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported");
return NULL;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return NULL;
} /* }}} */
| 167,082 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Segment::ParseCues(long long off, long long& pos, long& len) {
if (m_pCues)
return 0; // success
if (off < 0)
return -1;
long long total, avail;
const int status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_start + off;
if ((total < 0) || (pos >= total))
return 1; // don't bother parsing cues
const long long element_start = pos;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id != 0x0C53BB6B) // Cues ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID
assert((segment_stop < 0) || (pos <= segment_stop));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
if (size == 0) // weird, although technically not illegal
return 1; // done
pos += len; // consume length of size of element
assert((segment_stop < 0) || (pos <= segment_stop));
const long long element_stop = pos + size;
if ((segment_stop >= 0) && (element_stop > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && (element_stop > total))
return 1; // don't bother parsing anymore
len = static_cast<long>(size);
if (element_stop > avail)
return E_BUFFER_NOT_FULL;
const long long element_size = element_stop - element_start;
m_pCues =
new (std::nothrow) Cues(this, pos, size, element_start, element_size);
assert(m_pCues); // TODO
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Segment::ParseCues(long long off, long long& pos, long& len) {
if (m_pCues)
return 0; // success
if (off < 0)
return -1;
long long total, avail;
const int status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_start + off;
if ((total < 0) || (pos >= total))
return 1; // don't bother parsing cues
const long long element_start = pos;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadID(m_pReader, idpos, len);
if (id != 0x0C53BB6B) // Cues ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID
assert((segment_stop < 0) || (pos <= segment_stop));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
if (size == 0) // weird, although technically not illegal
return 1; // done
pos += len; // consume length of size of element
assert((segment_stop < 0) || (pos <= segment_stop));
const long long element_stop = pos + size;
if ((segment_stop >= 0) && (element_stop > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && (element_stop > total))
return 1; // don't bother parsing anymore
len = static_cast<long>(size);
if (element_stop > avail)
return E_BUFFER_NOT_FULL;
const long long element_size = element_stop - element_start;
m_pCues =
new (std::nothrow) Cues(this, pos, size, element_start, element_size);
if (m_pCues == NULL)
return -1;
return 0; // success
}
| 173,852 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const PPB_NaCl_Private* GetNaclInterface() {
pp::Module *module = pp::Module::Get();
CHECK(module);
return static_cast<const PPB_NaCl_Private*>(
module->GetBrowserInterface(PPB_NACL_PRIVATE_INTERFACE));
}
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 | const PPB_NaCl_Private* GetNaclInterface() {
| 170,741 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
Commit Message: Fixed bug #72227: imagescale out-of-bounds read
Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a
CWE ID: CWE-125 | static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
| 170,004 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int svc_rdma_recvfrom(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma_xprt =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct svc_rdma_op_ctxt *ctxt = NULL;
struct rpcrdma_msg *rmsgp;
int ret = 0;
dprintk("svcrdma: rqstp=%p\n", rqstp);
spin_lock(&rdma_xprt->sc_rq_dto_lock);
if (!list_empty(&rdma_xprt->sc_read_complete_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
rdma_read_complete(rqstp, ctxt);
goto complete;
} else if (!list_empty(&rdma_xprt->sc_rq_dto_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
} else {
atomic_inc(&rdma_stat_rq_starve);
clear_bit(XPT_DATA, &xprt->xpt_flags);
ctxt = NULL;
}
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
if (!ctxt) {
/* This is the EAGAIN path. The svc_recv routine will
* return -EAGAIN, the nfsd thread will go to call into
* svc_recv again and we shouldn't be on the active
* transport list
*/
if (test_bit(XPT_CLOSE, &xprt->xpt_flags))
goto defer;
goto out;
}
dprintk("svcrdma: processing ctxt=%p on xprt=%p, rqstp=%p\n",
ctxt, rdma_xprt, rqstp);
atomic_inc(&rdma_stat_recv);
/* Build up the XDR from the receive buffers. */
rdma_build_arg_xdr(rqstp, ctxt, ctxt->byte_len);
/* Decode the RDMA header. */
rmsgp = (struct rpcrdma_msg *)rqstp->rq_arg.head[0].iov_base;
ret = svc_rdma_xdr_decode_req(&rqstp->rq_arg);
if (ret < 0)
goto out_err;
if (ret == 0)
goto out_drop;
rqstp->rq_xprt_hlen = ret;
if (svc_rdma_is_backchannel_reply(xprt, rmsgp)) {
ret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt, rmsgp,
&rqstp->rq_arg);
svc_rdma_put_context(ctxt, 0);
if (ret)
goto repost;
return ret;
}
/* Read read-list data. */
ret = rdma_read_chunks(rdma_xprt, rmsgp, rqstp, ctxt);
if (ret > 0) {
/* read-list posted, defer until data received from client. */
goto defer;
} else if (ret < 0) {
/* Post of read-list failed, free context. */
svc_rdma_put_context(ctxt, 1);
return 0;
}
complete:
ret = rqstp->rq_arg.head[0].iov_len
+ rqstp->rq_arg.page_len
+ rqstp->rq_arg.tail[0].iov_len;
svc_rdma_put_context(ctxt, 0);
out:
dprintk("svcrdma: ret=%d, rq_arg.len=%u, "
"rq_arg.head[0].iov_base=%p, rq_arg.head[0].iov_len=%zd\n",
ret, rqstp->rq_arg.len,
rqstp->rq_arg.head[0].iov_base,
rqstp->rq_arg.head[0].iov_len);
rqstp->rq_prot = IPPROTO_MAX;
svc_xprt_copy_addrs(rqstp, xprt);
return ret;
out_err:
svc_rdma_send_error(rdma_xprt, rmsgp, ret);
svc_rdma_put_context(ctxt, 0);
return 0;
defer:
return 0;
out_drop:
svc_rdma_put_context(ctxt, 1);
repost:
return svc_rdma_repost_recv(rdma_xprt, GFP_KERNEL);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | int svc_rdma_recvfrom(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma_xprt =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct svc_rdma_op_ctxt *ctxt = NULL;
struct rpcrdma_msg *rmsgp;
int ret = 0;
dprintk("svcrdma: rqstp=%p\n", rqstp);
spin_lock(&rdma_xprt->sc_rq_dto_lock);
if (!list_empty(&rdma_xprt->sc_read_complete_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
rdma_read_complete(rqstp, ctxt);
goto complete;
} else if (!list_empty(&rdma_xprt->sc_rq_dto_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
} else {
atomic_inc(&rdma_stat_rq_starve);
clear_bit(XPT_DATA, &xprt->xpt_flags);
ctxt = NULL;
}
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
if (!ctxt) {
/* This is the EAGAIN path. The svc_recv routine will
* return -EAGAIN, the nfsd thread will go to call into
* svc_recv again and we shouldn't be on the active
* transport list
*/
if (test_bit(XPT_CLOSE, &xprt->xpt_flags))
goto defer;
goto out;
}
dprintk("svcrdma: processing ctxt=%p on xprt=%p, rqstp=%p\n",
ctxt, rdma_xprt, rqstp);
atomic_inc(&rdma_stat_recv);
/* Build up the XDR from the receive buffers. */
rdma_build_arg_xdr(rqstp, ctxt, ctxt->byte_len);
/* Decode the RDMA header. */
rmsgp = (struct rpcrdma_msg *)rqstp->rq_arg.head[0].iov_base;
ret = svc_rdma_xdr_decode_req(&rqstp->rq_arg);
if (ret < 0)
goto out_err;
if (ret == 0)
goto out_drop;
rqstp->rq_xprt_hlen = ret;
if (svc_rdma_is_backchannel_reply(xprt, &rmsgp->rm_xid)) {
ret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt,
&rmsgp->rm_xid,
&rqstp->rq_arg);
svc_rdma_put_context(ctxt, 0);
if (ret)
goto repost;
return ret;
}
/* Read read-list data. */
ret = rdma_read_chunks(rdma_xprt, rmsgp, rqstp, ctxt);
if (ret > 0) {
/* read-list posted, defer until data received from client. */
goto defer;
} else if (ret < 0) {
/* Post of read-list failed, free context. */
svc_rdma_put_context(ctxt, 1);
return 0;
}
complete:
ret = rqstp->rq_arg.head[0].iov_len
+ rqstp->rq_arg.page_len
+ rqstp->rq_arg.tail[0].iov_len;
svc_rdma_put_context(ctxt, 0);
out:
dprintk("svcrdma: ret=%d, rq_arg.len=%u, "
"rq_arg.head[0].iov_base=%p, rq_arg.head[0].iov_len=%zd\n",
ret, rqstp->rq_arg.len,
rqstp->rq_arg.head[0].iov_base,
rqstp->rq_arg.head[0].iov_len);
rqstp->rq_prot = IPPROTO_MAX;
svc_xprt_copy_addrs(rqstp, xprt);
return ret;
out_err:
svc_rdma_send_error(rdma_xprt, &rmsgp->rm_xid, ret);
svc_rdma_put_context(ctxt, 0);
return 0;
defer:
return 0;
out_drop:
svc_rdma_put_context(ctxt, 1);
repost:
return svc_rdma_repost_recv(rdma_xprt, GFP_KERNEL);
}
| 168,165 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[])
{
struct MHD_Daemon *d;
int port, opti, optc, cmdok, ret, slog_interval;
char *log_file, *slog_file;
program_name = argv[0];
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
server_data.www_dir = NULL;
#ifdef HAVE_GTOP
server_data.psysinfo.interfaces = NULL;
#endif
log_file = NULL;
slog_file = NULL;
slog_interval = 300;
port = DEFAULT_PORT;
cmdok = 1;
while ((optc = getopt_long(argc,
argv,
"vhp:w:d:l:",
long_options,
&opti)) != -1) {
switch (optc) {
case 'w':
if (optarg)
server_data.www_dir = strdup(optarg);
break;
case 'p':
if (optarg)
port = atoi(optarg);
break;
case 'h':
print_help();
switch (optc) {
case 'w':
if (optarg)
server_data.www_dir = strdup(optarg);
break;
case 'p':
if (optarg)
break;
case 'l':
if (optarg)
log_file = strdup(optarg);
break;
case 0:
if (!strcmp(long_options[opti].name, "sensor-log-file"))
slog_file = strdup(optarg);
else if (!strcmp(long_options[opti].name,
"sensor-log-interval"))
slog_interval = atoi(optarg);
break;
default:
cmdok = 0;
break;
}
}
if (!cmdok || optind != argc) {
fprintf(stderr, _("Try `%s --help' for more information.\n"),
program_name);
exit(EXIT_FAILURE);
}
if (!server_data.www_dir)
server_data.www_dir = strdup(DEFAULT_WWW_DIR);
if (!log_file)
log_file = strdup(DEFAULT_LOG_FILE);
pmutex_init(&mutex);
exit(EXIT_FAILURE);
}
if (!server_data.www_dir)
server_data.www_dir = strdup(DEFAULT_WWW_DIR);
if (!log_file)
log_file = strdup(DEFAULT_LOG_FILE);
port,
NULL, NULL, &cbk_http_request, server_data.sensors,
MHD_OPTION_END);
if (!d) {
log_err(_("Failed to create Web server."));
exit(EXIT_FAILURE);
}
log_info(_("Web server started on port: %d"), port);
log_info(_("WWW directory: %s"), server_data.www_dir);
log_info(_("URL: http://localhost:%d"), port);
if (slog_file) {
if (slog_interval <= 0)
slog_interval = 300;
ret = slog_activate(slog_file,
server_data.sensors,
&mutex,
slog_interval);
if (!ret)
log_err(_("Failed to activate logging of sensors."));
}
while (!server_stop_requested) {
pmutex_lock(&mutex);
#ifdef HAVE_GTOP
sysinfo_update(&server_data.psysinfo);
cpu_usage_sensor_update(server_data.cpu_usage);
#endif
#ifdef HAVE_ATASMART
atasmart_psensor_list_update(server_data.sensors);
#endif
hddtemp_psensor_list_update(server_data.sensors);
lmsensor_psensor_list_update(server_data.sensors);
psensor_log_measures(server_data.sensors);
pmutex_unlock(&mutex);
sleep(5);
}
slog_close();
MHD_stop_daemon(d);
/* sanity cleanup for valgrind */
psensor_list_free(server_data.sensors);
#ifdef HAVE_GTOP
psensor_free(server_data.cpu_usage);
#endif
free(server_data.www_dir);
lmsensor_cleanup();
#ifdef HAVE_GTOP
sysinfo_cleanup();
#endif
if (log_file != DEFAULT_LOG_FILE)
free(log_file);
return EXIT_SUCCESS;
}
Commit Message:
CWE ID: CWE-22 | int main(int argc, char *argv[])
{
struct MHD_Daemon *d;
int port, opti, optc, cmdok, ret, slog_interval;
char *log_file, *slog_file;
program_name = argv[0];
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
server_data.www_dir = NULL;
#ifdef HAVE_GTOP
server_data.psysinfo.interfaces = NULL;
#endif
log_file = NULL;
slog_file = NULL;
slog_interval = 300;
port = DEFAULT_PORT;
cmdok = 1;
while ((optc = getopt_long(argc,
argv,
"vhp:w:d:l:",
long_options,
&opti)) != -1) {
switch (optc) {
case 'w':
if (optarg)
server_data.www_dir = strdup(optarg);
break;
case 'p':
if (optarg)
port = atoi(optarg);
break;
case 'h':
print_help();
switch (optc) {
case 'w':
if (optarg)
server_data.www_dir = realpath(optarg, NULL);
break;
case 'p':
if (optarg)
break;
case 'l':
if (optarg)
log_file = strdup(optarg);
break;
case 0:
if (!strcmp(long_options[opti].name, "sensor-log-file"))
slog_file = strdup(optarg);
else if (!strcmp(long_options[opti].name,
"sensor-log-interval"))
slog_interval = atoi(optarg);
break;
default:
cmdok = 0;
break;
}
}
if (!cmdok || optind != argc) {
fprintf(stderr, _("Try `%s --help' for more information.\n"),
program_name);
exit(EXIT_FAILURE);
}
if (!server_data.www_dir)
server_data.www_dir = strdup(DEFAULT_WWW_DIR);
if (!log_file)
log_file = strdup(DEFAULT_LOG_FILE);
pmutex_init(&mutex);
exit(EXIT_FAILURE);
}
if (!server_data.www_dir) {
server_data.www_dir = realpath(DEFAULT_WWW_DIR, NULL);
if (!server_data.www_dir) {
fprintf(stderr,
_("Webserver directory does not exist.\n"));
exit(EXIT_FAILURE);
}
}
if (!log_file)
log_file = strdup(DEFAULT_LOG_FILE);
port,
NULL, NULL, &cbk_http_request, server_data.sensors,
MHD_OPTION_END);
if (!d) {
log_err(_("Failed to create Web server."));
exit(EXIT_FAILURE);
}
log_info(_("Web server started on port: %d"), port);
log_info(_("WWW directory: %s"), server_data.www_dir);
log_info(_("URL: http://localhost:%d"), port);
if (slog_file) {
if (slog_interval <= 0)
slog_interval = 300;
ret = slog_activate(slog_file,
server_data.sensors,
&mutex,
slog_interval);
if (!ret)
log_err(_("Failed to activate logging of sensors."));
}
while (!server_stop_requested) {
pmutex_lock(&mutex);
#ifdef HAVE_GTOP
sysinfo_update(&server_data.psysinfo);
cpu_usage_sensor_update(server_data.cpu_usage);
#endif
#ifdef HAVE_ATASMART
atasmart_psensor_list_update(server_data.sensors);
#endif
hddtemp_psensor_list_update(server_data.sensors);
lmsensor_psensor_list_update(server_data.sensors);
psensor_log_measures(server_data.sensors);
pmutex_unlock(&mutex);
sleep(5);
}
slog_close();
MHD_stop_daemon(d);
/* sanity cleanup for valgrind */
psensor_list_free(server_data.sensors);
#ifdef HAVE_GTOP
psensor_free(server_data.cpu_usage);
#endif
free(server_data.www_dir);
lmsensor_cleanup();
#ifdef HAVE_GTOP
sysinfo_cleanup();
#endif
if (log_file != DEFAULT_LOG_FILE)
free(log_file);
return EXIT_SUCCESS;
}
| 165,510 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DataReductionProxyConfigServiceClient::DataReductionProxyConfigServiceClient(
const net::BackoffEntry::Policy& backoff_policy,
DataReductionProxyRequestOptions* request_options,
DataReductionProxyMutableConfigValues* config_values,
DataReductionProxyConfig* config,
DataReductionProxyIOData* io_data,
network::NetworkConnectionTracker* network_connection_tracker,
ConfigStorer config_storer)
: request_options_(request_options),
config_values_(config_values),
config_(config),
io_data_(io_data),
network_connection_tracker_(network_connection_tracker),
config_storer_(config_storer),
backoff_policy_(backoff_policy),
backoff_entry_(&backoff_policy_),
config_service_url_(util::AddApiKeyToUrl(params::GetConfigServiceURL())),
enabled_(false),
remote_config_applied_(false),
#if defined(OS_ANDROID)
foreground_fetch_pending_(false),
#endif
previous_request_failed_authentication_(false),
failed_attempts_before_success_(0),
fetch_in_progress_(false),
client_config_override_used_(false) {
DCHECK(request_options);
DCHECK(config_values);
DCHECK(config);
DCHECK(io_data);
DCHECK(config_service_url_.is_valid());
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
client_config_override_ = command_line.GetSwitchValueASCII(
switches::kDataReductionProxyServerClientConfig);
thread_checker_.DetachFromThread();
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | DataReductionProxyConfigServiceClient::DataReductionProxyConfigServiceClient(
const net::BackoffEntry::Policy& backoff_policy,
DataReductionProxyRequestOptions* request_options,
DataReductionProxyMutableConfigValues* config_values,
DataReductionProxyConfig* config,
DataReductionProxyIOData* io_data,
network::NetworkConnectionTracker* network_connection_tracker,
ConfigStorer config_storer)
: request_options_(request_options),
config_values_(config_values),
config_(config),
io_data_(io_data),
network_connection_tracker_(network_connection_tracker),
config_storer_(config_storer),
backoff_policy_(backoff_policy),
backoff_entry_(&backoff_policy_),
config_service_url_(util::AddApiKeyToUrl(params::GetConfigServiceURL())),
enabled_(false),
remote_config_applied_(false),
#if defined(OS_ANDROID)
foreground_fetch_pending_(false),
#endif
previous_request_failed_authentication_(false),
failed_attempts_before_success_(0),
fetch_in_progress_(false),
client_config_override_used_(false) {
DCHECK(request_options);
DCHECK(config_values);
DCHECK(config);
DCHECK(io_data);
DCHECK(config_service_url_.is_valid());
DCHECK(!params::IsIncludedInHoldbackFieldTrial());
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
client_config_override_ = command_line.GetSwitchValueASCII(
switches::kDataReductionProxyServerClientConfig);
thread_checker_.DetachFromThread();
}
| 172,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t exitcode_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char *end, buf[sizeof("nnnnn\0")];
int tmp;
if (copy_from_user(buf, buffer, count))
return -EFAULT;
tmp = simple_strtol(buf, &end, 0);
if ((*end != '\0') && !isspace(*end))
return -EINVAL;
uml_exitcode = tmp;
return count;
}
Commit Message: uml: check length in exitcode_proc_write()
We don't cap the size of buffer from the user so we could write past the
end of the array here. Only root can write to this file.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119 | static ssize_t exitcode_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char *end, buf[sizeof("nnnnn\0")];
size_t size;
int tmp;
size = min(count, sizeof(buf));
if (copy_from_user(buf, buffer, size))
return -EFAULT;
tmp = simple_strtol(buf, &end, 0);
if ((*end != '\0') && !isspace(*end))
return -EINVAL;
uml_exitcode = tmp;
return count;
}
| 165,966 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BaseRenderingContext2D::Reset() {
ValidateStateStack();
UnwindStateStack();
state_stack_.resize(1);
state_stack_.front() = CanvasRenderingContext2DState::Create();
path_.Clear();
if (PaintCanvas* c = ExistingDrawingCanvas()) {
DCHECK_EQ(c->getSaveCount(), 2);
c->restore();
c->save();
DCHECK(c->getTotalMatrix().isIdentity());
#if DCHECK_IS_ON()
SkIRect clip_bounds;
DCHECK(c->getDeviceClipBounds(&clip_bounds));
DCHECK(clip_bounds == c->imageInfo().bounds());
#endif
}
ValidateStateStack();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Chris Harrelson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200 | void BaseRenderingContext2D::Reset() {
ValidateStateStack();
UnwindStateStack();
state_stack_.resize(1);
state_stack_.front() = CanvasRenderingContext2DState::Create();
path_.Clear();
if (PaintCanvas* c = ExistingDrawingCanvas()) {
DCHECK_EQ(c->getSaveCount(), 2);
c->restore();
c->save();
DCHECK(c->getTotalMatrix().isIdentity());
#if DCHECK_IS_ON()
SkIRect clip_bounds;
DCHECK(c->getDeviceClipBounds(&clip_bounds));
DCHECK(clip_bounds == c->imageInfo().bounds());
#endif
}
ValidateStateStack();
origin_tainted_by_content_ = false;
}
| 172,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_l2 la;
int len, err = 0;
BT_DBG("sk %p", sk);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
memset(&la, 0, sizeof(la));
len = min_t(unsigned int, sizeof(la), alen);
memcpy(&la, addr, len);
if (la.l2_cid)
return -EINVAL;
lock_sock(sk);
if (sk->sk_type == SOCK_SEQPACKET && !la.l2_psm) {
err = -EINVAL;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
switch (sk->sk_state) {
case BT_CONNECT:
case BT_CONNECT2:
case BT_CONFIG:
/* Already connecting */
goto wait;
case BT_CONNECTED:
/* Already connected */
goto done;
case BT_OPEN:
case BT_BOUND:
/* Can connect */
break;
default:
err = -EBADFD;
goto done;
}
/* Set destination address and psm */
bacpy(&bt_sk(sk)->dst, &la.l2_bdaddr);
l2cap_pi(sk)->psm = la.l2_psm;
err = l2cap_do_connect(sk);
if (err)
goto done;
wait:
err = bt_sock_wait_state(sk, BT_CONNECTED,
sock_sndtimeo(sk, flags & O_NONBLOCK));
done:
release_sock(sk);
return err;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_l2 la;
int len, err = 0;
BT_DBG("sk %p", sk);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
memset(&la, 0, sizeof(la));
len = min_t(unsigned int, sizeof(la), alen);
memcpy(&la, addr, len);
if (la.l2_cid)
return -EINVAL;
lock_sock(sk);
if (sk->sk_type == SOCK_SEQPACKET && !la.l2_psm) {
err = -EINVAL;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
case L2CAP_MODE_STREAMING:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
switch (sk->sk_state) {
case BT_CONNECT:
case BT_CONNECT2:
case BT_CONFIG:
/* Already connecting */
goto wait;
case BT_CONNECTED:
/* Already connected */
goto done;
case BT_OPEN:
case BT_BOUND:
/* Can connect */
break;
default:
err = -EBADFD;
goto done;
}
/* Set destination address and psm */
bacpy(&bt_sk(sk)->dst, &la.l2_bdaddr);
l2cap_pi(sk)->psm = la.l2_psm;
err = l2cap_do_connect(sk);
if (err)
goto done;
wait:
err = bt_sock_wait_state(sk, BT_CONNECTED,
sock_sndtimeo(sk, flags & O_NONBLOCK));
done:
release_sock(sk);
return err;
}
| 167,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size,
const struct utee_attribute *usr_params,
unsigned long param_count)
{
TEE_Result res;
struct tee_ta_session *sess;
const struct tee_cryp_obj_type_props *type_props;
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
size_t byte_size;
TEE_Attribute *params = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_STATE;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_STATE;
/* Find description of object */
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_SUPPORTED;
/* Check that maxKeySize follows restrictions */
if (key_size % type_props->quanta != 0)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size < type_props->min_size)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size > type_props->max_size)
return TEE_ERROR_NOT_SUPPORTED;
params = malloc(sizeof(TEE_Attribute) * param_count);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count,
params);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
switch (o->info.objectType) {
case TEE_TYPE_AES:
case TEE_TYPE_DES:
case TEE_TYPE_DES3:
case TEE_TYPE_HMAC_MD5:
case TEE_TYPE_HMAC_SHA1:
case TEE_TYPE_HMAC_SHA224:
case TEE_TYPE_HMAC_SHA256:
case TEE_TYPE_HMAC_SHA384:
case TEE_TYPE_HMAC_SHA512:
case TEE_TYPE_GENERIC_SECRET:
byte_size = key_size / 8;
/*
* We have to do it like this because the parity bits aren't
* counted when telling the size of the key in bits.
*/
if (o->info.objectType == TEE_TYPE_DES ||
o->info.objectType == TEE_TYPE_DES3) {
byte_size = (key_size + key_size / 7) / 8;
}
key = (struct tee_cryp_obj_secret *)o->attr;
if (byte_size > key->alloc_size) {
res = TEE_ERROR_EXCESS_DATA;
goto out;
}
res = crypto_rng_read((void *)(key + 1), byte_size);
if (res != TEE_SUCCESS)
goto out;
key->key_size = byte_size;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
break;
case TEE_TYPE_RSA_KEYPAIR:
res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DSA_KEYPAIR:
res = tee_svc_obj_generate_key_dsa(o, type_props, key_size);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DH_KEYPAIR:
res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_ECDSA_KEYPAIR:
case TEE_TYPE_ECDH_KEYPAIR:
res = tee_svc_obj_generate_key_ecc(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
default:
res = TEE_ERROR_BAD_FORMAT;
}
out:
free(params);
if (res == TEE_SUCCESS) {
o->info.keySize = key_size;
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
}
return res;
}
Commit Message: svc: check for allocation overflow in crypto calls
Without checking for overflow there is a risk of allocating a buffer
with size smaller than anticipated and as a consequence of that it might
lead to a heap based overflow with attacker controlled data written
outside the boundaries of the buffer.
Fixes: OP-TEE-2018-0010: "Integer overflow in crypto system calls (x2)"
Signed-off-by: Joakim Bech <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Reviewed-by: Jens Wiklander <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-119 | TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size,
const struct utee_attribute *usr_params,
unsigned long param_count)
{
TEE_Result res;
struct tee_ta_session *sess;
const struct tee_cryp_obj_type_props *type_props;
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
size_t byte_size;
TEE_Attribute *params = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_STATE;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_STATE;
/* Find description of object */
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_SUPPORTED;
/* Check that maxKeySize follows restrictions */
if (key_size % type_props->quanta != 0)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size < type_props->min_size)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size > type_props->max_size)
return TEE_ERROR_NOT_SUPPORTED;
size_t alloc_size = 0;
if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size))
return TEE_ERROR_OVERFLOW;
params = malloc(alloc_size);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count,
params);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
switch (o->info.objectType) {
case TEE_TYPE_AES:
case TEE_TYPE_DES:
case TEE_TYPE_DES3:
case TEE_TYPE_HMAC_MD5:
case TEE_TYPE_HMAC_SHA1:
case TEE_TYPE_HMAC_SHA224:
case TEE_TYPE_HMAC_SHA256:
case TEE_TYPE_HMAC_SHA384:
case TEE_TYPE_HMAC_SHA512:
case TEE_TYPE_GENERIC_SECRET:
byte_size = key_size / 8;
/*
* We have to do it like this because the parity bits aren't
* counted when telling the size of the key in bits.
*/
if (o->info.objectType == TEE_TYPE_DES ||
o->info.objectType == TEE_TYPE_DES3) {
byte_size = (key_size + key_size / 7) / 8;
}
key = (struct tee_cryp_obj_secret *)o->attr;
if (byte_size > key->alloc_size) {
res = TEE_ERROR_EXCESS_DATA;
goto out;
}
res = crypto_rng_read((void *)(key + 1), byte_size);
if (res != TEE_SUCCESS)
goto out;
key->key_size = byte_size;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
break;
case TEE_TYPE_RSA_KEYPAIR:
res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DSA_KEYPAIR:
res = tee_svc_obj_generate_key_dsa(o, type_props, key_size);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DH_KEYPAIR:
res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_ECDSA_KEYPAIR:
case TEE_TYPE_ECDH_KEYPAIR:
res = tee_svc_obj_generate_key_ecc(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
default:
res = TEE_ERROR_BAD_FORMAT;
}
out:
free(params);
if (res == TEE_SUCCESS) {
o->info.keySize = key_size;
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
}
return res;
}
| 169,468 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nfs4_open_confirm_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (!data->rpc_done)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(&data->path, state, data->o_arg.open_flags);
out_free:
nfs4_opendata_put(data);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs4_open_confirm_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (!data->rpc_done)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(&data->path, state, data->o_arg.fmode);
out_free:
nfs4_opendata_put(data);
}
| 165,694 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs4_open_revalidate(struct inode *dir, struct dentry *dentry, int openflags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct rpc_cred *cred;
struct nfs4_state *state;
cred = rpc_lookup_cred();
if (IS_ERR(cred))
return PTR_ERR(cred);
state = nfs4_do_open(dir, &path, openflags, NULL, cred);
put_rpccred(cred);
if (IS_ERR(state)) {
switch (PTR_ERR(state)) {
case -EPERM:
case -EACCES:
case -EDQUOT:
case -ENOSPC:
case -EROFS:
lookup_instantiate_filp(nd, (struct dentry *)state, NULL);
return 1;
default:
goto out_drop;
}
}
if (state->inode == dentry->d_inode) {
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
nfs4_intent_set_file(nd, &path, state);
return 1;
}
nfs4_close_sync(&path, state, openflags);
out_drop:
d_drop(dentry);
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | nfs4_open_revalidate(struct inode *dir, struct dentry *dentry, int openflags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct rpc_cred *cred;
struct nfs4_state *state;
fmode_t fmode = openflags & (FMODE_READ | FMODE_WRITE);
cred = rpc_lookup_cred();
if (IS_ERR(cred))
return PTR_ERR(cred);
state = nfs4_do_open(dir, &path, fmode, openflags, NULL, cred);
put_rpccred(cred);
if (IS_ERR(state)) {
switch (PTR_ERR(state)) {
case -EPERM:
case -EACCES:
case -EDQUOT:
case -ENOSPC:
case -EROFS:
lookup_instantiate_filp(nd, (struct dentry *)state, NULL);
return 1;
default:
goto out_drop;
}
}
if (state->inode == dentry->d_inode) {
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
nfs4_intent_set_file(nd, &path, state, fmode);
return 1;
}
nfs4_close_sync(&path, state, fmode);
out_drop:
d_drop(dentry);
return 0;
}
| 165,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
*p == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
Commit Message: Follow on from CVE-2014-3571. This fixes the code that was the original source
of the crash due to p being NULL. Steve's fix prevents this situation from
occuring - however this is by no means obvious by looking at the code for
dtls1_get_record. This fix just makes things look a bit more sane.
Reviewed-by: Dr Stephen Henson <[email protected]>
CWE ID: | int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
s->packet_length > DTLS1_RT_HEADER_LENGTH &&
s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
| 166,827 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void big_key_describe(const struct key *key, struct seq_file *m)
{
size_t datalen = (size_t)key->payload.data[big_key_len];
seq_puts(m, key->description);
if (key_is_instantiated(key))
seq_printf(m, ": %zu [%s]",
datalen,
datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff");
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20 | void big_key_describe(const struct key *key, struct seq_file *m)
{
size_t datalen = (size_t)key->payload.data[big_key_len];
seq_puts(m, key->description);
if (key_is_positive(key))
seq_printf(m, ": %zu [%s]",
datalen,
datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff");
}
| 167,692 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int AudioRendererAlgorithm::FillBuffer(
uint8* dest, int requested_frames) {
DCHECK_NE(bytes_per_frame_, 0);
if (playback_rate_ == 0.0f)
return 0;
int total_frames_rendered = 0;
uint8* output_ptr = dest;
while (total_frames_rendered < requested_frames) {
if (index_into_window_ == window_size_)
ResetWindow();
bool rendered_frame = true;
if (playback_rate_ > 1.0)
rendered_frame = OutputFasterPlayback(output_ptr);
else if (playback_rate_ < 1.0)
rendered_frame = OutputSlowerPlayback(output_ptr);
else
rendered_frame = OutputNormalPlayback(output_ptr);
if (!rendered_frame) {
needs_more_data_ = true;
break;
}
output_ptr += bytes_per_frame_;
total_frames_rendered++;
}
return total_frames_rendered;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | int AudioRendererAlgorithm::FillBuffer(
uint8* dest, int requested_frames) {
DCHECK_NE(bytes_per_frame_, 0);
if (playback_rate_ == 0.0f)
return 0;
int slower_step = ceil(window_size_ * playback_rate_);
int faster_step = ceil(window_size_ / playback_rate_);
AlignToFrameBoundary(&slower_step);
AlignToFrameBoundary(&faster_step);
int total_frames_rendered = 0;
uint8* output_ptr = dest;
while (total_frames_rendered < requested_frames) {
if (index_into_window_ == window_size_)
ResetWindow();
bool rendered_frame = true;
if (window_size_ > faster_step) {
rendered_frame = OutputFasterPlayback(
output_ptr, window_size_, faster_step);
} else if (slower_step < window_size_) {
rendered_frame = OutputSlowerPlayback(
output_ptr, slower_step, window_size_);
} else {
rendered_frame = OutputNormalPlayback(output_ptr);
}
if (!rendered_frame) {
needs_more_data_ = true;
break;
}
output_ptr += bytes_per_frame_;
total_frames_rendered++;
}
return total_frames_rendered;
}
| 171,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MediaStreamDispatcherHost::DoGenerateStream(
int32_t page_request_id,
const StreamControls& controls,
bool user_gesture,
GenerateStreamCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(MEDIA_DEVICE_INVALID_SECURITY_ORIGIN, std::string(),
MediaStreamDevices(), MediaStreamDevices());
return;
}
media_stream_manager_->GenerateStream(
render_process_id_, render_frame_id_, page_request_id, controls,
std::move(salt_and_origin), user_gesture, std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceChanged,
weak_factory_.GetWeakPtr()));
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void MediaStreamDispatcherHost::DoGenerateStream(
int32_t page_request_id,
const StreamControls& controls,
bool user_gesture,
GenerateStreamCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(MEDIA_DEVICE_INVALID_SECURITY_ORIGIN, std::string(),
MediaStreamDevices(), MediaStreamDevices());
return;
}
media_stream_manager_->GenerateStream(
render_process_id_, render_frame_id_, requester_id_, page_request_id,
controls, std::move(salt_and_origin), user_gesture, std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceChanged,
weak_factory_.GetWeakPtr()));
}
| 173,094 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int amd_gpio_remove(struct platform_device *pdev)
{
struct amd_gpio *gpio_dev;
gpio_dev = platform_get_drvdata(pdev);
gpiochip_remove(&gpio_dev->gc);
pinctrl_unregister(gpio_dev->pctrl);
return 0;
}
Commit Message: pinctrl/amd: Drop pinctrl_unregister for devm_ registered device
It's not necessary to unregister pin controller device registered
with devm_pinctrl_register() and using pinctrl_unregister() leads
to a double free.
Fixes: 3bfd44306c65 ("pinctrl: amd: Add support for additional GPIO")
Signed-off-by: Wei Yongjun <[email protected]>
Signed-off-by: Linus Walleij <[email protected]>
CWE ID: CWE-415 | static int amd_gpio_remove(struct platform_device *pdev)
{
struct amd_gpio *gpio_dev;
gpio_dev = platform_get_drvdata(pdev);
gpiochip_remove(&gpio_dev->gc);
return 0;
}
| 169,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tt_cmap12_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_groups;
if ( table + 16 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 4;
length = TT_NEXT_ULONG( p );
p = table + 12;
p = table + 12;
num_groups = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 16 + 12 * num_groups )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
for ( n = 0; n < num_groups; n++ )
{
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
last = end;
}
}
Commit Message:
CWE ID: CWE-189 | tt_cmap12_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_groups;
if ( table + 16 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 4;
length = TT_NEXT_ULONG( p );
p = table + 12;
p = table + 12;
num_groups = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
length < 16 + 12 * num_groups )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
for ( n = 0; n < num_groups; n++ )
{
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
last = end;
}
}
| 164,740 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static av_cold int vqa_decode_init(AVCodecContext *avctx)
{
VqaContext *s = avctx->priv_data;
int i, j, codebook_index;
s->avctx = avctx;
avctx->pix_fmt = PIX_FMT_PAL8;
/* make sure the extradata made it */
if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
av_log(s->avctx, AV_LOG_ERROR, " VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE);
return -1;
}
/* load up the VQA parameters from the header */
s->vqa_version = s->avctx->extradata[0];
s->width = AV_RL16(&s->avctx->extradata[6]);
s->height = AV_RL16(&s->avctx->extradata[8]);
if(av_image_check_size(s->width, s->height, 0, avctx)){
s->width= s->height= 0;
return -1;
}
s->vector_width = s->avctx->extradata[10];
s->vector_height = s->avctx->extradata[11];
s->partial_count = s->partial_countdown = s->avctx->extradata[13];
/* the vector dimensions have to meet very stringent requirements */
if ((s->vector_width != 4) ||
((s->vector_height != 2) && (s->vector_height != 4))) {
/* return without further initialization */
return -1;
}
/* allocate codebooks */
s->codebook_size = MAX_CODEBOOK_SIZE;
s->codebook = av_malloc(s->codebook_size);
/* allocate decode buffer */
s->decode_buffer_size = (s->width / s->vector_width) *
(s->height / s->vector_height) * 2;
s->decode_buffer = av_malloc(s->decode_buffer_size);
if (!s->decode_buffer)
goto fail;
/* initialize the solid-color vectors */
if (s->vector_height == 4) {
codebook_index = 0xFF00 * 16;
for (i = 0; i < 256; i++)
for (j = 0; j < 16; j++)
s->codebook[codebook_index++] = i;
} else {
codebook_index = 0xF00 * 8;
for (i = 0; i < 256; i++)
for (j = 0; j < 8; j++)
s->codebook[codebook_index++] = i;
}
s->next_codebook_buffer_index = 0;
s->frame.data[0] = NULL;
return 0;
fail:
av_freep(&s->codebook);
av_freep(&s->next_codebook_buffer);
av_freep(&s->decode_buffer);
return AVERROR(ENOMEM);
}
Commit Message:
CWE ID: CWE-119 | static av_cold int vqa_decode_init(AVCodecContext *avctx)
{
VqaContext *s = avctx->priv_data;
int i, j, codebook_index;
s->avctx = avctx;
avctx->pix_fmt = PIX_FMT_PAL8;
/* make sure the extradata made it */
if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
av_log(s->avctx, AV_LOG_ERROR, " VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE);
return -1;
}
/* load up the VQA parameters from the header */
s->vqa_version = s->avctx->extradata[0];
s->width = AV_RL16(&s->avctx->extradata[6]);
s->height = AV_RL16(&s->avctx->extradata[8]);
if(av_image_check_size(s->width, s->height, 0, avctx)){
s->width= s->height= 0;
return -1;
}
s->vector_width = s->avctx->extradata[10];
s->vector_height = s->avctx->extradata[11];
s->partial_count = s->partial_countdown = s->avctx->extradata[13];
/* the vector dimensions have to meet very stringent requirements */
if ((s->vector_width != 4) ||
((s->vector_height != 2) && (s->vector_height != 4))) {
/* return without further initialization */
return -1;
}
if (s->width & (s->vector_width - 1) ||
s->height & (s->vector_height - 1)) {
av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n");
return AVERROR_INVALIDDATA;
}
/* allocate codebooks */
s->codebook_size = MAX_CODEBOOK_SIZE;
s->codebook = av_malloc(s->codebook_size);
/* allocate decode buffer */
s->decode_buffer_size = (s->width / s->vector_width) *
(s->height / s->vector_height) * 2;
s->decode_buffer = av_malloc(s->decode_buffer_size);
if (!s->decode_buffer)
goto fail;
/* initialize the solid-color vectors */
if (s->vector_height == 4) {
codebook_index = 0xFF00 * 16;
for (i = 0; i < 256; i++)
for (j = 0; j < 16; j++)
s->codebook[codebook_index++] = i;
} else {
codebook_index = 0xF00 * 8;
for (i = 0; i < 256; i++)
for (j = 0; j < 8; j++)
s->codebook[codebook_index++] = i;
}
s->next_codebook_buffer_index = 0;
s->frame.data[0] = NULL;
return 0;
fail:
av_freep(&s->codebook);
av_freep(&s->next_codebook_buffer);
av_freep(&s->decode_buffer);
return AVERROR(ENOMEM);
}
| 165,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_find_changing_element(const byte *line, int x, int w)
{
int a, b;
if (line == 0)
return w;
if (x == -1) {
a = 0;
x = 0;
} else {
}
while (x < w) {
b = getbit(line, x);
if (a != b)
break;
x++;
}
return x;
}
Commit Message:
CWE ID: CWE-119 | jbig2_find_changing_element(const byte *line, int x, int w)
jbig2_find_changing_element(const byte *line, uint32_t x, uint32_t w)
{
int a, b;
if (line == 0)
return (int)w;
if (x == MINUS1) {
a = 0;
x = 0;
} else {
}
while (x < w) {
b = getbit(line, x);
if (a != b)
break;
x++;
}
return x;
}
| 165,494 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int test(char *URL)
{
int errors = 0;
(void)URL; /* not used */
errors += test_weird_arguments();
errors += test_unsigned_short_formatting();
errors += test_signed_short_formatting();
errors += test_unsigned_int_formatting();
errors += test_signed_int_formatting();
errors += test_unsigned_long_formatting();
errors += test_signed_long_formatting();
errors += test_curl_off_t_formatting();
errors += test_string_formatting();
if(errors)
return TEST_ERR_MAJOR_BAD;
else
return 0;
}
Commit Message: printf: fix floating point buffer overflow issues
... and add a bunch of floating point printf tests
CWE ID: CWE-119 | int test(char *URL)
{
int errors = 0;
(void)URL; /* not used */
errors += test_weird_arguments();
errors += test_unsigned_short_formatting();
errors += test_signed_short_formatting();
errors += test_unsigned_int_formatting();
errors += test_signed_int_formatting();
errors += test_unsigned_long_formatting();
errors += test_signed_long_formatting();
errors += test_curl_off_t_formatting();
errors += test_string_formatting();
errors += test_float_formatting();
if(errors)
return TEST_ERR_MAJOR_BAD;
else
return 0;
}
| 169,438 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InitPrefMembers() {
settings_->InitPrefMembers();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | void InitPrefMembers() {
| 172,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_immediate_generic_region(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *segment_data)
{
Jbig2RegionSegmentInfo rsi;
byte seg_flags;
int8_t gbat[8];
int offset;
int gbat_bytes = 0;
Jbig2GenericRegionParams params;
int code = 0;
Jbig2Image *image = NULL;
Jbig2WordStream *ws = NULL;
Jbig2ArithState *as = NULL;
Jbig2ArithCx *GB_stats = NULL;
/* 7.4.6 */
if (segment->data_length < 18)
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short");
jbig2_get_region_segment_info(&rsi, segment_data);
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "generic region: %d x %d @ (%d, %d), flags = %02x", rsi.width, rsi.height, rsi.x, rsi.y, rsi.flags);
/* 7.4.6.2 */
seg_flags = segment_data[17];
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "segment flags = %02x", seg_flags);
if ((seg_flags & 1) && (seg_flags & 6))
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "MMR is 1, but GBTEMPLATE is not 0");
/* 7.4.6.3 */
if (!(seg_flags & 1)) {
gbat_bytes = (seg_flags & 6) ? 2 : 8;
if (18 + gbat_bytes > segment->data_length)
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short");
memcpy(gbat, segment_data + 18, gbat_bytes);
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "gbat: %d, %d", gbat[0], gbat[1]);
}
offset = 18 + gbat_bytes;
/* Table 34 */
params.MMR = seg_flags & 1;
params.GBTEMPLATE = (seg_flags & 6) >> 1;
params.TPGDON = (seg_flags & 8) >> 3;
params.USESKIP = 0;
memcpy(params.gbat, gbat, gbat_bytes);
image = jbig2_image_new(ctx, rsi.width, rsi.height);
if (image == NULL)
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate generic image");
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "allocated %d x %d image buffer for region decode results", rsi.width, rsi.height);
if (params.MMR) {
code = jbig2_decode_generic_mmr(ctx, segment, ¶ms, segment_data + offset, segment->data_length - offset, image);
} else {
int stats_size = jbig2_generic_stats_size(ctx, params.GBTEMPLATE);
GB_stats = jbig2_new(ctx, Jbig2ArithCx, stats_size);
if (GB_stats == NULL) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate GB_stats in jbig2_immediate_generic_region");
goto cleanup;
}
memset(GB_stats, 0, stats_size);
ws = jbig2_word_stream_buf_new(ctx, segment_data + offset, segment->data_length - offset);
if (ws == NULL) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate ws in jbig2_immediate_generic_region");
goto cleanup;
}
as = jbig2_arith_new(ctx, ws);
if (as == NULL) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate as in jbig2_immediate_generic_region");
goto cleanup;
}
code = jbig2_decode_generic_region(ctx, segment, ¶ms, as, image, GB_stats);
}
if (code >= 0)
jbig2_page_add_result(ctx, &ctx->pages[ctx->current_page], image, rsi.x, rsi.y, rsi.op);
else
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error while decoding immediate_generic_region");
cleanup:
jbig2_free(ctx->allocator, as);
jbig2_word_stream_buf_free(ctx, ws);
jbig2_free(ctx->allocator, GB_stats);
jbig2_image_release(ctx, image);
return code;
}
Commit Message:
CWE ID: CWE-119 | jbig2_immediate_generic_region(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *segment_data)
{
Jbig2RegionSegmentInfo rsi;
byte seg_flags;
int8_t gbat[8];
int offset;
uint32_t gbat_bytes = 0;
Jbig2GenericRegionParams params;
int code = 0;
Jbig2Image *image = NULL;
Jbig2WordStream *ws = NULL;
Jbig2ArithState *as = NULL;
Jbig2ArithCx *GB_stats = NULL;
/* 7.4.6 */
if (segment->data_length < 18)
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short");
jbig2_get_region_segment_info(&rsi, segment_data);
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "generic region: %d x %d @ (%d, %d), flags = %02x", rsi.width, rsi.height, rsi.x, rsi.y, rsi.flags);
/* 7.4.6.2 */
seg_flags = segment_data[17];
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "segment flags = %02x", seg_flags);
if ((seg_flags & 1) && (seg_flags & 6))
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "MMR is 1, but GBTEMPLATE is not 0");
/* 7.4.6.3 */
if (!(seg_flags & 1)) {
gbat_bytes = (seg_flags & 6) ? 2 : 8;
if (18 + gbat_bytes > segment->data_length)
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short");
memcpy(gbat, segment_data + 18, gbat_bytes);
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "gbat: %d, %d", gbat[0], gbat[1]);
}
offset = 18 + gbat_bytes;
/* Table 34 */
params.MMR = seg_flags & 1;
params.GBTEMPLATE = (seg_flags & 6) >> 1;
params.TPGDON = (seg_flags & 8) >> 3;
params.USESKIP = 0;
memcpy(params.gbat, gbat, gbat_bytes);
image = jbig2_image_new(ctx, rsi.width, rsi.height);
if (image == NULL)
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate generic image");
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "allocated %d x %d image buffer for region decode results", rsi.width, rsi.height);
if (params.MMR) {
code = jbig2_decode_generic_mmr(ctx, segment, ¶ms, segment_data + offset, segment->data_length - offset, image);
} else {
int stats_size = jbig2_generic_stats_size(ctx, params.GBTEMPLATE);
GB_stats = jbig2_new(ctx, Jbig2ArithCx, stats_size);
if (GB_stats == NULL) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate GB_stats in jbig2_immediate_generic_region");
goto cleanup;
}
memset(GB_stats, 0, stats_size);
ws = jbig2_word_stream_buf_new(ctx, segment_data + offset, segment->data_length - offset);
if (ws == NULL) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate ws in jbig2_immediate_generic_region");
goto cleanup;
}
as = jbig2_arith_new(ctx, ws);
if (as == NULL) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate as in jbig2_immediate_generic_region");
goto cleanup;
}
code = jbig2_decode_generic_region(ctx, segment, ¶ms, as, image, GB_stats);
}
if (code >= 0)
jbig2_page_add_result(ctx, &ctx->pages[ctx->current_page], image, rsi.x, rsi.y, rsi.op);
else
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error while decoding immediate_generic_region");
cleanup:
jbig2_free(ctx->allocator, as);
jbig2_word_stream_buf_free(ctx, ws);
jbig2_free(ctx->allocator, GB_stats);
jbig2_image_release(ctx, image);
return code;
}
| 165,486 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_async_increment (IncrementData *data)
{
gint32 newx = data->x + 1;
dbus_g_method_return (data->context, newx);
g_free (data);
return FALSE;
}
Commit Message:
CWE ID: CWE-264 | do_async_increment (IncrementData *data)
| 165,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Textfield::OnFocus() {
GetRenderText()->set_focused(true);
if (ShouldShowCursor()) {
UpdateCursorViewPosition();
cursor_view_.SetVisible(true);
}
if (GetInputMethod())
GetInputMethod()->SetFocusedTextInputClient(this);
OnCaretBoundsChanged();
if (ShouldBlinkCursor())
StartBlinkingCursor();
if (use_focus_ring_) {
FocusRing::Install(this, invalid_
? ui::NativeTheme::kColorId_AlertSeverityHigh
: ui::NativeTheme::kColorId_NumColors);
}
SchedulePaint();
View::OnFocus();
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID: | void Textfield::OnFocus() {
#if defined(OS_MACOSX)
if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD)
password_input_enabler_.reset(new ui::ScopedPasswordInputEnabler());
#endif // defined(OS_MACOSX)
GetRenderText()->set_focused(true);
if (ShouldShowCursor()) {
UpdateCursorViewPosition();
cursor_view_.SetVisible(true);
}
if (GetInputMethod())
GetInputMethod()->SetFocusedTextInputClient(this);
OnCaretBoundsChanged();
if (ShouldBlinkCursor())
StartBlinkingCursor();
if (use_focus_ring_) {
FocusRing::Install(this, invalid_
? ui::NativeTheme::kColorId_AlertSeverityHigh
: ui::NativeTheme::kColorId_NumColors);
}
SchedulePaint();
View::OnFocus();
}
| 171,861 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int userns_install(struct nsproxy *nsproxy, void *ns)
{
struct user_namespace *user_ns = ns;
struct cred *cred;
/* Don't allow gaining capabilities by reentering
* the same user namespace.
*/
if (user_ns == current_user_ns())
return -EINVAL;
/* Threaded processes may not enter a different user namespace */
if (atomic_read(¤t->mm->mm_users) > 1)
return -EINVAL;
if (!ns_capable(user_ns, CAP_SYS_ADMIN))
return -EPERM;
cred = prepare_creds();
if (!cred)
return -ENOMEM;
put_user_ns(cred->user_ns);
set_cred_user_ns(cred, get_user_ns(user_ns));
return commit_creds(cred);
}
Commit Message: userns: Don't allow CLONE_NEWUSER | CLONE_FS
Don't allowing sharing the root directory with processes in a
different user namespace. There doesn't seem to be any point, and to
allow it would require the overhead of putting a user namespace
reference in fs_struct (for permission checks) and incrementing that
reference count on practically every call to fork.
So just perform the inexpensive test of forbidding sharing fs_struct
acrosss processes in different user namespaces. We already disallow
other forms of threading when unsharing a user namespace so this
should be no real burden in practice.
This updates setns, clone, and unshare to disallow multiple user
namespaces sharing an fs_struct.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static int userns_install(struct nsproxy *nsproxy, void *ns)
{
struct user_namespace *user_ns = ns;
struct cred *cred;
/* Don't allow gaining capabilities by reentering
* the same user namespace.
*/
if (user_ns == current_user_ns())
return -EINVAL;
/* Threaded processes may not enter a different user namespace */
if (atomic_read(¤t->mm->mm_users) > 1)
return -EINVAL;
if (current->fs->users != 1)
return -EINVAL;
if (!ns_capable(user_ns, CAP_SYS_ADMIN))
return -EPERM;
cred = prepare_creds();
if (!cred)
return -ENOMEM;
put_user_ns(cred->user_ns);
set_cred_user_ns(cred, get_user_ns(user_ns));
return commit_creds(cred);
}
| 166,108 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Verify_StoreExistingGroupExistingCache(base::Time expected_update_time) {
EXPECT_TRUE(delegate()->stored_group_success_);
EXPECT_EQ(cache_.get(), group_->newest_complete_cache());
AppCacheDatabase::CacheRecord cache_record;
EXPECT_TRUE(database()->FindCache(1, &cache_record));
EXPECT_EQ(1, cache_record.cache_id);
EXPECT_EQ(1, cache_record.group_id);
EXPECT_FALSE(cache_record.online_wildcard);
EXPECT_TRUE(expected_update_time == cache_record.update_time);
EXPECT_EQ(100 + kDefaultEntrySize, cache_record.cache_size);
std::vector<AppCacheDatabase::EntryRecord> entry_records;
EXPECT_TRUE(database()->FindEntriesForCache(1, &entry_records));
EXPECT_EQ(2U, entry_records.size());
if (entry_records[0].url == kDefaultEntryUrl)
entry_records.erase(entry_records.begin());
EXPECT_EQ(1, entry_records[0].cache_id);
EXPECT_EQ(kEntryUrl, entry_records[0].url);
EXPECT_EQ(AppCacheEntry::MASTER, entry_records[0].flags);
EXPECT_EQ(1, entry_records[0].response_id);
EXPECT_EQ(100, entry_records[0].response_size);
EXPECT_EQ(100 + kDefaultEntrySize, storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
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 Verify_StoreExistingGroupExistingCache(base::Time expected_update_time) {
EXPECT_TRUE(delegate()->stored_group_success_);
EXPECT_EQ(cache_.get(), group_->newest_complete_cache());
AppCacheDatabase::CacheRecord cache_record;
EXPECT_TRUE(database()->FindCache(1, &cache_record));
EXPECT_EQ(1, cache_record.cache_id);
EXPECT_EQ(1, cache_record.group_id);
EXPECT_FALSE(cache_record.online_wildcard);
EXPECT_TRUE(expected_update_time == cache_record.update_time);
EXPECT_EQ(100 + kDefaultEntrySize, cache_record.cache_size);
EXPECT_EQ(10 + kDefaultEntryPadding, cache_record.padding_size);
std::vector<AppCacheDatabase::EntryRecord> entry_records;
EXPECT_TRUE(database()->FindEntriesForCache(1, &entry_records));
EXPECT_EQ(2U, entry_records.size());
if (entry_records[0].url == kDefaultEntryUrl)
entry_records.erase(entry_records.begin());
EXPECT_EQ(1, entry_records[0].cache_id);
EXPECT_EQ(kEntryUrl, entry_records[0].url);
EXPECT_EQ(AppCacheEntry::EXPLICIT, entry_records[0].flags);
EXPECT_EQ(1, entry_records[0].response_id);
EXPECT_EQ(100, entry_records[0].response_size);
EXPECT_EQ(10, entry_records[0].padding_size);
EXPECT_EQ(100 + 10 + kDefaultEntrySize + kDefaultEntryPadding,
storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100 + 10, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
| 172,994 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(unserialize)
{
char *buf = NULL;
size_t buf_len;
const unsigned char *p;
php_unserialize_data_t var_hash;
zval *options = NULL, *classes = NULL;
HashTable *class_hash = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) {
RETURN_FALSE;
}
if (buf_len == 0) {
RETURN_FALSE;
}
p = (const unsigned char*) buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if(options != NULL) {
classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1);
if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {
ALLOC_HASHTABLE(class_hash);
zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);
}
if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {
zval *entry;
zend_string *lcname;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {
convert_to_string_ex(entry);
lcname = zend_string_tolower(Z_STR_P(entry));
zend_hash_add_empty_element(class_hash, lcname);
zend_string_release(lcname);
} ZEND_HASH_FOREACH_END();
}
}
if (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
zval_ptr_dtor(return_value);
if (!EG(exception)) {
php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes",
(zend_long)((char*)p - buf), buf_len);
}
RETURN_FALSE;
}
/* We should keep an reference to return_value to prevent it from being dtor
in case nesting calls to unserialize */
var_push_dtor(&var_hash, return_value);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
}
Commit Message: Complete the fix of bug #70172 for PHP 7
CWE ID: CWE-416 | PHP_FUNCTION(unserialize)
{
char *buf = NULL;
size_t buf_len;
const unsigned char *p;
php_unserialize_data_t var_hash;
zval *options = NULL, *classes = NULL;
zval *retval;
HashTable *class_hash = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) {
RETURN_FALSE;
}
if (buf_len == 0) {
RETURN_FALSE;
}
p = (const unsigned char*) buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if(options != NULL) {
classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1);
if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {
ALLOC_HASHTABLE(class_hash);
zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);
}
if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {
zval *entry;
zend_string *lcname;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {
convert_to_string_ex(entry);
lcname = zend_string_tolower(Z_STR_P(entry));
zend_hash_add_empty_element(class_hash, lcname);
zend_string_release(lcname);
} ZEND_HASH_FOREACH_END();
}
}
retval = var_tmp_var(&var_hash);
if (!php_var_unserialize_ex(retval, &p, p + buf_len, &var_hash, class_hash)) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
if (!EG(exception)) {
php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes",
(zend_long)((char*)p - buf), buf_len);
}
RETURN_FALSE;
}
ZVAL_COPY(return_value, retval);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
}
| 168,666 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
sp<ABuffer> data = bufferMeta->getBuffer(
header, portIndex == kPortIndexInput /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
| 174,142 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);
sock_put(sk);
}
}
Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS
SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled
while packets are collected on the error queue.
So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags
is not enough to safely assume that the skb contains
OPT_STATS data.
Add a bit in sock_exterr_skb to indicate whether the
skb contains opt_stats data.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <[email protected]>
Signed-off-by: Soheil Hassas Yeganeh <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125 | void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
sock_put(sk);
}
}
| 170,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BlockEntry::Kind SimpleBlock::GetKind() const
{
return kBlockSimple;
}
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 | BlockEntry::Kind SimpleBlock::GetKind() const
| 174,332 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool parse_reconnect(struct pool *pool, json_t *val)
{
char *sockaddr_url, *stratum_port, *tmp;
char *url, *port, address[256];
memset(address, 0, 255);
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
else {
char *dot_pool, *dot_reconnect;
dot_pool = strchr(pool->sockaddr_url, '.');
if (!dot_pool) {
applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
pool->sockaddr_url);
return false;
}
dot_reconnect = strchr(url, '.');
if (!dot_reconnect) {
applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
url);
return false;
}
if (strcmp(dot_pool, dot_reconnect)) {
applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
pool->sockaddr_url);
return false;
}
}
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
sprintf(address, "%s:%s", url, port);
if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
return false;
applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
clear_pool_work(pool);
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
tmp = pool->sockaddr_url;
pool->sockaddr_url = sockaddr_url;
pool->stratum_url = pool->sockaddr_url;
free(tmp);
tmp = pool->stratum_port;
pool->stratum_port = stratum_port;
free(tmp);
mutex_unlock(&pool->stratum_lock);
if (!restart_stratum(pool)) {
pool_failed(pool);
return false;
}
return true;
}
Commit Message: Do some random sanity checking for stratum message parsing
CWE ID: CWE-119 | static bool parse_reconnect(struct pool *pool, json_t *val)
{
char *sockaddr_url, *stratum_port, *tmp;
char *url, *port, address[256];
memset(address, 0, 255);
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
else {
char *dot_pool, *dot_reconnect;
dot_pool = strchr(pool->sockaddr_url, '.');
if (!dot_pool) {
applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
pool->sockaddr_url);
return false;
}
dot_reconnect = strchr(url, '.');
if (!dot_reconnect) {
applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
url);
return false;
}
if (strcmp(dot_pool, dot_reconnect)) {
applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
pool->sockaddr_url);
return false;
}
}
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
snprintf(address, 254, "%s:%s", url, port);
if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
return false;
applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
clear_pool_work(pool);
mutex_lock(&pool->stratum_lock);
__suspend_stratum(pool);
tmp = pool->sockaddr_url;
pool->sockaddr_url = sockaddr_url;
pool->stratum_url = pool->sockaddr_url;
free(tmp);
tmp = pool->stratum_port;
pool->stratum_port = stratum_port;
free(tmp);
mutex_unlock(&pool->stratum_lock);
if (!restart_stratum(pool)) {
pool_failed(pool);
return false;
}
return true;
}
| 166,307 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AcceleratedStaticBitmapImage::CheckThread() {
if (detach_thread_at_next_check_) {
thread_checker_.DetachFromThread();
detach_thread_at_next_check_ = false;
}
CHECK(thread_checker_.CalledOnValidThread());
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void AcceleratedStaticBitmapImage::CheckThread() {
| 172,590 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_purgekeys";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL))) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp);
} else {
ret.code = kadm5_purgekeys((void *)handle, arg->princ,
arg->keepkvno);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_purgekeys";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL))) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp);
} else {
ret.code = kadm5_purgekeys((void *)handle, arg->princ,
arg->keepkvno);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline void assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
{
switch (ctxt->op_bytes) {
case 2:
ctxt->_eip = (u16)dst;
break;
case 4:
ctxt->_eip = (u32)dst;
break;
case 8:
ctxt->_eip = dst;
break;
default:
WARN(1, "unsupported eip assignment size\n");
}
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
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 inline void assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
static inline int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst,
int cs_l)
{
switch (ctxt->op_bytes) {
case 2:
ctxt->_eip = (u16)dst;
break;
case 4:
ctxt->_eip = (u32)dst;
break;
case 8:
if ((cs_l && is_noncanonical_address(dst)) ||
(!cs_l && (dst & ~(u32)-1)))
return emulate_gp(ctxt, 0);
ctxt->_eip = dst;
break;
default:
WARN(1, "unsupported eip assignment size\n");
}
return X86EMUL_CONTINUE;
}
static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
{
return assign_eip_far(ctxt, dst, ctxt->mode == X86EMUL_MODE_PROT64);
}
| 169,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int createFromTiffRgba(TIFF * tif, gdImagePtr im)
{
int a;
int x, y;
int alphaBlendingFlag = 0;
int color;
int width = im->sx;
int height = im->sy;
uint32 *buffer;
uint32 rgba;
/* switch off colour merging on target gd image just while we write out
* content - we want to preserve the alpha data until the user chooses
* what to do with the image */
alphaBlendingFlag = im->alphaBlendingFlag;
gdImageAlphaBlending(im, 0);
buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height);
if (!buffer) {
return GD_FAILURE;
}
TIFFReadRGBAImage(tif, width, height, buffer, 0);
for(y = 0; y < height; y++) {
for(x = 0; x < width; x++) {
/* if it doesn't already exist, allocate a new colour,
* else use existing one */
rgba = buffer[(y * width + x)];
a = (0xff - TIFFGetA(rgba)) / 2;
color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a);
/* set pixel colour to this colour */
gdImageSetPixel(im, x, height - y - 1, color);
}
}
gdFree(buffer);
/* now reset colour merge for alpha blending routines */
gdImageAlphaBlending(im, alphaBlendingFlag);
return GD_SUCCESS;
}
Commit Message: Fix invalid read in gdImageCreateFromTiffPtr()
tiff_invalid_read.tiff is corrupt, and causes an invalid read in
gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit
is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case,
dynamicGetbuf() is called with a negative dp->pos, but also positive buffer
overflows have to be handled, in which case 0 has to be returned (cf. commit
75e29a9).
Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create
the image, because the return value of TIFFReadRGBAImage() is not checked.
We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6911
CWE ID: CWE-125 | static int createFromTiffRgba(TIFF * tif, gdImagePtr im)
{
int a;
int x, y;
int alphaBlendingFlag = 0;
int color;
int width = im->sx;
int height = im->sy;
uint32 *buffer;
uint32 rgba;
int success;
/* switch off colour merging on target gd image just while we write out
* content - we want to preserve the alpha data until the user chooses
* what to do with the image */
alphaBlendingFlag = im->alphaBlendingFlag;
gdImageAlphaBlending(im, 0);
buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height);
if (!buffer) {
return GD_FAILURE;
}
success = TIFFReadRGBAImage(tif, width, height, buffer, 1);
if (success) {
for(y = 0; y < height; y++) {
for(x = 0; x < width; x++) {
/* if it doesn't already exist, allocate a new colour,
* else use existing one */
rgba = buffer[(y * width + x)];
a = (0xff - TIFFGetA(rgba)) / 2;
color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a);
/* set pixel colour to this colour */
gdImageSetPixel(im, x, height - y - 1, color);
}
}
}
gdFree(buffer);
/* now reset colour merge for alpha blending routines */
gdImageAlphaBlending(im, alphaBlendingFlag);
return success;
}
| 168,822 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_ctl_elem_user_tlv(struct snd_kcontrol *kcontrol,
int op_flag,
unsigned int size,
unsigned int __user *tlv)
{
struct user_element *ue = kcontrol->private_data;
int change = 0;
void *new_data;
if (op_flag > 0) {
if (size > 1024 * 128) /* sane value */
return -EINVAL;
new_data = memdup_user(tlv, size);
if (IS_ERR(new_data))
return PTR_ERR(new_data);
change = ue->tlv_data_size != size;
if (!change)
change = memcmp(ue->tlv_data, new_data, size);
kfree(ue->tlv_data);
ue->tlv_data = new_data;
ue->tlv_data_size = size;
} else {
if (! ue->tlv_data_size || ! ue->tlv_data)
return -ENXIO;
if (size < ue->tlv_data_size)
return -ENOSPC;
if (copy_to_user(tlv, ue->tlv_data, ue->tlv_data_size))
return -EFAULT;
}
return change;
}
Commit Message: ALSA: control: Protect user controls against concurrent access
The user-control put and get handlers as well as the tlv do not protect against
concurrent access from multiple threads. Since the state of the control is not
updated atomically it is possible that either two write operations or a write
and a read operation race against each other. Both can lead to arbitrary memory
disclosure. This patch introduces a new lock that protects user-controls from
concurrent access. Since applications typically access controls sequentially
than in parallel a single lock per card should be fine.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-362 | static int snd_ctl_elem_user_tlv(struct snd_kcontrol *kcontrol,
int op_flag,
unsigned int size,
unsigned int __user *tlv)
{
struct user_element *ue = kcontrol->private_data;
int change = 0;
void *new_data;
if (op_flag > 0) {
if (size > 1024 * 128) /* sane value */
return -EINVAL;
new_data = memdup_user(tlv, size);
if (IS_ERR(new_data))
return PTR_ERR(new_data);
mutex_lock(&ue->card->user_ctl_lock);
change = ue->tlv_data_size != size;
if (!change)
change = memcmp(ue->tlv_data, new_data, size);
kfree(ue->tlv_data);
ue->tlv_data = new_data;
ue->tlv_data_size = size;
mutex_unlock(&ue->card->user_ctl_lock);
} else {
int ret = 0;
mutex_lock(&ue->card->user_ctl_lock);
if (!ue->tlv_data_size || !ue->tlv_data) {
ret = -ENXIO;
goto err_unlock;
}
if (size < ue->tlv_data_size) {
ret = -ENOSPC;
goto err_unlock;
}
if (copy_to_user(tlv, ue->tlv_data, ue->tlv_data_size))
ret = -EFAULT;
err_unlock:
mutex_unlock(&ue->card->user_ctl_lock);
if (ret)
return ret;
}
return change;
}
| 166,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NetworkHandler::NetworkHandler(const std::string& host_id)
: DevToolsDomainHandler(Network::Metainfo::domainName),
process_(nullptr),
host_(nullptr),
enabled_(false),
host_id_(host_id),
bypass_service_worker_(false),
cache_disabled_(false),
weak_factory_(this) {
static bool have_configured_service_worker_context = false;
if (have_configured_service_worker_context)
return;
have_configured_service_worker_context = true;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&ConfigureServiceWorkerContextOnIO));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | NetworkHandler::NetworkHandler(const std::string& host_id)
: DevToolsDomainHandler(Network::Metainfo::domainName),
browser_context_(nullptr),
storage_partition_(nullptr),
host_(nullptr),
enabled_(false),
host_id_(host_id),
bypass_service_worker_(false),
cache_disabled_(false),
weak_factory_(this) {
static bool have_configured_service_worker_context = false;
if (have_configured_service_worker_context)
return;
have_configured_service_worker_context = true;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&ConfigureServiceWorkerContextOnIO));
}
| 172,759 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sshkey_load_file(int fd, struct sshbuf *blob)
{
u_char buf[1024];
size_t len;
struct stat st;
int r;
if (fstat(fd, &st) < 0)
return SSH_ERR_SYSTEM_ERROR;
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size > MAX_KEY_FILE_SIZE)
return SSH_ERR_INVALID_FORMAT;
for (;;) {
if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
if (errno == EPIPE)
break;
r = SSH_ERR_SYSTEM_ERROR;
goto out;
}
if ((r = sshbuf_put(blob, buf, len)) != 0)
goto out;
if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
}
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size != (off_t)sshbuf_len(blob)) {
r = SSH_ERR_FILE_CHANGED;
goto out;
}
r = 0;
out:
explicit_bzero(buf, sizeof(buf));
if (r != 0)
sshbuf_reset(blob);
return r;
}
Commit Message: use sshbuf_allocate() to pre-allocate the buffer used for loading
keys. This avoids implicit realloc inside the buffer code, which
might theoretically leave fragments of the key on the heap. This
doesn't appear to happen in practice for normal sized keys, but
was observed for novelty oversize ones.
Pointed out by Jann Horn of Project Zero; ok markus@
CWE ID: CWE-320 | sshkey_load_file(int fd, struct sshbuf *blob)
{
u_char buf[1024];
size_t len;
struct stat st;
int r, dontmax = 0;
if (fstat(fd, &st) < 0)
return SSH_ERR_SYSTEM_ERROR;
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size > MAX_KEY_FILE_SIZE)
return SSH_ERR_INVALID_FORMAT;
/*
* Pre-allocate the buffer used for the key contents and clamp its
* maximum size. This ensures that key contents are never leaked via
* implicit realloc() in the sshbuf code.
*/
if ((st.st_mode & S_IFREG) == 0 || st.st_size <= 0) {
st.st_size = 64*1024; /* 64k should be enough for anyone :) */
dontmax = 1;
}
if ((r = sshbuf_allocate(blob, st.st_size)) != 0 ||
(dontmax && (r = sshbuf_set_max_size(blob, st.st_size)) != 0))
return r;
for (;;) {
if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
if (errno == EPIPE)
break;
r = SSH_ERR_SYSTEM_ERROR;
goto out;
}
if ((r = sshbuf_put(blob, buf, len)) != 0)
goto out;
if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
}
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size != (off_t)sshbuf_len(blob)) {
r = SSH_ERR_FILE_CHANGED;
goto out;
}
r = 0;
out:
explicit_bzero(buf, sizeof(buf));
if (r != 0)
sshbuf_reset(blob);
return r;
}
| 168,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int append_camera_metadata(camera_metadata_t *dst,
const camera_metadata_t *src) {
if (dst == NULL || src == NULL ) return ERROR;
if (dst->entry_capacity < src->entry_count + dst->entry_count) return ERROR;
if (dst->data_capacity < src->data_count + dst->data_count) return ERROR;
memcpy(get_entries(dst) + dst->entry_count, get_entries(src),
sizeof(camera_metadata_buffer_entry_t[src->entry_count]));
memcpy(get_data(dst) + dst->data_count, get_data(src),
sizeof(uint8_t[src->data_count]));
if (dst->data_count != 0) {
camera_metadata_buffer_entry_t *entry = get_entries(dst) + dst->entry_count;
for (size_t i = 0; i < src->entry_count; i++, entry++) {
if ( calculate_camera_metadata_entry_data_size(entry->type,
entry->count) > 0 ) {
entry->data.offset += dst->data_count;
}
}
}
if (dst->entry_count == 0) {
dst->flags |= src->flags & FLAG_SORTED;
} else if (src->entry_count != 0) {
dst->flags &= ~FLAG_SORTED;
} else {
}
dst->entry_count += src->entry_count;
dst->data_count += src->data_count;
assert(validate_camera_metadata_structure(dst, NULL) == OK);
return OK;
}
Commit Message: Camera metadata: Check for inconsistent data count
Resolve merge conflict for nyc-release
Also check for overflow of data/entry count on append.
Bug: 30591838
Change-Id: Ibf4c3c6e236cdb28234f3125055d95ef0a2416a2
CWE ID: CWE-264 | int append_camera_metadata(camera_metadata_t *dst,
const camera_metadata_t *src) {
if (dst == NULL || src == NULL ) return ERROR;
// Check for overflow
if (src->entry_count + dst->entry_count < src->entry_count) return ERROR;
if (src->data_count + dst->data_count < src->data_count) return ERROR;
// Check for space
if (dst->entry_capacity < src->entry_count + dst->entry_count) return ERROR;
if (dst->data_capacity < src->data_count + dst->data_count) return ERROR;
memcpy(get_entries(dst) + dst->entry_count, get_entries(src),
sizeof(camera_metadata_buffer_entry_t[src->entry_count]));
memcpy(get_data(dst) + dst->data_count, get_data(src),
sizeof(uint8_t[src->data_count]));
if (dst->data_count != 0) {
camera_metadata_buffer_entry_t *entry = get_entries(dst) + dst->entry_count;
for (size_t i = 0; i < src->entry_count; i++, entry++) {
if ( calculate_camera_metadata_entry_data_size(entry->type,
entry->count) > 0 ) {
entry->data.offset += dst->data_count;
}
}
}
if (dst->entry_count == 0) {
dst->flags |= src->flags & FLAG_SORTED;
} else if (src->entry_count != 0) {
dst->flags &= ~FLAG_SORTED;
} else {
}
dst->entry_count += src->entry_count;
dst->data_count += src->data_count;
assert(validate_camera_metadata_structure(dst, NULL) == OK);
return OK;
}
| 173,396 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)
{
zval** ele_value = NULL;
if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if(Z_TYPE_PP(ele_value)!= IS_STRING ){
/* element value is not a string */
return FAILURE;
}
if(strcmp(key_name, LOC_LANG_TAG) != 0 &&
strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {
/* not lang or grandfathered tag */
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
}
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
}
return LOC_NOT_FOUND;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)
{
zval** ele_value = NULL;
if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if(Z_TYPE_PP(ele_value)!= IS_STRING ){
/* element value is not a string */
return FAILURE;
}
if(strcmp(key_name, LOC_LANG_TAG) != 0 &&
strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {
/* not lang or grandfathered tag */
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
}
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
}
return LOC_NOT_FOUND;
}
| 167,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TextTrack::addCue(TextTrackCue* cue) {
DCHECK(cue);
if (std::isnan(cue->startTime()) || std::isnan(cue->endTime()) ||
cue->startTime() < 0 || cue->endTime() < 0)
return;
if (TextTrack* cue_track = cue->track())
cue_track->removeCue(cue, ASSERT_NO_EXCEPTION);
cue->SetTrack(this);
EnsureTextTrackCueList()->Add(cue);
if (GetCueTimeline() && mode_ != DisabledKeyword())
GetCueTimeline()->AddCue(this, cue);
}
Commit Message: Support negative timestamps of TextTrackCue
Ensure proper behaviour for negative timestamps of TextTrackCue.
1. Cues with negative startTime should become active from 0s.
2. Cues with negative startTime and endTime should never be active.
Bug: 314032
Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d
Reviewed-on: https://chromium-review.googlesource.com/863270
Commit-Queue: srirama chandra sekhar <[email protected]>
Reviewed-by: Fredrik Söderquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529012}
CWE ID: | void TextTrack::addCue(TextTrackCue* cue) {
DCHECK(cue);
if (std::isnan(cue->startTime()) || std::isnan(cue->endTime()))
return;
if (TextTrack* cue_track = cue->track())
cue_track->removeCue(cue, ASSERT_NO_EXCEPTION);
cue->SetTrack(this);
EnsureTextTrackCueList()->Add(cue);
if (GetCueTimeline() && mode_ != DisabledKeyword())
GetCueTimeline()->AddCue(this, cue);
}
| 171,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ChromeURLRequestContext::ChromeURLRequestContext(
ContextType type,
chrome_browser_net::LoadTimeStats* load_time_stats)
: load_time_stats_(load_time_stats) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (load_time_stats_)
load_time_stats_->RegisterURLRequestContext(this, type);
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | ChromeURLRequestContext::ChromeURLRequestContext(
ContextType type,
chrome_browser_net::LoadTimeStats* load_time_stats)
: weak_factory_(this),
load_time_stats_(load_time_stats) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (load_time_stats_)
load_time_stats_->RegisterURLRequestContext(this, type);
}
| 171,250 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: HostCache::HostCache(size_t max_entries)
: max_entries_(max_entries), network_changes_(0) {}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID: | HostCache::HostCache(size_t max_entries)
| 172,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fe_netjoin_deinit(void)
{
while (joinservers != NULL)
netjoin_server_remove(joinservers->data);
if (join_tag != -1) {
g_source_remove(join_tag);
signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting);
}
signal_remove("setup changed", (SIGNAL_FUNC) read_settings);
signal_remove("message quit", (SIGNAL_FUNC) msg_quit);
signal_remove("message join", (SIGNAL_FUNC) msg_join);
signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode);
}
Commit Message: Merge branch 'netjoin-timeout' into 'master'
fe-netjoin: remove irc servers on "server disconnected" signal
Closes #7
See merge request !10
CWE ID: CWE-416 | void fe_netjoin_deinit(void)
{
while (joinservers != NULL)
netjoin_server_remove(joinservers->data);
if (join_tag != -1) {
g_source_remove(join_tag);
signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting);
}
signal_remove("setup changed", (SIGNAL_FUNC) read_settings);
signal_remove("server disconnected", (SIGNAL_FUNC) sig_server_disconnected);
signal_remove("message quit", (SIGNAL_FUNC) msg_quit);
signal_remove("message join", (SIGNAL_FUNC) msg_join);
signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode);
}
| 168,290 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) {
frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
if (droppable_nframes_ > 0 &&
(cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) {
for (unsigned int i = 0; i < droppable_nframes_; ++i) {
if (droppable_frames_[i] == video->frame()) {
std::cout << " Encoding droppable frame: "
<< droppable_frames_[i] << "\n";
frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
return;
}
}
}
}
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 PreEncodeFrameHook(libvpx_test::VideoSource *video) {
//
// Frame flags and layer id for temporal layers.
// For two layers, test pattern is:
// 1 3
// 0 2 .....
// LAST is updated on base/layer 0, GOLDEN updated on layer 1.
// Non-zero pattern_switch parameter means pattern will switch to
// not using LAST for frame_num >= pattern_switch.
int SetFrameFlags(int frame_num,
int num_temp_layers,
int pattern_switch) {
int frame_flags = 0;
if (num_temp_layers == 2) {
if (frame_num % 2 == 0) {
if (frame_num < pattern_switch || pattern_switch == 0) {
// Layer 0: predict from LAST and ARF, update LAST.
frame_flags = VP8_EFLAG_NO_REF_GF |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF;
} else {
// Layer 0: predict from GF and ARF, update GF.
frame_flags = VP8_EFLAG_NO_REF_LAST |
VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_ARF;
}
} else {
if (frame_num < pattern_switch || pattern_switch == 0) {
// Layer 1: predict from L, GF, and ARF, update GF.
frame_flags = VP8_EFLAG_NO_UPD_ARF |
VP8_EFLAG_NO_UPD_LAST;
} else {
// Layer 1: predict from GF and ARF, update GF.
frame_flags = VP8_EFLAG_NO_REF_LAST |
VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_ARF;
}
}
}
return frame_flags;
}
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
// For temporal layer case.
if (cfg_.ts_number_layers > 1) {
frame_flags_ = SetFrameFlags(video->frame(),
cfg_.ts_number_layers,
pattern_switch_);
for (unsigned int i = 0; i < droppable_nframes_; ++i) {
if (droppable_frames_[i] == video->frame()) {
std::cout << "Encoding droppable frame: "
<< droppable_frames_[i] << "\n";
}
}
} else {
if (droppable_nframes_ > 0 &&
(cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) {
for (unsigned int i = 0; i < droppable_nframes_; ++i) {
if (droppable_frames_[i] == video->frame()) {
std::cout << "Encoding droppable frame: "
<< droppable_frames_[i] << "\n";
frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
return;
}
}
}
}
}
| 174,542 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ZeroSuggestProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
matches_.clear();
if (!input.from_omnibox_focus() || client()->IsOffTheRecord() ||
input.type() == metrics::OmniboxInputType::INVALID)
return;
Stop(true, false);
set_field_trial_triggered(false);
set_field_trial_triggered_in_session(false);
results_from_cache_ = false;
permanent_text_ = input.text();
current_query_ = input.current_url().spec();
current_title_ = input.current_title();
current_page_classification_ = input.current_page_classification();
current_url_match_ = MatchForCurrentURL();
std::string url_string = GetContextualSuggestionsUrl();
GURL suggest_url(url_string);
if (!suggest_url.is_valid())
return;
const TemplateURLService* template_url_service =
client()->GetTemplateURLService();
const TemplateURL* default_provider =
template_url_service->GetDefaultSearchProvider();
const bool can_send_current_url =
CanSendURL(input.current_url(), suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
GURL arbitrary_insecure_url(kArbitraryInsecureUrlString);
ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE;
if (!can_send_current_url) {
const bool can_send_ordinary_url =
CanSendURL(arbitrary_insecure_url, suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
eligibility = can_send_ordinary_url
? ZeroSuggestEligibility::URL_INELIGIBLE
: ZeroSuggestEligibility::GENERALLY_INELIGIBLE;
}
UMA_HISTOGRAM_ENUMERATION(
"Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility),
static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE));
if (can_send_current_url &&
!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() &&
!OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
if (OmniboxFieldTrial::InZeroSuggestRedirectToChromeFieldTrial()) {
url_string +=
"/url=" + net::EscapePath(current_query_) +
OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields();
suggest_url = GURL(url_string);
} else {
base::string16 prefix;
TemplateURLRef::SearchTermsArgs search_term_args(prefix);
search_term_args.current_page_url = current_query_;
suggest_url =
GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms(
search_term_args, template_url_service->search_terms_data()));
}
} else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) {
return;
}
done_ = false;
MaybeUseCachedSuggestions();
Run(suggest_url);
}
Commit Message: Provide experimental contextual suggestions when current URL comes from a google domain.
The counts for the Omnibox.ZeroSuggestRequests historgram are 35% smaller for groups that are running under the ZeroSuggestRedirectToChrome flag. Note that previous to this CL, a request was not made when the user was visiting an HTTPS page and the domain of the current was different from that of the service providing zero suggestions. This CL addresses this restrictions by making sure that requests are sent to the experimental service when Google is the default search engine AND the same request was validated to be sent to Google.
BUG=692471
Review-Url: https://codereview.chromium.org/2915163003
Cr-Commit-Position: refs/heads/master@{#476786}
CWE ID: | void ZeroSuggestProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
matches_.clear();
if (!input.from_omnibox_focus() || client()->IsOffTheRecord() ||
input.type() == metrics::OmniboxInputType::INVALID)
return;
Stop(true, false);
set_field_trial_triggered(false);
set_field_trial_triggered_in_session(false);
results_from_cache_ = false;
permanent_text_ = input.text();
current_query_ = input.current_url().spec();
current_title_ = input.current_title();
current_page_classification_ = input.current_page_classification();
current_url_match_ = MatchForCurrentURL();
GURL suggest_url(GetContextualSuggestionsUrl());
if (!suggest_url.is_valid())
return;
const TemplateURLService* template_url_service =
client()->GetTemplateURLService();
const TemplateURL* default_provider =
template_url_service->GetDefaultSearchProvider();
const bool can_send_current_url =
CanSendURL(input.current_url(), suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
GURL arbitrary_insecure_url(kArbitraryInsecureUrlString);
ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE;
if (!can_send_current_url) {
const bool can_send_ordinary_url =
CanSendURL(arbitrary_insecure_url, suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
eligibility = can_send_ordinary_url
? ZeroSuggestEligibility::URL_INELIGIBLE
: ZeroSuggestEligibility::GENERALLY_INELIGIBLE;
}
UMA_HISTOGRAM_ENUMERATION(
"Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility),
static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE));
if (can_send_current_url &&
!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() &&
!OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
if (UseExperimentalSuggestService(*template_url_service)) {
suggest_url = GURL(
OmniboxFieldTrial::ZeroSuggestRedirectToChromeServerAddress() +
"/url=" + net::EscapePath(current_query_) +
OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields());
} else {
base::string16 prefix;
TemplateURLRef::SearchTermsArgs search_term_args(prefix);
search_term_args.current_page_url = current_query_;
suggest_url =
GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms(
search_term_args, template_url_service->search_terms_data()));
}
} else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) {
return;
}
done_ = false;
MaybeUseCachedSuggestions();
Run(suggest_url);
}
| 172,013 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: double VideoTrack::GetFrameRate() const
{
return m_rate;
}
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 | double VideoTrack::GetFrameRate() const
| 174,326 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute)
{
v8::Local<v8::Context> context = inspectedContext->context();
v8::Context::Scope contextScope(context);
v8::Isolate* isolate = context->GetIsolate();
v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Local<v8::Object> console = v8::Object::New(isolate);
createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback);
createBoundFunctionProperty(context, console, "error", V8Console::errorCallback);
createBoundFunctionProperty(context, console, "info", V8Console::infoCallback);
createBoundFunctionProperty(context, console, "log", V8Console::logCallback);
createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback);
createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback);
createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback);
createBoundFunctionProperty(context, console, "table", V8Console::tableCallback);
createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback);
createBoundFunctionProperty(context, console, "group", V8Console::groupCallback);
createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback);
createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback);
createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback);
createBoundFunctionProperty(context, console, "count", V8Console::countCallback);
createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback);
createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback);
createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback);
createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback);
createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback);
createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback);
createBoundFunctionProperty(context, console, "time", V8Console::timeCallback);
createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback);
createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback);
bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false);
DCHECK(success);
if (hasMemoryAttribute)
console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT);
console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext));
return console;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute)
{
v8::Local<v8::Context> context = inspectedContext->context();
v8::Context::Scope contextScope(context);
v8::Isolate* isolate = context->GetIsolate();
v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Local<v8::Object> console = v8::Object::New(isolate);
bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false);
DCHECK(success);
createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback);
createBoundFunctionProperty(context, console, "error", V8Console::errorCallback);
createBoundFunctionProperty(context, console, "info", V8Console::infoCallback);
createBoundFunctionProperty(context, console, "log", V8Console::logCallback);
createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback);
createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback);
createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback);
createBoundFunctionProperty(context, console, "table", V8Console::tableCallback);
createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback);
createBoundFunctionProperty(context, console, "group", V8Console::groupCallback);
createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback);
createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback);
createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback);
createBoundFunctionProperty(context, console, "count", V8Console::countCallback);
createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback);
createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback);
createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback);
createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback);
createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback);
createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback);
createBoundFunctionProperty(context, console, "time", V8Console::timeCallback);
createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback);
createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback);
if (hasMemoryAttribute)
console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT);
console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext));
return console;
}
| 172,063 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WT_VoiceFilter (S_FILTER_CONTROL *pFilter, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pAudioBuffer;
EAS_I32 k;
EAS_I32 b1;
EAS_I32 b2;
EAS_I32 z1;
EAS_I32 z2;
EAS_I32 acc0;
EAS_I32 acc1;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pAudioBuffer = pWTIntFrame->pAudioBuffer;
z1 = pFilter->z1;
z2 = pFilter->z2;
b1 = -pWTIntFrame->frame.b1;
/*lint -e{702} <avoid divide> */
b2 = -pWTIntFrame->frame.b2 >> 1;
/*lint -e{702} <avoid divide> */
k = pWTIntFrame->frame.k >> 1;
while (numSamples--)
{
/* do filter calculations */
acc0 = *pAudioBuffer;
acc1 = z1 * b1;
acc1 += z2 * b2;
acc0 = acc1 + k * acc0;
z2 = z1;
/*lint -e{702} <avoid divide> */
z1 = acc0 >> 14;
*pAudioBuffer++ = (EAS_I16) z1;
}
/* save delay values */
pFilter->z1 = (EAS_I16) z1;
pFilter->z2 = (EAS_I16) z2;
}
Commit Message: Sonivox: add SafetyNet log.
Bug: 26366256
Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0
CWE ID: CWE-119 | void WT_VoiceFilter (S_FILTER_CONTROL *pFilter, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pAudioBuffer;
EAS_I32 k;
EAS_I32 b1;
EAS_I32 b2;
EAS_I32 z1;
EAS_I32 z2;
EAS_I32 acc0;
EAS_I32 acc1;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
android_errorWriteLog(0x534e4554, "26366256");
return;
}
pAudioBuffer = pWTIntFrame->pAudioBuffer;
z1 = pFilter->z1;
z2 = pFilter->z2;
b1 = -pWTIntFrame->frame.b1;
/*lint -e{702} <avoid divide> */
b2 = -pWTIntFrame->frame.b2 >> 1;
/*lint -e{702} <avoid divide> */
k = pWTIntFrame->frame.k >> 1;
while (numSamples--)
{
/* do filter calculations */
acc0 = *pAudioBuffer;
acc1 = z1 * b1;
acc1 += z2 * b2;
acc0 = acc1 + k * acc0;
z2 = z1;
/*lint -e{702} <avoid divide> */
z1 = acc0 >> 14;
*pAudioBuffer++ = (EAS_I16) z1;
}
/* save delay values */
pFilter->z1 = (EAS_I16) z1;
pFilter->z2 = (EAS_I16) z2;
}
| 174,605 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
chromeos::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
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 | bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
bool FindAndUpdateProperty(
const chromeos::input_method::ImeProperty& new_prop,
chromeos::input_method::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::input_method::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
| 170,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PopupContainer::showPopup(FrameView* view)
{
m_frameView = view;
listBox()->m_focusedNode = m_frameView->frame()->document()->focusedNode();
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
IntRect popupRect = frameRect();
chromeClient->popupOpened(this, layoutAndCalculateWidgetRect(popupRect.height(), popupRect.location()), false);
m_popupOpen = true;
}
if (!m_listBox->parent())
addChild(m_listBox.get());
m_listBox->setVerticalScrollbarMode(ScrollbarAuto);
m_listBox->scrollToRevealSelection();
invalidate();
}
Commit Message: [REGRESSION] Refreshed autofill popup renders garbage
https://bugs.webkit.org/show_bug.cgi?id=83255
http://code.google.com/p/chromium/issues/detail?id=118374
The code used to update only the PopupContainer coordinates as if they were the coordinates relative
to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer,
so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's
location should be (0, 0) (and their sizes should always be equal).
Reviewed by Kent Tamura.
No new tests, as the popup appearance is not testable in WebKit.
* platform/chromium/PopupContainer.cpp:
(WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed.
(WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect()
for passing into chromeClient.
(WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container.
(WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly.
* platform/chromium/PopupContainer.h:
(PopupContainer):
git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void PopupContainer::showPopup(FrameView* view)
{
m_frameView = view;
listBox()->m_focusedNode = m_frameView->frame()->document()->focusedNode();
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
IntRect popupRect = m_originalFrameRect;
chromeClient->popupOpened(this, layoutAndCalculateWidgetRect(popupRect.height(), popupRect.location()), false);
m_popupOpen = true;
}
if (!m_listBox->parent())
addChild(m_listBox.get());
m_listBox->setVerticalScrollbarMode(ScrollbarAuto);
m_listBox->scrollToRevealSelection();
invalidate();
}
| 171,029 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int insert_pin(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char auth_id,
unsigned char pin_reference,
int min_length,
const char *label,
int pin_flags
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
int r;
memset(&pin_info, 0, sizeof(pin_info));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = id;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = pin_reference;
pin_info.attrs.pin.flags = pin_flags;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = min_length;
pin_info.attrs.pin.stored_length = 16;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.logged_in = SC_PIN_STATE_UNKNOWN;
sc_format_path(path, &pin_info.path);
memset(&pin_obj, 0, sizeof(pin_obj));
strlcpy(pin_obj.label, label, sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;
pin_obj.auth_id.len = auth_id ? 0 : 1;
pin_obj.auth_id.value[0] = auth_id;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(pin_info.path.len>=2) pin_info.path.len-=2;
sc_append_file_id(&pin_info.path, 0x5049);
if(sc_select_file(card, &pin_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&pin_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for PIN-Ref %02X\n", pin_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0, fbz=-1;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==pin_reference) ++found;
if(buf[i]==0x90) fbz=buf[i+1+buf[i+1]];
}
if(found) pin_info.tries_left=fbz;
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_PWDD-Record found\n");
return 1;
}
} else {
if(sc_select_file(card, &pin_info.path, &f)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"Select(%s) failed\n", path);
return 1;
}
pin_info.tries_left=f->prop_attr[3];
sc_file_free(f);
}
r=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_pin_obj(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, FBZ=%d\n", path, pin_info.tries_left);
return 0;
}
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 insert_pin(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char auth_id,
unsigned char pin_reference,
int min_length,
const char *label,
int pin_flags
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
int r;
memset(&pin_info, 0, sizeof(pin_info));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = id;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = pin_reference;
pin_info.attrs.pin.flags = pin_flags;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = min_length;
pin_info.attrs.pin.stored_length = 16;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.logged_in = SC_PIN_STATE_UNKNOWN;
sc_format_path(path, &pin_info.path);
memset(&pin_obj, 0, sizeof(pin_obj));
strlcpy(pin_obj.label, label, sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;
pin_obj.auth_id.len = auth_id ? 0 : 1;
pin_obj.auth_id.value[0] = auth_id;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(pin_info.path.len>=2) pin_info.path.len-=2;
sc_append_file_id(&pin_info.path, 0x5049);
if(sc_select_file(card, &pin_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&pin_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for PIN-Ref %02X\n", pin_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0, fbz=-1;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==pin_reference) ++found;
if(buf[i]==0x90) fbz=buf[i+1+buf[i+1]];
}
if(found) pin_info.tries_left=fbz;
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_PWDD-Record found\n");
return 1;
}
} else {
if(sc_select_file(card, &pin_info.path, &f)!=SC_SUCCESS
|| !f->prop_attr || f->prop_attr_len < 4){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"Select(%s) failed\n", path);
return 1;
}
pin_info.tries_left=f->prop_attr[3];
sc_file_free(f);
}
r=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_pin_obj(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, FBZ=%d\n", path, pin_info.tries_left);
return 0;
}
| 169,068 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int common_timer_set(struct k_itimer *timr, int flags,
struct itimerspec64 *new_setting,
struct itimerspec64 *old_setting)
{
const struct k_clock *kc = timr->kclock;
bool sigev_none;
ktime_t expires;
if (old_setting)
common_timer_get(timr, old_setting);
/* Prevent rearming by clearing the interval */
timr->it_interval = 0;
/*
* Careful here. On SMP systems the timer expiry function could be
* active and spinning on timr->it_lock.
*/
if (kc->timer_try_to_cancel(timr) < 0)
return TIMER_RETRY;
timr->it_active = 0;
timr->it_requeue_pending = (timr->it_requeue_pending + 2) &
~REQUEUE_PENDING;
timr->it_overrun_last = 0;
/* Switch off the timer when it_value is zero */
if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
return 0;
timr->it_interval = timespec64_to_ktime(new_setting->it_interval);
expires = timespec64_to_ktime(new_setting->it_value);
sigev_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE;
kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none);
timr->it_active = !sigev_none;
return 0;
}
Commit Message: posix-timer: Properly check sigevent->sigev_notify
timer_create() specifies via sigevent->sigev_notify the signal delivery for
the new timer. The valid modes are SIGEV_NONE, SIGEV_SIGNAL, SIGEV_THREAD
and (SIGEV_SIGNAL | SIGEV_THREAD_ID).
The sanity check in good_sigevent() is only checking the valid combination
for the SIGEV_THREAD_ID bit, i.e. SIGEV_SIGNAL, but if SIGEV_THREAD_ID is
not set it accepts any random value.
This has no real effects on the posix timer and signal delivery code, but
it affects show_timer() which handles the output of /proc/$PID/timers. That
function uses a string array to pretty print sigev_notify. The access to
that array has no bound checks, so random sigev_notify cause access beyond
the array bounds.
Add proper checks for the valid notify modes and remove the SIGEV_THREAD_ID
masking from various code pathes as SIGEV_NONE can never be set in
combination with SIGEV_THREAD_ID.
Reported-by: Eric Biggers <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Reported-by: Alexey Dobriyan <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: John Stultz <[email protected]>
Cc: [email protected]
CWE ID: CWE-125 | int common_timer_set(struct k_itimer *timr, int flags,
struct itimerspec64 *new_setting,
struct itimerspec64 *old_setting)
{
const struct k_clock *kc = timr->kclock;
bool sigev_none;
ktime_t expires;
if (old_setting)
common_timer_get(timr, old_setting);
/* Prevent rearming by clearing the interval */
timr->it_interval = 0;
/*
* Careful here. On SMP systems the timer expiry function could be
* active and spinning on timr->it_lock.
*/
if (kc->timer_try_to_cancel(timr) < 0)
return TIMER_RETRY;
timr->it_active = 0;
timr->it_requeue_pending = (timr->it_requeue_pending + 2) &
~REQUEUE_PENDING;
timr->it_overrun_last = 0;
/* Switch off the timer when it_value is zero */
if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
return 0;
timr->it_interval = timespec64_to_ktime(new_setting->it_interval);
expires = timespec64_to_ktime(new_setting->it_value);
sigev_none = timr->it_sigev_notify == SIGEV_NONE;
kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none);
timr->it_active = !sigev_none;
return 0;
}
| 169,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count,
loff_t *ppos)
{
struct usb_yurex *dev;
int retval = 0;
int bytes_read = 0;
char in_buffer[20];
unsigned long flags;
dev = file->private_data;
mutex_lock(&dev->io_mutex);
if (!dev->interface) { /* already disconnected */
retval = -ENODEV;
goto exit;
}
spin_lock_irqsave(&dev->lock, flags);
bytes_read = snprintf(in_buffer, 20, "%lld\n", dev->bbu);
spin_unlock_irqrestore(&dev->lock, flags);
if (*ppos < bytes_read) {
if (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos))
retval = -EFAULT;
else {
retval = bytes_read - *ppos;
*ppos += bytes_read;
}
}
exit:
mutex_unlock(&dev->io_mutex);
return retval;
}
Commit Message: USB: yurex: fix out-of-bounds uaccess in read handler
In general, accessing userspace memory beyond the length of the supplied
buffer in VFS read/write handlers can lead to both kernel memory corruption
(via kernel_read()/kernel_write(), which can e.g. be triggered via
sys_splice()) and privilege escalation inside userspace.
Fix it by using simple_read_from_buffer() instead of custom logic.
Fixes: 6bc235a2e24a ("USB: add driver for Meywa-Denki & Kayac YUREX")
Signed-off-by: Jann Horn <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-20 | static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count,
loff_t *ppos)
{
struct usb_yurex *dev;
int len = 0;
char in_buffer[20];
unsigned long flags;
dev = file->private_data;
mutex_lock(&dev->io_mutex);
if (!dev->interface) { /* already disconnected */
mutex_unlock(&dev->io_mutex);
return -ENODEV;
}
spin_lock_irqsave(&dev->lock, flags);
len = snprintf(in_buffer, 20, "%lld\n", dev->bbu);
spin_unlock_irqrestore(&dev->lock, flags);
mutex_unlock(&dev->io_mutex);
return simple_read_from_buffer(buffer, count, ppos, in_buffer, len);
}
| 169,084 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static reactor_status_t run_reactor(reactor_t *reactor, int iterations) {
assert(reactor != NULL);
reactor->run_thread = pthread_self();
reactor->is_running = true;
struct epoll_event events[MAX_EVENTS];
for (int i = 0; iterations == 0 || i < iterations; ++i) {
pthread_mutex_lock(&reactor->list_lock);
list_clear(reactor->invalidation_list);
pthread_mutex_unlock(&reactor->list_lock);
int ret;
do {
ret = epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno));
reactor->is_running = false;
return REACTOR_STATUS_ERROR;
}
for (int j = 0; j < ret; ++j) {
if (events[j].data.ptr == NULL) {
eventfd_t value;
eventfd_read(reactor->event_fd, &value);
reactor->is_running = false;
return REACTOR_STATUS_STOP;
}
reactor_object_t *object = (reactor_object_t *)events[j].data.ptr;
pthread_mutex_lock(&reactor->list_lock);
if (list_contains(reactor->invalidation_list, object)) {
pthread_mutex_unlock(&reactor->list_lock);
continue;
}
pthread_mutex_lock(&object->lock);
pthread_mutex_unlock(&reactor->list_lock);
reactor->object_removed = false;
if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready)
object->read_ready(object->context);
if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready)
object->write_ready(object->context);
pthread_mutex_unlock(&object->lock);
if (reactor->object_removed) {
pthread_mutex_destroy(&object->lock);
osi_free(object);
}
}
}
reactor->is_running = false;
return REACTOR_STATUS_DONE;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static reactor_status_t run_reactor(reactor_t *reactor, int iterations) {
assert(reactor != NULL);
reactor->run_thread = pthread_self();
reactor->is_running = true;
struct epoll_event events[MAX_EVENTS];
for (int i = 0; iterations == 0 || i < iterations; ++i) {
pthread_mutex_lock(&reactor->list_lock);
list_clear(reactor->invalidation_list);
pthread_mutex_unlock(&reactor->list_lock);
int ret;
do {
ret = TEMP_FAILURE_RETRY(epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1));
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno));
reactor->is_running = false;
return REACTOR_STATUS_ERROR;
}
for (int j = 0; j < ret; ++j) {
if (events[j].data.ptr == NULL) {
eventfd_t value;
eventfd_read(reactor->event_fd, &value);
reactor->is_running = false;
return REACTOR_STATUS_STOP;
}
reactor_object_t *object = (reactor_object_t *)events[j].data.ptr;
pthread_mutex_lock(&reactor->list_lock);
if (list_contains(reactor->invalidation_list, object)) {
pthread_mutex_unlock(&reactor->list_lock);
continue;
}
pthread_mutex_lock(&object->lock);
pthread_mutex_unlock(&reactor->list_lock);
reactor->object_removed = false;
if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready)
object->read_ready(object->context);
if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready)
object->write_ready(object->context);
pthread_mutex_unlock(&object->lock);
if (reactor->object_removed) {
pthread_mutex_destroy(&object->lock);
osi_free(object);
}
}
}
reactor->is_running = false;
return REACTOR_STATUS_DONE;
}
| 173,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
swapl(&stuff->numSpecs);
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(specs[0]));
}
Commit Message:
CWE ID: CWE-20 | SProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
swapl(&stuff->numSpecs);
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(specs[0]));
}
| 165,435 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) {
#define SIZEOF_FILE_NAME 255
int i = 0;
const char* basename;
if (!dbg_data) {
return 0;
}
switch (dbg_dir_entry->Type) {
case IMAGE_DEBUG_TYPE_CODEVIEW:
if (!strncmp ((char*) dbg_data, "RSDS", 4)) {
SCV_RSDS_HEADER rsds_hdr;
init_rsdr_hdr (&rsds_hdr);
if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) {
bprintf ("Warning: Cannot read PE debug info\n");
return 0;
}
snprintf (res->guidstr, GUIDSTR_LEN,
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x",
rsds_hdr.guid.data1,
rsds_hdr.guid.data2,
rsds_hdr.guid.data3,
rsds_hdr.guid.data4[0],
rsds_hdr.guid.data4[1],
rsds_hdr.guid.data4[2],
rsds_hdr.guid.data4[3],
rsds_hdr.guid.data4[4],
rsds_hdr.guid.data4[5],
rsds_hdr.guid.data4[6],
rsds_hdr.guid.data4[7],
rsds_hdr.age);
basename = r_file_basename ((char*) rsds_hdr.file_name);
strncpy (res->file_name, (const char*)
basename, sizeof (res->file_name));
res->file_name[sizeof (res->file_name) - 1] = 0;
rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr);
} else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) {
SCV_NB10_HEADER nb10_hdr;
init_cv_nb10_header (&nb10_hdr);
get_nb10 (dbg_data, &nb10_hdr);
snprintf (res->guidstr, sizeof (res->guidstr),
"%x%x", nb10_hdr.timestamp, nb10_hdr.age);
strncpy (res->file_name, (const char*)
nb10_hdr.file_name, sizeof(res->file_name) - 1);
res->file_name[sizeof (res->file_name) - 1] = 0;
nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr);
} else {
bprintf ("CodeView section not NB10 or RSDS\n");
return 0;
}
break;
default:
return 0;
}
while (i < 33) {
res->guidstr[i] = toupper ((int) res->guidstr[i]);
i++;
}
return 1;
}
Commit Message: Fix crash in pe
CWE ID: CWE-125 | static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) {
#define SIZEOF_FILE_NAME 255
int i = 0;
const char* basename;
if (!dbg_data) {
return 0;
}
switch (dbg_dir_entry->Type) {
case IMAGE_DEBUG_TYPE_CODEVIEW:
if (!strncmp ((char*) dbg_data, "RSDS", 4)) {
SCV_RSDS_HEADER rsds_hdr;
init_rsdr_hdr (&rsds_hdr);
if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) {
bprintf ("Warning: Cannot read PE debug info\n");
return 0;
}
snprintf (res->guidstr, GUIDSTR_LEN,
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x",
rsds_hdr.guid.data1,
rsds_hdr.guid.data2,
rsds_hdr.guid.data3,
rsds_hdr.guid.data4[0],
rsds_hdr.guid.data4[1],
rsds_hdr.guid.data4[2],
rsds_hdr.guid.data4[3],
rsds_hdr.guid.data4[4],
rsds_hdr.guid.data4[5],
rsds_hdr.guid.data4[6],
rsds_hdr.guid.data4[7],
rsds_hdr.age);
basename = r_file_basename ((char*) rsds_hdr.file_name);
strncpy (res->file_name, (const char*)
basename, sizeof (res->file_name));
res->file_name[sizeof (res->file_name) - 1] = 0;
rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr);
} else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) {
if (dbg_data_len < 20) {
eprintf ("Truncated NB10 entry, not enough data to parse\n");
return 0;
}
SCV_NB10_HEADER nb10_hdr = {{0}};
init_cv_nb10_header (&nb10_hdr);
get_nb10 (dbg_data, &nb10_hdr);
snprintf (res->guidstr, sizeof (res->guidstr),
"%x%x", nb10_hdr.timestamp, nb10_hdr.age);
res->file_name[0] = 0;
if (nb10_hdr.file_name) {
strncpy (res->file_name, (const char*)
nb10_hdr.file_name, sizeof (res->file_name) - 1);
}
res->file_name[sizeof (res->file_name) - 1] = 0;
nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr);
} else {
bprintf ("CodeView section not NB10 or RSDS\n");
return 0;
}
break;
default:
return 0;
}
while (i < 33) {
res->guidstr[i] = toupper ((int) res->guidstr[i]);
i++;
}
return 1;
}
| 169,228 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DataReductionProxySettings::MaybeActivateDataReductionProxy(
bool at_startup) {
DCHECK(thread_checker_.CalledOnValidThread());
PrefService* prefs = GetOriginalProfilePrefs();
if (!prefs)
return;
if (spdy_proxy_auth_enabled_.GetValue() && at_startup) {
int64_t last_enabled_time =
prefs->GetInt64(prefs::kDataReductionProxyLastEnabledTime);
if (last_enabled_time != 0) {
RecordDaysSinceEnabledMetric(
(clock_->Now() - base::Time::FromInternalValue(last_enabled_time))
.InDays());
}
int64_t last_savings_cleared_time = prefs->GetInt64(
prefs::kDataReductionProxySavingsClearedNegativeSystemClock);
if (last_savings_cleared_time != 0) {
int32_t days_since_savings_cleared =
(clock_->Now() -
base::Time::FromInternalValue(last_savings_cleared_time))
.InDays();
if (days_since_savings_cleared == 0)
days_since_savings_cleared = 1;
UMA_HISTOGRAM_CUSTOM_COUNTS(
"DataReductionProxy.DaysSinceSavingsCleared.NegativeSystemClock",
days_since_savings_cleared, 1, 365, 50);
}
}
if (spdy_proxy_auth_enabled_.GetValue() &&
!prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) {
prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true);
ResetDataReductionStatistics();
}
if (!at_startup) {
if (IsDataReductionProxyEnabled()) {
RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON);
prefs->SetInt64(prefs::kDataReductionProxyLastEnabledTime,
clock_->Now().ToInternalValue());
RecordDaysSinceEnabledMetric(0);
} else {
RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF);
}
}
if (at_startup && !data_reduction_proxy_service_->Initialized())
deferred_initialization_ = true;
else
UpdateIOData(at_startup);
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | void DataReductionProxySettings::MaybeActivateDataReductionProxy(
bool at_startup) {
DCHECK(thread_checker_.CalledOnValidThread());
PrefService* prefs = GetOriginalProfilePrefs();
if (!prefs)
return;
bool enabled = IsDataSaverEnabledByUser(prefs);
if (enabled && at_startup) {
int64_t last_enabled_time =
prefs->GetInt64(prefs::kDataReductionProxyLastEnabledTime);
if (last_enabled_time != 0) {
RecordDaysSinceEnabledMetric(
(clock_->Now() - base::Time::FromInternalValue(last_enabled_time))
.InDays());
}
int64_t last_savings_cleared_time = prefs->GetInt64(
prefs::kDataReductionProxySavingsClearedNegativeSystemClock);
if (last_savings_cleared_time != 0) {
int32_t days_since_savings_cleared =
(clock_->Now() -
base::Time::FromInternalValue(last_savings_cleared_time))
.InDays();
if (days_since_savings_cleared == 0)
days_since_savings_cleared = 1;
UMA_HISTOGRAM_CUSTOM_COUNTS(
"DataReductionProxy.DaysSinceSavingsCleared.NegativeSystemClock",
days_since_savings_cleared, 1, 365, 50);
}
}
if (enabled &&
!prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) {
prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true);
ResetDataReductionStatistics();
}
if (!at_startup) {
if (IsDataReductionProxyEnabled()) {
RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON);
prefs->SetInt64(prefs::kDataReductionProxyLastEnabledTime,
clock_->Now().ToInternalValue());
RecordDaysSinceEnabledMetric(0);
} else {
RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF);
}
}
if (at_startup && !data_reduction_proxy_service_->Initialized())
deferred_initialization_ = true;
else
UpdateIOData(at_startup);
}
| 172,557 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) {
PersistentHistogramAllocator::GetCreateHistogramResultHistogram();
InitializeStatisticsRecorder();
if (use_persistent_histogram_allocator_) {
GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0,
"StatisticsRecorderTest");
}
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264 | StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) {
InitializeStatisticsRecorder();
if (use_persistent_histogram_allocator_) {
GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0,
"StatisticsRecorderTest");
}
}
| 172,139 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromeOSChangeInputMethod(
InputMethodStatusConnection* connection, const char* name) {
DCHECK(name);
DLOG(INFO) << "ChangeInputMethod: " << name;
g_return_val_if_fail(connection, false);
return connection->ChangeInputMethod(name);
}
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 | bool ChromeOSChangeInputMethod(
| 170,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
if (!htmlDocument->hasNamedItem(key.impl()) && !htmlDocument->hasExtraNamedItem(key.impl()))
return v8Undefined();
RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
if (items->isEmpty())
return v8Undefined();
if (items->hasExactlyOneItem()) {
Node* node = items->item(0);
Frame* frame = 0;
if (node->hasTagName(HTMLNames::iframeTag) && (frame = toHTMLIFrameElement(node)->contentFrame()))
return toV8(frame->domWindow(), creationContext, isolate);
return toV8(node, creationContext, isolate);
}
return toV8(items.release(), creationContext, isolate);
}
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
if (!htmlDocument->hasNamedItem(key) && !htmlDocument->hasExtraNamedItem(key))
return v8Undefined();
RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
if (items->isEmpty())
return v8Undefined();
if (items->hasExactlyOneItem()) {
Node* node = items->item(0);
Frame* frame = 0;
if (node->hasTagName(HTMLNames::iframeTag) && (frame = toHTMLIFrameElement(node)->contentFrame()))
return toV8(frame->domWindow(), creationContext, isolate);
return toV8(node, creationContext, isolate);
}
return toV8(items.release(), creationContext, isolate);
}
| 171,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ieee80211_radiotap_iterator_init(
struct ieee80211_radiotap_iterator *iterator,
struct ieee80211_radiotap_header *radiotap_header,
int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns)
{
/* Linux only supports version 0 radiotap format */
if (radiotap_header->it_version)
return -EINVAL;
/* sanity check for allowed length and radiotap length field */
if (max_length < get_unaligned_le16(&radiotap_header->it_len))
return -EINVAL;
iterator->_rtheader = radiotap_header;
iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len);
iterator->_arg_index = 0;
iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present);
iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header);
iterator->_reset_on_ext = 0;
iterator->_next_bitmap = &radiotap_header->it_present;
iterator->_next_bitmap++;
iterator->_vns = vns;
iterator->current_namespace = &radiotap_ns;
iterator->is_radiotap_ns = 1;
/* find payload start allowing for extended bitmap(s) */
if (iterator->_bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT)) {
while (get_unaligned_le32(iterator->_arg) &
(1 << IEEE80211_RADIOTAP_EXT)) {
iterator->_arg += sizeof(uint32_t);
/*
* check for insanity where the present bitmaps
* keep claiming to extend up to or even beyond the
* stated radiotap header length
*/
if ((unsigned long)iterator->_arg -
(unsigned long)iterator->_rtheader >
(unsigned long)iterator->_max_length)
return -EINVAL;
}
iterator->_arg += sizeof(uint32_t);
/*
* no need to check again for blowing past stated radiotap
* header length, because ieee80211_radiotap_iterator_next
* checks it before it is dereferenced
*/
}
iterator->this_arg = iterator->_arg;
/* we are all initialized happily */
return 0;
}
Commit Message: wireless: radiotap: fix parsing buffer overrun
When parsing an invalid radiotap header, the parser can overrun
the buffer that is passed in because it doesn't correctly check
1) the minimum radiotap header size
2) the space for extended bitmaps
The first issue doesn't affect any in-kernel user as they all
check the minimum size before calling the radiotap function.
The second issue could potentially affect the kernel if an skb
is passed in that consists only of the radiotap header with a
lot of extended bitmaps that extend past the SKB. In that case
a read-only buffer overrun by at most 4 bytes is possible.
Fix this by adding the appropriate checks to the parser.
Cc: [email protected]
Reported-by: Evan Huus <[email protected]>
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-119 | int ieee80211_radiotap_iterator_init(
struct ieee80211_radiotap_iterator *iterator,
struct ieee80211_radiotap_header *radiotap_header,
int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns)
{
/* check the radiotap header can actually be present */
if (max_length < sizeof(struct ieee80211_radiotap_header))
return -EINVAL;
/* Linux only supports version 0 radiotap format */
if (radiotap_header->it_version)
return -EINVAL;
/* sanity check for allowed length and radiotap length field */
if (max_length < get_unaligned_le16(&radiotap_header->it_len))
return -EINVAL;
iterator->_rtheader = radiotap_header;
iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len);
iterator->_arg_index = 0;
iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present);
iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header);
iterator->_reset_on_ext = 0;
iterator->_next_bitmap = &radiotap_header->it_present;
iterator->_next_bitmap++;
iterator->_vns = vns;
iterator->current_namespace = &radiotap_ns;
iterator->is_radiotap_ns = 1;
/* find payload start allowing for extended bitmap(s) */
if (iterator->_bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT)) {
while (get_unaligned_le32(iterator->_arg) &
(1 << IEEE80211_RADIOTAP_EXT)) {
iterator->_arg += sizeof(uint32_t);
/*
* check for insanity where the present bitmaps
* keep claiming to extend up to or even beyond the
* stated radiotap header length
*/
if ((unsigned long)iterator->_arg -
(unsigned long)iterator->_rtheader +
sizeof(uint32_t) >
(unsigned long)iterator->_max_length)
return -EINVAL;
}
iterator->_arg += sizeof(uint32_t);
/*
* no need to check again for blowing past stated radiotap
* header length, because ieee80211_radiotap_iterator_next
* checks it before it is dereferenced
*/
}
iterator->this_arg = iterator->_arg;
/* we are all initialized happily */
return 0;
}
| 165,909 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ras_validate(jas_stream_t *in)
{
uchar buf[RAS_MAGICLEN];
int i;
int n;
uint_fast32_t magic;
assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < RAS_MAGICLEN) {
return -1;
}
magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |
(JAS_CAST(uint_fast32_t, buf[1]) << 16) |
(JAS_CAST(uint_fast32_t, buf[2]) << 8) |
buf[3];
/* Is the signature correct for the Sun Rasterfile format? */
if (magic != RAS_MAGIC) {
return -1;
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | int ras_validate(jas_stream_t *in)
{
jas_uchar buf[RAS_MAGICLEN];
int i;
int n;
uint_fast32_t magic;
assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < RAS_MAGICLEN) {
return -1;
}
magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |
(JAS_CAST(uint_fast32_t, buf[1]) << 16) |
(JAS_CAST(uint_fast32_t, buf[2]) << 8) |
buf[3];
/* Is the signature correct for the Sun Rasterfile format? */
if (magic != RAS_MAGIC) {
return -1;
}
return 0;
}
| 168,729 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FrameSelection::MoveRangeSelection(const VisiblePosition& base_position,
const VisiblePosition& extent_position,
TextGranularity granularity) {
SelectionInDOMTree new_selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtentDeprecated(base_position.DeepEquivalent(),
extent_position.DeepEquivalent())
.SetAffinity(base_position.Affinity())
.SetIsHandleVisible(IsHandleVisible())
.Build();
if (new_selection.IsNone())
return;
const VisibleSelection& visible_selection =
CreateVisibleSelectionWithGranularity(new_selection, granularity);
if (visible_selection.IsNone())
return;
SelectionInDOMTree::Builder builder;
if (visible_selection.IsBaseFirst()) {
builder.SetBaseAndExtent(visible_selection.Start(),
visible_selection.End());
} else {
builder.SetBaseAndExtent(visible_selection.End(),
visible_selection.Start());
}
builder.SetAffinity(visible_selection.Affinity());
builder.SetIsHandleVisible(IsHandleVisible());
SetSelection(builder.Build(), SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetGranularity(granularity)
.Build());
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119 | void FrameSelection::MoveRangeSelection(const VisiblePosition& base_position,
const VisiblePosition& extent_position,
TextGranularity granularity) {
SelectionInDOMTree new_selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtentDeprecated(base_position.DeepEquivalent(),
extent_position.DeepEquivalent())
.SetAffinity(base_position.Affinity())
.Build();
if (new_selection.IsNone())
return;
const VisibleSelection& visible_selection =
CreateVisibleSelectionWithGranularity(new_selection, granularity);
if (visible_selection.IsNone())
return;
SelectionInDOMTree::Builder builder;
if (visible_selection.IsBaseFirst()) {
builder.SetBaseAndExtent(visible_selection.Start(),
visible_selection.End());
} else {
builder.SetBaseAndExtent(visible_selection.End(),
visible_selection.Start());
}
builder.SetAffinity(visible_selection.Affinity());
SetSelection(builder.Build(), SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetGranularity(granularity)
.SetShouldShowHandle(IsHandleVisible())
.Build());
}
| 171,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
renderer_process_(base::kNullProcessHandle),
renderer_pid_(base::kNullProcessId),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
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: | GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
| 170,931 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void EncoderTest::InitializeConfig() {
const vpx_codec_err_t res = codec_->DefaultEncoderConfig(&cfg_, 0);
ASSERT_EQ(VPX_CODEC_OK, res);
}
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 | void EncoderTest::InitializeConfig() {
const vpx_codec_err_t res = codec_->DefaultEncoderConfig(&cfg_, 0);
dec_cfg_ = vpx_codec_dec_cfg_t();
ASSERT_EQ(VPX_CODEC_OK, res);
}
| 174,538 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_seq_ioctl_remove_events(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_remove_events info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/*
* Input mostly not implemented XXX.
*/
if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
/*
* No restrictions so for a user client we can clear
* the whole fifo
*/
if (client->type == USER_CLIENT)
snd_seq_fifo_clear(client->data.user.fifo);
}
if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
snd_seq_queue_remove_cells(client->number, &info);
return 0;
}
Commit Message: ALSA: seq: Fix missing NULL check at remove_events ioctl
snd_seq_ioctl_remove_events() calls snd_seq_fifo_clear()
unconditionally even if there is no FIFO assigned, and this leads to
an Oops due to NULL dereference. The fix is just to add a proper NULL
check.
Reported-by: Dmitry Vyukov <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: | static int snd_seq_ioctl_remove_events(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_remove_events info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/*
* Input mostly not implemented XXX.
*/
if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
/*
* No restrictions so for a user client we can clear
* the whole fifo
*/
if (client->type == USER_CLIENT && client->data.user.fifo)
snd_seq_fifo_clear(client->data.user.fifo);
}
if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
snd_seq_queue_remove_cells(client->number, &info);
return 0;
}
| 167,410 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole,
OnDidAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState,
OnUpdateUserActivationState)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking,
OnSetNeedsOcclusionTracking);
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame,
OnBubbleLogicalScrollInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess,
OnRenderFallbackContentInParentProcess)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416 | bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState,
OnUpdateUserActivationState)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking,
OnSetNeedsOcclusionTracking);
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame,
OnBubbleLogicalScrollInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess,
OnRenderFallbackContentInParentProcess)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_END_MESSAGE_MAP()
return handled;
}
| 172,486 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_MINIT_FUNCTION(gd)
{
le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, "gd", module_number);
le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, "gd font", module_number);
#if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE
gdFontCacheMutexSetup();
#endif
#if HAVE_LIBT1
T1_SetBitmapPad(8);
T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE);
T1_SetLogLevel(T1LOG_DEBUG);
le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, "gd PS font", module_number);
le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, "gd PS encoding", module_number);
#endif
#ifndef HAVE_GD_BUNDLED
gdSetErrorMethod(php_gd_error_method);
#endif
REGISTER_INI_ENTRIES();
REGISTER_LONG_CONSTANT("IMG_GIF", 1, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_JPG", 2, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_JPEG", 2, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_PNG", 4, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WBMP", 8, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_XPM", 16, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WEBP", 32, CONST_CS | CONST_PERSISTENT);
/* special colours for gd */
REGISTER_LONG_CONSTANT("IMG_COLOR_TILED", gdTiled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_STYLED", gdStyled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_BRUSHED", gdBrushed, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_STYLEDBRUSHED", gdStyledBrushed, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_TRANSPARENT", gdTransparent, CONST_CS | CONST_PERSISTENT);
/* for imagefilledarc */
REGISTER_LONG_CONSTANT("IMG_ARC_ROUNDED", gdArc, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_PIE", gdPie, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_CHORD", gdChord, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_NOFILL", gdNoFill, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_EDGED", gdEdged, CONST_CS | CONST_PERSISTENT);
/* GD2 image format types */
REGISTER_LONG_CONSTANT("IMG_GD2_RAW", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GD2_COMPRESSED", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_HORIZONTAL", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_VERTICAL", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_BOTH", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_REPLACE", gdEffectReplace, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_ALPHABLEND", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_NORMAL", gdEffectNormal, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_OVERLAY", gdEffectOverlay, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_DEFAULT", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_TRANSPARENT", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_BLACK", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_WHITE", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_SIDES", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_THRESHOLD", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BELL", GD_BELL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BESSEL", GD_BESSEL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BILINEAR_FIXED", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BICUBIC", GD_BICUBIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BICUBIC_FIXED", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BLACKMAN", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BOX", GD_BOX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BSPLINE", GD_BSPLINE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CATMULLROM", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GAUSSIAN", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GENERALIZED_CUBIC", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HERMITE", GD_HERMITE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HAMMING", GD_HAMMING, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HANNING", GD_HANNING, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_MITCHELL", GD_MITCHELL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_POWER", GD_POWER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_QUADRATIC", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_SINC", GD_SINC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_NEAREST_NEIGHBOUR", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WEIGHTED4", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_TRIANGLE", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_TRANSLATE", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SCALE", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_ROTATE", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_HORIZONTAL", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_VERTICAL", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT);
#if defined(HAVE_GD_BUNDLED)
REGISTER_LONG_CONSTANT("GD_BUNDLED", 1, CONST_CS | CONST_PERSISTENT);
#else
REGISTER_LONG_CONSTANT("GD_BUNDLED", 0, CONST_CS | CONST_PERSISTENT);
#endif
/* Section Filters */
REGISTER_LONG_CONSTANT("IMG_FILTER_NEGATE", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_GRAYSCALE", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_BRIGHTNESS", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_CONTRAST", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_COLORIZE", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_EDGEDETECT", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_GAUSSIAN_BLUR", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_SELECTIVE_BLUR", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_EMBOSS", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_MEAN_REMOVAL", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_SMOOTH", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_PIXELATE", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT);
/* End Section Filters */
#ifdef GD_VERSION_STRING
REGISTER_STRING_CONSTANT("GD_VERSION", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT);
#endif
#if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION)
REGISTER_LONG_CONSTANT("GD_MAJOR_VERSION", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GD_MINOR_VERSION", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GD_RELEASE_VERSION", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("GD_EXTRA_VERSION", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT);
#endif
#ifdef HAVE_GD_PNG
/*
* cannot include #include "png.h"
* /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup.
* as error, use the values for now...
*/
REGISTER_LONG_CONSTANT("PNG_NO_FILTER", 0x00, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_NONE", 0x08, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_SUB", 0x10, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_UP", 0x20, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_AVG", 0x40, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_PAETH", 0x80, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_ALL_FILTERS", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT);
#endif
return SUCCESS;
}
Commit Message: Fix bug#72697 - select_colors write out-of-bounds
CWE ID: CWE-787 | PHP_MINIT_FUNCTION(gd)
{
le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, "gd", module_number);
le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, "gd font", module_number);
#if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE
gdFontCacheMutexSetup();
#endif
#if HAVE_LIBT1
T1_SetBitmapPad(8);
T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE);
T1_SetLogLevel(T1LOG_DEBUG);
le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, "gd PS font", module_number);
le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, "gd PS encoding", module_number);
#endif
#ifndef HAVE_GD_BUNDLED
gdSetErrorMethod(php_gd_error_method);
#endif
REGISTER_INI_ENTRIES();
REGISTER_LONG_CONSTANT("IMG_GIF", 1, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_JPG", 2, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_JPEG", 2, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_PNG", 4, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WBMP", 8, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_XPM", 16, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WEBP", 32, CONST_CS | CONST_PERSISTENT);
/* special colours for gd */
REGISTER_LONG_CONSTANT("IMG_COLOR_TILED", gdTiled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_STYLED", gdStyled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_BRUSHED", gdBrushed, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_STYLEDBRUSHED", gdStyledBrushed, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_COLOR_TRANSPARENT", gdTransparent, CONST_CS | CONST_PERSISTENT);
/* for imagefilledarc */
REGISTER_LONG_CONSTANT("IMG_ARC_ROUNDED", gdArc, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_PIE", gdPie, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_CHORD", gdChord, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_NOFILL", gdNoFill, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_ARC_EDGED", gdEdged, CONST_CS | CONST_PERSISTENT);
/* GD2 image format types */
REGISTER_LONG_CONSTANT("IMG_GD2_RAW", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GD2_COMPRESSED", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_HORIZONTAL", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_VERTICAL", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FLIP_BOTH", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_REPLACE", gdEffectReplace, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_ALPHABLEND", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_NORMAL", gdEffectNormal, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_EFFECT_OVERLAY", gdEffectOverlay, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_DEFAULT", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_TRANSPARENT", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_BLACK", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_WHITE", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_SIDES", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CROP_THRESHOLD", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BELL", GD_BELL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BESSEL", GD_BESSEL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BILINEAR_FIXED", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BICUBIC", GD_BICUBIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BICUBIC_FIXED", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BLACKMAN", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BOX", GD_BOX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_BSPLINE", GD_BSPLINE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_CATMULLROM", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GAUSSIAN", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_GENERALIZED_CUBIC", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HERMITE", GD_HERMITE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HAMMING", GD_HAMMING, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_HANNING", GD_HANNING, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_MITCHELL", GD_MITCHELL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_POWER", GD_POWER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_QUADRATIC", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_SINC", GD_SINC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_NEAREST_NEIGHBOUR", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_WEIGHTED4", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_TRIANGLE", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_TRANSLATE", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SCALE", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_ROTATE", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_HORIZONTAL", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_VERTICAL", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT);
#if defined(HAVE_GD_BUNDLED)
REGISTER_LONG_CONSTANT("GD_BUNDLED", 1, CONST_CS | CONST_PERSISTENT);
#else
REGISTER_LONG_CONSTANT("GD_BUNDLED", 0, CONST_CS | CONST_PERSISTENT);
#endif
/* Section Filters */
REGISTER_LONG_CONSTANT("IMG_FILTER_NEGATE", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_GRAYSCALE", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_BRIGHTNESS", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_CONTRAST", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_COLORIZE", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_EDGEDETECT", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_GAUSSIAN_BLUR", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_SELECTIVE_BLUR", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_EMBOSS", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_MEAN_REMOVAL", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_SMOOTH", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("IMG_FILTER_PIXELATE", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT);
/* End Section Filters */
#ifdef GD_VERSION_STRING
REGISTER_STRING_CONSTANT("GD_VERSION", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT);
#endif
#if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION)
REGISTER_LONG_CONSTANT("GD_MAJOR_VERSION", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GD_MINOR_VERSION", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GD_RELEASE_VERSION", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("GD_EXTRA_VERSION", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT);
#endif
#ifdef HAVE_GD_PNG
/*
* cannot include #include "png.h"
* /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup.
* as error, use the values for now...
*/
REGISTER_LONG_CONSTANT("PNG_NO_FILTER", 0x00, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_NONE", 0x08, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_SUB", 0x10, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_UP", 0x20, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_AVG", 0x40, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_FILTER_PAETH", 0x80, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PNG_ALL_FILTERS", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT);
#endif
return SUCCESS;
}
| 166,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t driver_override_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
char *driver_override, *old = pdev->driver_override, *cp;
if (count > PATH_MAX)
return -EINVAL;
driver_override = kstrndup(buf, count, GFP_KERNEL);
if (!driver_override)
return -ENOMEM;
cp = strchr(driver_override, '\n');
if (cp)
*cp = '\0';
if (strlen(driver_override)) {
pdev->driver_override = driver_override;
} else {
kfree(driver_override);
pdev->driver_override = NULL;
}
kfree(old);
return count;
}
Commit Message: driver core: platform: fix race condition with driver_override
The driver_override implementation is susceptible to race condition when
different threads are reading vs storing a different driver override.
Add locking to avoid race condition.
Fixes: 3d713e0e382e ("driver core: platform: add device binding path 'driver_override'")
Cc: [email protected]
Signed-off-by: Adrian Salido <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-362 | static ssize_t driver_override_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
char *driver_override, *old, *cp;
if (count > PATH_MAX)
return -EINVAL;
driver_override = kstrndup(buf, count, GFP_KERNEL);
if (!driver_override)
return -ENOMEM;
cp = strchr(driver_override, '\n');
if (cp)
*cp = '\0';
device_lock(dev);
old = pdev->driver_override;
if (strlen(driver_override)) {
pdev->driver_override = driver_override;
} else {
kfree(driver_override);
pdev->driver_override = NULL;
}
device_unlock(dev);
kfree(old);
return count;
}
| 167,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
| 169,080 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MarkingVisitor::ConservativelyMarkHeader(HeapObjectHeader* header) {
const GCInfo* gc_info = ThreadHeap::GcInfo(header->GcInfoIndex());
if (gc_info->HasVTable() && !VTableInitialized(header->Payload())) {
MarkHeaderNoTracing(header);
#if DCHECK_IS_ON()
DCHECK(IsUninitializedMemory(header->Payload(), header->PayloadSize()));
#endif
} else {
MarkHeader(header, gc_info->trace_);
}
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560434}
CWE ID: CWE-362 | void MarkingVisitor::ConservativelyMarkHeader(HeapObjectHeader* header) {
const GCInfo* gc_info =
GCInfoTable::Get().GCInfoFromIndex(header->GcInfoIndex());
if (gc_info->HasVTable() && !VTableInitialized(header->Payload())) {
MarkHeaderNoTracing(header);
#if DCHECK_IS_ON()
DCHECK(IsUninitializedMemory(header->Payload(), header->PayloadSize()));
#endif
} else {
MarkHeader(header, gc_info->trace_);
}
}
| 173,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void vrend_clear(struct vrend_context *ctx,
unsigned buffers,
const union pipe_color_union *color,
double depth, unsigned stencil)
{
GLbitfield bits = 0;
if (ctx->in_error)
return;
if (ctx->ctx_switch_pending)
vrend_finish_context_switch(ctx);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id);
vrend_update_frontface_state(ctx);
if (ctx->sub->stencil_state_dirty)
vrend_update_stencil_state(ctx);
if (ctx->sub->scissor_state_dirty)
vrend_update_scissor_state(ctx);
if (ctx->sub->viewport_state_dirty)
vrend_update_viewport_state(ctx);
vrend_use_program(ctx, 0);
if (buffers & PIPE_CLEAR_COLOR) {
if (ctx->sub->nr_cbufs && ctx->sub->surf[0] && vrend_format_is_emulated_alpha(ctx->sub->surf[0]->format)) {
glClearColor(color->f[3], 0.0, 0.0, 0.0);
} else {
glClearColor(color->f[0], color->f[1], color->f[2], color->f[3]);
}
}
if (buffers & PIPE_CLEAR_DEPTH) {
/* gallium clears don't respect depth mask */
glDepthMask(GL_TRUE);
glClearDepth(depth);
}
if (buffers & PIPE_CLEAR_STENCIL)
glClearStencil(stencil);
if (buffers & PIPE_CLEAR_COLOR) {
uint32_t mask = 0;
int i;
for (i = 0; i < ctx->sub->nr_cbufs; i++) {
if (ctx->sub->surf[i])
mask |= (1 << i);
}
if (mask != (buffers >> 2)) {
mask = buffers >> 2;
while (mask) {
i = u_bit_scan(&mask);
if (util_format_is_pure_uint(ctx->sub->surf[i]->format))
glClearBufferuiv(GL_COLOR,
i, (GLuint *)color);
else if (util_format_is_pure_sint(ctx->sub->surf[i]->format))
glClearBufferiv(GL_COLOR,
i, (GLint *)color);
else
glClearBufferfv(GL_COLOR,
i, (GLfloat *)color);
}
}
else
bits |= GL_COLOR_BUFFER_BIT;
}
if (buffers & PIPE_CLEAR_DEPTH)
bits |= GL_DEPTH_BUFFER_BIT;
if (buffers & PIPE_CLEAR_STENCIL)
bits |= GL_STENCIL_BUFFER_BIT;
if (bits)
glClear(bits);
if (buffers & PIPE_CLEAR_DEPTH)
if (!ctx->sub->dsa_state.depth.writemask)
glDepthMask(GL_FALSE);
}
Commit Message:
CWE ID: CWE-476 | void vrend_clear(struct vrend_context *ctx,
unsigned buffers,
const union pipe_color_union *color,
double depth, unsigned stencil)
{
GLbitfield bits = 0;
if (ctx->in_error)
return;
if (ctx->ctx_switch_pending)
vrend_finish_context_switch(ctx);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id);
vrend_update_frontface_state(ctx);
if (ctx->sub->stencil_state_dirty)
vrend_update_stencil_state(ctx);
if (ctx->sub->scissor_state_dirty)
vrend_update_scissor_state(ctx);
if (ctx->sub->viewport_state_dirty)
vrend_update_viewport_state(ctx);
vrend_use_program(ctx, 0);
if (buffers & PIPE_CLEAR_COLOR) {
if (ctx->sub->nr_cbufs && ctx->sub->surf[0] && vrend_format_is_emulated_alpha(ctx->sub->surf[0]->format)) {
glClearColor(color->f[3], 0.0, 0.0, 0.0);
} else {
glClearColor(color->f[0], color->f[1], color->f[2], color->f[3]);
}
}
if (buffers & PIPE_CLEAR_DEPTH) {
/* gallium clears don't respect depth mask */
glDepthMask(GL_TRUE);
glClearDepth(depth);
}
if (buffers & PIPE_CLEAR_STENCIL)
glClearStencil(stencil);
if (buffers & PIPE_CLEAR_COLOR) {
uint32_t mask = 0;
int i;
for (i = 0; i < ctx->sub->nr_cbufs; i++) {
if (ctx->sub->surf[i])
mask |= (1 << i);
}
if (mask != (buffers >> 2)) {
mask = buffers >> 2;
while (mask) {
i = u_bit_scan(&mask);
if (i < PIPE_MAX_COLOR_BUFS && ctx->sub->surf[i] && util_format_is_pure_uint(ctx->sub->surf[i] && ctx->sub->surf[i]->format))
glClearBufferuiv(GL_COLOR,
i, (GLuint *)color);
else if (i < PIPE_MAX_COLOR_BUFS && ctx->sub->surf[i] && util_format_is_pure_sint(ctx->sub->surf[i] && ctx->sub->surf[i]->format))
glClearBufferiv(GL_COLOR,
i, (GLint *)color);
else
glClearBufferfv(GL_COLOR,
i, (GLfloat *)color);
}
}
else
bits |= GL_COLOR_BUFFER_BIT;
}
if (buffers & PIPE_CLEAR_DEPTH)
bits |= GL_DEPTH_BUFFER_BIT;
if (buffers & PIPE_CLEAR_STENCIL)
bits |= GL_STENCIL_BUFFER_BIT;
if (bits)
glClear(bits);
if (buffers & PIPE_CLEAR_DEPTH)
if (!ctx->sub->dsa_state.depth.writemask)
glDepthMask(GL_FALSE);
}
| 164,958 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LocalFileSystem::resolveURL(ExecutionContext* context, const KURL& fileSystemURL, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks));
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::resolveURLInternal, this, contextPtr, fileSystemURL, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
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 | void LocalFileSystem::resolveURL(ExecutionContext* context, const KURL& fileSystemURL, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
CallbackWrapper* wrapper = new CallbackWrapper(callbacks);
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::resolveURLInternal, this, contextPtr, fileSystemURL, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
| 171,430 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dotraplinkage void notrace do_int3(struct pt_regs *regs, long error_code)
{
#ifdef CONFIG_DYNAMIC_FTRACE
/*
* ftrace must be first, everything else may cause a recursive crash.
* See note by declaration of modifying_ftrace_code in ftrace.c
*/
if (unlikely(atomic_read(&modifying_ftrace_code)) &&
ftrace_int3_handler(regs))
return;
#endif
if (poke_int3_handler(regs))
return;
ist_enter(regs);
RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
#ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
if (kgdb_ll_trap(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
#endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
#ifdef CONFIG_KPROBES
if (kprobe_int3_handler(regs))
goto exit;
#endif
if (notify_die(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
/*
* Let others (NMI) know that the debug stack is in use
* as we may switch to the interrupt stack.
*/
debug_stack_usage_inc();
cond_local_irq_enable(regs);
do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, error_code, NULL);
cond_local_irq_disable(regs);
debug_stack_usage_dec();
exit:
ist_exit(regs);
}
Commit Message: x86/entry/64: Don't use IST entry for #BP stack
There's nothing IST-worthy about #BP/int3. We don't allow kprobes
in the small handful of places in the kernel that run at CPL0 with
an invalid stack, and 32-bit kernels have used normal interrupt
gates for #BP forever.
Furthermore, we don't allow kprobes in places that have usergs while
in kernel mode, so "paranoid" is also unnecessary.
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: [email protected]
CWE ID: CWE-362 | dotraplinkage void notrace do_int3(struct pt_regs *regs, long error_code)
{
#ifdef CONFIG_DYNAMIC_FTRACE
/*
* ftrace must be first, everything else may cause a recursive crash.
* See note by declaration of modifying_ftrace_code in ftrace.c
*/
if (unlikely(atomic_read(&modifying_ftrace_code)) &&
ftrace_int3_handler(regs))
return;
#endif
if (poke_int3_handler(regs))
return;
/*
* Use ist_enter despite the fact that we don't use an IST stack.
* We can be called from a kprobe in non-CONTEXT_KERNEL kernel
* mode or even during context tracking state changes.
*
* This means that we can't schedule. That's okay.
*/
ist_enter(regs);
RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
#ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
if (kgdb_ll_trap(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
#endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
#ifdef CONFIG_KPROBES
if (kprobe_int3_handler(regs))
goto exit;
#endif
if (notify_die(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
cond_local_irq_enable(regs);
do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, error_code, NULL);
cond_local_irq_disable(regs);
exit:
ist_exit(regs);
}
| 169,270 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void mca_ccb_hdl_req(tMCA_CCB* p_ccb, tMCA_CCB_EVT* p_data) {
BT_HDR* p_pkt = &p_data->hdr;
uint8_t *p, *p_start;
tMCA_DCB* p_dcb;
tMCA_CTRL evt_data;
tMCA_CCB_MSG* p_rx_msg = NULL;
uint8_t reject_code = MCA_RSP_NO_RESOURCE;
bool send_rsp = false;
bool check_req = false;
uint8_t reject_opcode;
MCA_TRACE_DEBUG("mca_ccb_hdl_req status:%d", p_ccb->status);
p_rx_msg = (tMCA_CCB_MSG*)p_pkt;
p = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
evt_data.hdr.op_code = *p++;
BE_STREAM_TO_UINT16(evt_data.hdr.mdl_id, p);
reject_opcode = evt_data.hdr.op_code + 1;
MCA_TRACE_DEBUG("received mdl id: %d ", evt_data.hdr.mdl_id);
if (p_ccb->status == MCA_CCB_STAT_PENDING) {
MCA_TRACE_DEBUG("received req inpending state");
/* allow abort in pending state */
if ((p_ccb->status == MCA_CCB_STAT_PENDING) &&
(evt_data.hdr.op_code == MCA_OP_MDL_ABORT_REQ)) {
reject_code = MCA_RSP_SUCCESS;
send_rsp = true;
/* clear the pending status */
p_ccb->status = MCA_CCB_STAT_NORM;
if (p_ccb->p_tx_req &&
((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) {
mca_dcb_dealloc(p_dcb, NULL);
osi_free_and_reset((void**)&p_ccb->p_tx_req);
}
} else
reject_code = MCA_RSP_BAD_OP;
} else if (p_ccb->p_rx_msg) {
MCA_TRACE_DEBUG("still handling prev req");
/* still holding previous message, reject this new one ?? */
} else if (p_ccb->p_tx_req) {
MCA_TRACE_DEBUG("still waiting for a response ctrl_vpsm:0x%x",
p_ccb->ctrl_vpsm);
/* sent a request; waiting for response */
if (p_ccb->ctrl_vpsm == 0) {
MCA_TRACE_DEBUG("local is ACP. accept the cmd from INT");
/* local is acceptor, need to handle the request */
check_req = true;
reject_code = MCA_RSP_SUCCESS;
/* drop the previous request */
if ((p_ccb->p_tx_req->op_code == MCA_OP_MDL_CREATE_REQ) &&
((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) {
mca_dcb_dealloc(p_dcb, NULL);
}
osi_free_and_reset((void**)&p_ccb->p_tx_req);
mca_stop_timer(p_ccb);
} else {
/* local is initiator, ignore the req */
osi_free(p_pkt);
return;
}
} else if (p_pkt->layer_specific != MCA_RSP_SUCCESS) {
reject_code = (uint8_t)p_pkt->layer_specific;
if (((evt_data.hdr.op_code >= MCA_NUM_STANDARD_OPCODE) &&
(evt_data.hdr.op_code < MCA_FIRST_SYNC_OP)) ||
(evt_data.hdr.op_code > MCA_LAST_SYNC_OP)) {
/* invalid op code */
reject_opcode = MCA_OP_ERROR_RSP;
evt_data.hdr.mdl_id = 0;
}
} else {
check_req = true;
reject_code = MCA_RSP_SUCCESS;
}
if (check_req) {
if (reject_code == MCA_RSP_SUCCESS) {
reject_code = MCA_RSP_BAD_MDL;
if (MCA_IS_VALID_MDL_ID(evt_data.hdr.mdl_id) ||
((evt_data.hdr.mdl_id == MCA_ALL_MDL_ID) &&
(evt_data.hdr.op_code == MCA_OP_MDL_DELETE_REQ))) {
reject_code = MCA_RSP_SUCCESS;
/* mdl_id is valid according to the spec */
switch (evt_data.hdr.op_code) {
case MCA_OP_MDL_CREATE_REQ:
evt_data.create_ind.dep_id = *p++;
evt_data.create_ind.cfg = *p++;
p_rx_msg->mdep_id = evt_data.create_ind.dep_id;
if (!mca_is_valid_dep_id(p_ccb->p_rcb, p_rx_msg->mdep_id)) {
MCA_TRACE_ERROR("%s: Invalid local MDEP ID %d", __func__,
p_rx_msg->mdep_id);
reject_code = MCA_RSP_BAD_MDEP;
} else if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) {
MCA_TRACE_DEBUG("the mdl_id is currently used in the CL(create)");
mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id);
} else {
/* check if this dep still have MDL available */
if (mca_dep_free_mdl(p_ccb, evt_data.create_ind.dep_id) == 0) {
MCA_TRACE_ERROR("%s: MAX_MDL is used by MDEP %d", __func__,
evt_data.create_ind.dep_id);
reject_code = MCA_RSP_MDEP_BUSY;
}
}
break;
case MCA_OP_MDL_RECONNECT_REQ:
if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) {
MCA_TRACE_ERROR("%s: MDL_ID %d busy, in CL(reconn)", __func__,
evt_data.hdr.mdl_id);
reject_code = MCA_RSP_MDL_BUSY;
}
break;
case MCA_OP_MDL_ABORT_REQ:
reject_code = MCA_RSP_BAD_OP;
break;
case MCA_OP_MDL_DELETE_REQ:
/* delete the associated mdl */
mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id);
send_rsp = true;
break;
}
}
}
}
if (((reject_code != MCA_RSP_SUCCESS) &&
(evt_data.hdr.op_code != MCA_OP_SYNC_INFO_IND)) ||
send_rsp) {
BT_HDR* p_buf = (BT_HDR*)osi_malloc(MCA_CTRL_MTU + sizeof(BT_HDR));
p_buf->offset = L2CAP_MIN_OFFSET;
p = p_start = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
*p++ = reject_opcode;
*p++ = reject_code;
bool valid_response = true;
switch (reject_opcode) {
case MCA_OP_ERROR_RSP:
case MCA_OP_MDL_CREATE_RSP:
case MCA_OP_MDL_RECONNECT_RSP:
case MCA_OP_MDL_ABORT_RSP:
case MCA_OP_MDL_DELETE_RSP:
UINT16_TO_BE_STREAM(p, evt_data.hdr.mdl_id);
break;
case MCA_OP_SYNC_CAP_RSP:
memset(p, 0, 7);
p += 7;
break;
case MCA_OP_SYNC_SET_RSP:
memset(p, 0, 14);
p += 14;
break;
default:
MCA_TRACE_ERROR("%s: reject_opcode 0x%02x not recognized", __func__,
reject_opcode);
valid_response = false;
break;
}
if (valid_response) {
p_buf->len = p - p_start;
MCA_TRACE_ERROR("%s: reject_opcode=0x%02x, reject_code=0x%02x, length=%d",
__func__, reject_opcode, reject_code, p_buf->len);
L2CA_DataWrite(p_ccb->lcid, p_buf);
} else {
osi_free(p_buf);
}
}
if (reject_code == MCA_RSP_SUCCESS) {
/* use the received GKI buffer to store information to double check response
* API */
p_rx_msg->op_code = evt_data.hdr.op_code;
p_rx_msg->mdl_id = evt_data.hdr.mdl_id;
p_ccb->p_rx_msg = p_rx_msg;
if (send_rsp) {
osi_free(p_pkt);
p_ccb->p_rx_msg = NULL;
}
mca_ccb_report_event(p_ccb, evt_data.hdr.op_code, &evt_data);
} else
osi_free(p_pkt);
}
Commit Message: Add packet length checks in mca_ccb_hdl_req
Bug: 110791536
Test: manual
Change-Id: Ica5d8037246682fdb190b2747a86ed8d44c2869a
(cherry picked from commit 4de7ccdd914b7a178df9180d15f675b257ea6e02)
CWE ID: CWE-125 | void mca_ccb_hdl_req(tMCA_CCB* p_ccb, tMCA_CCB_EVT* p_data) {
BT_HDR* p_pkt = &p_data->hdr;
uint8_t *p, *p_start;
tMCA_DCB* p_dcb;
tMCA_CTRL evt_data;
tMCA_CCB_MSG* p_rx_msg = NULL;
uint8_t reject_code = MCA_RSP_NO_RESOURCE;
bool send_rsp = false;
bool check_req = false;
uint8_t reject_opcode;
MCA_TRACE_DEBUG("mca_ccb_hdl_req status:%d", p_ccb->status);
p_rx_msg = (tMCA_CCB_MSG*)p_pkt;
p = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
evt_data.hdr.op_code = *p++;
reject_opcode = evt_data.hdr.op_code + 1;
if (p_pkt->len >= 3) {
BE_STREAM_TO_UINT16(evt_data.hdr.mdl_id, p);
} else {
android_errorWriteLog(0x534e4554, "110791536");
evt_data.hdr.mdl_id = 0;
}
MCA_TRACE_DEBUG("received mdl id: %d ", evt_data.hdr.mdl_id);
if (p_ccb->status == MCA_CCB_STAT_PENDING) {
MCA_TRACE_DEBUG("received req inpending state");
/* allow abort in pending state */
if ((p_ccb->status == MCA_CCB_STAT_PENDING) &&
(evt_data.hdr.op_code == MCA_OP_MDL_ABORT_REQ)) {
reject_code = MCA_RSP_SUCCESS;
send_rsp = true;
/* clear the pending status */
p_ccb->status = MCA_CCB_STAT_NORM;
if (p_ccb->p_tx_req &&
((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) {
mca_dcb_dealloc(p_dcb, NULL);
osi_free_and_reset((void**)&p_ccb->p_tx_req);
}
} else
reject_code = MCA_RSP_BAD_OP;
} else if (p_ccb->p_rx_msg) {
MCA_TRACE_DEBUG("still handling prev req");
/* still holding previous message, reject this new one ?? */
} else if (p_ccb->p_tx_req) {
MCA_TRACE_DEBUG("still waiting for a response ctrl_vpsm:0x%x",
p_ccb->ctrl_vpsm);
/* sent a request; waiting for response */
if (p_ccb->ctrl_vpsm == 0) {
MCA_TRACE_DEBUG("local is ACP. accept the cmd from INT");
/* local is acceptor, need to handle the request */
check_req = true;
reject_code = MCA_RSP_SUCCESS;
/* drop the previous request */
if ((p_ccb->p_tx_req->op_code == MCA_OP_MDL_CREATE_REQ) &&
((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) {
mca_dcb_dealloc(p_dcb, NULL);
}
osi_free_and_reset((void**)&p_ccb->p_tx_req);
mca_stop_timer(p_ccb);
} else {
/* local is initiator, ignore the req */
osi_free(p_pkt);
return;
}
} else if (p_pkt->layer_specific != MCA_RSP_SUCCESS) {
reject_code = (uint8_t)p_pkt->layer_specific;
if (((evt_data.hdr.op_code >= MCA_NUM_STANDARD_OPCODE) &&
(evt_data.hdr.op_code < MCA_FIRST_SYNC_OP)) ||
(evt_data.hdr.op_code > MCA_LAST_SYNC_OP)) {
/* invalid op code */
reject_opcode = MCA_OP_ERROR_RSP;
evt_data.hdr.mdl_id = 0;
}
} else {
check_req = true;
reject_code = MCA_RSP_SUCCESS;
}
if (check_req) {
if (reject_code == MCA_RSP_SUCCESS) {
reject_code = MCA_RSP_BAD_MDL;
if (MCA_IS_VALID_MDL_ID(evt_data.hdr.mdl_id) ||
((evt_data.hdr.mdl_id == MCA_ALL_MDL_ID) &&
(evt_data.hdr.op_code == MCA_OP_MDL_DELETE_REQ))) {
reject_code = MCA_RSP_SUCCESS;
/* mdl_id is valid according to the spec */
switch (evt_data.hdr.op_code) {
case MCA_OP_MDL_CREATE_REQ:
evt_data.create_ind.dep_id = *p++;
evt_data.create_ind.cfg = *p++;
p_rx_msg->mdep_id = evt_data.create_ind.dep_id;
if (!mca_is_valid_dep_id(p_ccb->p_rcb, p_rx_msg->mdep_id)) {
MCA_TRACE_ERROR("%s: Invalid local MDEP ID %d", __func__,
p_rx_msg->mdep_id);
reject_code = MCA_RSP_BAD_MDEP;
} else if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) {
MCA_TRACE_DEBUG("the mdl_id is currently used in the CL(create)");
mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id);
} else {
/* check if this dep still have MDL available */
if (mca_dep_free_mdl(p_ccb, evt_data.create_ind.dep_id) == 0) {
MCA_TRACE_ERROR("%s: MAX_MDL is used by MDEP %d", __func__,
evt_data.create_ind.dep_id);
reject_code = MCA_RSP_MDEP_BUSY;
}
}
break;
case MCA_OP_MDL_RECONNECT_REQ:
if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) {
MCA_TRACE_ERROR("%s: MDL_ID %d busy, in CL(reconn)", __func__,
evt_data.hdr.mdl_id);
reject_code = MCA_RSP_MDL_BUSY;
}
break;
case MCA_OP_MDL_ABORT_REQ:
reject_code = MCA_RSP_BAD_OP;
break;
case MCA_OP_MDL_DELETE_REQ:
/* delete the associated mdl */
mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id);
send_rsp = true;
break;
}
}
}
}
if (((reject_code != MCA_RSP_SUCCESS) &&
(evt_data.hdr.op_code != MCA_OP_SYNC_INFO_IND)) ||
send_rsp) {
BT_HDR* p_buf = (BT_HDR*)osi_malloc(MCA_CTRL_MTU + sizeof(BT_HDR));
p_buf->offset = L2CAP_MIN_OFFSET;
p = p_start = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
*p++ = reject_opcode;
*p++ = reject_code;
bool valid_response = true;
switch (reject_opcode) {
case MCA_OP_ERROR_RSP:
case MCA_OP_MDL_CREATE_RSP:
case MCA_OP_MDL_RECONNECT_RSP:
case MCA_OP_MDL_ABORT_RSP:
case MCA_OP_MDL_DELETE_RSP:
UINT16_TO_BE_STREAM(p, evt_data.hdr.mdl_id);
break;
case MCA_OP_SYNC_CAP_RSP:
memset(p, 0, 7);
p += 7;
break;
case MCA_OP_SYNC_SET_RSP:
memset(p, 0, 14);
p += 14;
break;
default:
MCA_TRACE_ERROR("%s: reject_opcode 0x%02x not recognized", __func__,
reject_opcode);
valid_response = false;
break;
}
if (valid_response) {
p_buf->len = p - p_start;
MCA_TRACE_ERROR("%s: reject_opcode=0x%02x, reject_code=0x%02x, length=%d",
__func__, reject_opcode, reject_code, p_buf->len);
L2CA_DataWrite(p_ccb->lcid, p_buf);
} else {
osi_free(p_buf);
}
}
if (reject_code == MCA_RSP_SUCCESS) {
/* use the received GKI buffer to store information to double check response
* API */
p_rx_msg->op_code = evt_data.hdr.op_code;
p_rx_msg->mdl_id = evt_data.hdr.mdl_id;
p_ccb->p_rx_msg = p_rx_msg;
if (send_rsp) {
osi_free(p_pkt);
p_ccb->p_rx_msg = NULL;
}
mca_ccb_report_event(p_ccb, evt_data.hdr.op_code, &evt_data);
} else
osi_free(p_pkt);
}
| 174,080 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int string_check(char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf failed:\nwe '%s'\nsystem: '%s'\n",
buf, buf2);
return 1;
}
return 0;
}
Commit Message: printf: fix floating point buffer overflow issues
... and add a bunch of floating point printf tests
CWE ID: CWE-119 | static int string_check(char *buf, const char *buf2)
static int _string_check(int linenumber, char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf line %d failed:\nwe '%s'\nsystem: '%s'\n",
linenumber, buf, buf2);
return 1;
}
return 0;
}
| 169,437 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostViewAura::RunCompositingDidCommitCallbacks(
ui::Compositor* compositor) {
for (std::vector< base::Callback<void(ui::Compositor*)> >::const_iterator
it = on_compositing_did_commit_callbacks_.begin();
it != on_compositing_did_commit_callbacks_.end(); ++it) {
it->Run(compositor);
}
on_compositing_did_commit_callbacks_.clear();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderWidgetHostViewAura::RunCompositingDidCommitCallbacks(
void RenderWidgetHostViewAura::RunCompositingDidCommitCallbacks() {
for (std::vector<base::Closure>::const_iterator
it = on_compositing_did_commit_callbacks_.begin();
it != on_compositing_did_commit_callbacks_.end(); ++it) {
it->Run();
}
on_compositing_did_commit_callbacks_.clear();
}
| 171,384 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.