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: FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
mWriteBuffer = buffer;
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
memmove(mWriteBuffer, buffer, sizeof(const FLAC__int32 * const) * getChannels());
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
| 174,026 |
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 SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: SampleTable: check integer overflow during table alloc
Bug: 15328708
Bug: 15342615
Bug: 15342751
Change-Id: I6bb110a1eba46506799c73be8ff9a4f71c7e7053
CWE ID: CWE-189 | status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
| 173,377 |
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 _ewk_frame_smart_del(Evas_Object* ewkFrame)
{
EWK_FRAME_SD_GET(ewkFrame, smartData);
if (smartData) {
if (smartData->frame) {
WebCore::FrameLoaderClientEfl* flc = _ewk_frame_loader_efl_get(smartData->frame);
flc->setWebFrame(0);
smartData->frame->loader()->detachFromParent();
smartData->frame->loader()->cancelAndClear();
smartData->frame = 0;
}
eina_stringshare_del(smartData->title);
eina_stringshare_del(smartData->uri);
eina_stringshare_del(smartData->name);
}
_parent_sc.del(ewkFrame);
}
Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing
https://bugs.webkit.org/show_bug.cgi?id=85879
Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17
Reviewed by Noam Rosenthal.
Source/WebKit/efl:
_ewk_frame_smart_del() is considering now that the frame can be present in cache.
loader()->detachFromParent() is only applied for the main frame.
loader()->cancelAndClear() is not used anymore.
* ewk/ewk_frame.cpp:
(_ewk_frame_smart_del):
LayoutTests:
* platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html.
git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void _ewk_frame_smart_del(Evas_Object* ewkFrame)
{
EWK_FRAME_SD_GET(ewkFrame, smartData);
if (smartData) {
if (smartData->frame) {
WebCore::FrameLoaderClientEfl* flc = _ewk_frame_loader_efl_get(smartData->frame);
flc->setWebFrame(0);
EWK_FRAME_SD_GET(ewk_view_frame_main_get(smartData->view), mainSmartData);
if (mainSmartData->frame == smartData->frame) // applying only for main frame is enough (will traverse through frame tree)
smartData->frame->loader()->detachFromParent();
smartData->frame = 0;
}
eina_stringshare_del(smartData->title);
eina_stringshare_del(smartData->uri);
eina_stringshare_del(smartData->name);
}
_parent_sc.del(ewkFrame);
}
| 170,978 |
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 rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value,
BN_GENCB *cb)
{
BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp;
BIGNUM local_r0, local_d, local_p;
BIGNUM *pr0, *d, *p;
int bitsp, bitsq, ok = -1, n = 0;
BN_CTX *ctx = NULL;
unsigned long error = 0;
/*
* When generating ridiculously small keys, we can get stuck
* continually regenerating the same prime values.
*/
if (bits < 16) {
ok = 0; /* we set our own err */
RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL);
goto err;
}
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
BN_CTX_start(ctx);
r0 = BN_CTX_get(ctx);
r1 = BN_CTX_get(ctx);
r2 = BN_CTX_get(ctx);
r3 = BN_CTX_get(ctx);
if (r3 == NULL)
goto err;
bitsp = (bits + 1) / 2;
bitsq = bits - bitsp;
/* We need the RSA components non-NULL */
if (!rsa->n && ((rsa->n = BN_new()) == NULL))
goto err;
if (!rsa->d && ((rsa->d = BN_new()) == NULL))
goto err;
if (!rsa->e && ((rsa->e = BN_new()) == NULL))
goto err;
if (!rsa->p && ((rsa->p = BN_new()) == NULL))
goto err;
if (!rsa->q && ((rsa->q = BN_new()) == NULL))
goto err;
if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL))
goto err;
if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL))
goto err;
if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL))
goto err;
if (BN_copy(rsa->e, e_value) == NULL)
goto err;
BN_set_flags(r2, BN_FLG_CONSTTIME);
/* generate p and q */
for (;;) {
if (!BN_sub(r2, rsa->p, BN_value_one()))
goto err;
ERR_set_mark();
if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
/* GCD == 1 since inverse exists */
break;
}
error = ERR_peek_last_error();
if (ERR_GET_LIB(error) == ERR_LIB_BN
&& ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
/* GCD != 1 */
ERR_pop_to_mark();
} else {
goto err;
}
if (!BN_GENCB_call(cb, 2, n++))
goto err;
}
if (!BN_GENCB_call(cb, 3, 0))
goto err;
for (;;) {
do {
if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb))
goto err;
} while (BN_cmp(rsa->p, rsa->q) == 0);
if (!BN_sub(r2, rsa->q, BN_value_one()))
goto err;
ERR_set_mark();
if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
/* GCD == 1 since inverse exists */
break;
}
error = ERR_peek_last_error();
if (ERR_GET_LIB(error) == ERR_LIB_BN
&& ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
/* GCD != 1 */
ERR_pop_to_mark();
} else {
goto err;
}
if (!BN_GENCB_call(cb, 2, n++))
goto err;
}
if (!BN_GENCB_call(cb, 3, 1))
goto err;
if (BN_cmp(rsa->p, rsa->q) < 0) {
tmp = rsa->p;
rsa->p = rsa->q;
rsa->q = tmp;
}
/* calculate n */
if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx))
goto err;
/* calculate d */
if (!BN_sub(r1, rsa->p, BN_value_one()))
goto err; /* p-1 */
if (!BN_sub(r2, rsa->q, BN_value_one()))
goto err; /* q-1 */
if (!BN_mul(r0, r1, r2, ctx))
goto err; /* (p-1)(q-1) */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
pr0 = &local_r0;
BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
} else
pr0 = r0;
if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx))
goto err; /* d */
/* set up d for correct BN_FLG_CONSTTIME flag */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
d = &local_d;
BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
} else
d = rsa->d;
/* calculate d mod (p-1) */
if (!BN_mod(rsa->dmp1, d, r1, ctx))
goto err;
/* calculate d mod (q-1) */
if (!BN_mod(rsa->dmq1, d, r2, ctx))
goto err;
/* calculate inverse of q mod p */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
p = &local_p;
BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
} else
p = rsa->p;
if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx))
goto err;
ok = 1;
err:
if (ok == -1) {
RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN);
ok = 0;
}
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
return ok;
}
Commit Message:
CWE ID: CWE-327 | static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value,
BN_GENCB *cb)
{
BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp;
BIGNUM local_r0, local_d, local_p;
BIGNUM *pr0, *d, *p;
int bitsp, bitsq, ok = -1, n = 0;
BN_CTX *ctx = NULL;
unsigned long error = 0;
/*
* When generating ridiculously small keys, we can get stuck
* continually regenerating the same prime values.
*/
if (bits < 16) {
ok = 0; /* we set our own err */
RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL);
goto err;
}
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
BN_CTX_start(ctx);
r0 = BN_CTX_get(ctx);
r1 = BN_CTX_get(ctx);
r2 = BN_CTX_get(ctx);
r3 = BN_CTX_get(ctx);
if (r3 == NULL)
goto err;
bitsp = (bits + 1) / 2;
bitsq = bits - bitsp;
/* We need the RSA components non-NULL */
if (!rsa->n && ((rsa->n = BN_new()) == NULL))
goto err;
if (!rsa->d && ((rsa->d = BN_new()) == NULL))
goto err;
if (!rsa->e && ((rsa->e = BN_new()) == NULL))
goto err;
if (!rsa->p && ((rsa->p = BN_new()) == NULL))
goto err;
if (!rsa->q && ((rsa->q = BN_new()) == NULL))
goto err;
if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL))
goto err;
if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL))
goto err;
if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL))
goto err;
if (BN_copy(rsa->e, e_value) == NULL)
goto err;
BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
BN_set_flags(r2, BN_FLG_CONSTTIME);
/* generate p and q */
for (;;) {
if (!BN_sub(r2, rsa->p, BN_value_one()))
goto err;
ERR_set_mark();
if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
/* GCD == 1 since inverse exists */
break;
}
error = ERR_peek_last_error();
if (ERR_GET_LIB(error) == ERR_LIB_BN
&& ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
/* GCD != 1 */
ERR_pop_to_mark();
} else {
goto err;
}
if (!BN_GENCB_call(cb, 2, n++))
goto err;
}
if (!BN_GENCB_call(cb, 3, 0))
goto err;
for (;;) {
do {
if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb))
goto err;
} while (BN_cmp(rsa->p, rsa->q) == 0);
if (!BN_sub(r2, rsa->q, BN_value_one()))
goto err;
ERR_set_mark();
if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
/* GCD == 1 since inverse exists */
break;
}
error = ERR_peek_last_error();
if (ERR_GET_LIB(error) == ERR_LIB_BN
&& ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
/* GCD != 1 */
ERR_pop_to_mark();
} else {
goto err;
}
if (!BN_GENCB_call(cb, 2, n++))
goto err;
}
if (!BN_GENCB_call(cb, 3, 1))
goto err;
if (BN_cmp(rsa->p, rsa->q) < 0) {
tmp = rsa->p;
rsa->p = rsa->q;
rsa->q = tmp;
}
/* calculate n */
if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx))
goto err;
/* calculate d */
if (!BN_sub(r1, rsa->p, BN_value_one()))
goto err; /* p-1 */
if (!BN_sub(r2, rsa->q, BN_value_one()))
goto err; /* q-1 */
if (!BN_mul(r0, r1, r2, ctx))
goto err; /* (p-1)(q-1) */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
pr0 = &local_r0;
BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
} else
pr0 = r0;
if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx))
goto err; /* d */
/* set up d for correct BN_FLG_CONSTTIME flag */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
d = &local_d;
BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
} else
d = rsa->d;
/* calculate d mod (p-1) */
if (!BN_mod(rsa->dmp1, d, r1, ctx))
goto err;
/* calculate d mod (q-1) */
if (!BN_mod(rsa->dmq1, d, r2, ctx))
goto err;
/* calculate inverse of q mod p */
if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
p = &local_p;
BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
} else
p = rsa->p;
if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx))
goto err;
ok = 1;
err:
if (ok == -1) {
RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN);
ok = 0;
}
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
return ok;
}
| 165,328 |
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 out_write(struct audio_stream_out *stream, const void* buffer,
size_t bytes)
{
struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
int sent;
DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd);
pthread_mutex_lock(&out->common.lock);
if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED)
{
DEBUG("stream suspended");
pthread_mutex_unlock(&out->common.lock);
return -1;
}
/* only allow autostarting if we are in stopped or standby */
if ((out->common.state == AUDIO_A2DP_STATE_STOPPED) ||
(out->common.state == AUDIO_A2DP_STATE_STANDBY))
{
if (start_audio_datapath(&out->common) < 0)
{
/* emulate time this write represents to avoid very fast write
failures during transition periods or remote suspend */
int us_delay = calc_audiotime(out->common.cfg, bytes);
DEBUG("emulate a2dp write delay (%d us)", us_delay);
usleep(us_delay);
pthread_mutex_unlock(&out->common.lock);
return -1;
}
}
else if (out->common.state != AUDIO_A2DP_STATE_STARTED)
{
ERROR("stream not in stopped or standby");
pthread_mutex_unlock(&out->common.lock);
return -1;
}
pthread_mutex_unlock(&out->common.lock);
sent = skt_write(out->common.audio_fd, buffer, bytes);
if (sent == -1) {
skt_disconnect(out->common.audio_fd);
out->common.audio_fd = AUDIO_SKT_DISCONNECTED;
if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED)
out->common.state = AUDIO_A2DP_STATE_STOPPED;
else
ERROR("write failed : stream suspended, avoid resetting state");
} else {
const size_t frames = bytes / audio_stream_out_frame_size(stream);
out->frames_rendered += frames;
out->frames_presented += frames;
}
DEBUG("wrote %d bytes out of %zu bytes", sent, bytes);
return sent;
}
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 ssize_t out_write(struct audio_stream_out *stream, const void* buffer,
size_t bytes)
{
struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
int sent;
DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd);
pthread_mutex_lock(&out->common.lock);
if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED)
{
DEBUG("stream suspended");
pthread_mutex_unlock(&out->common.lock);
return -1;
}
/* only allow autostarting if we are in stopped or standby */
if ((out->common.state == AUDIO_A2DP_STATE_STOPPED) ||
(out->common.state == AUDIO_A2DP_STATE_STANDBY))
{
if (start_audio_datapath(&out->common) < 0)
{
/* emulate time this write represents to avoid very fast write
failures during transition periods or remote suspend */
int us_delay = calc_audiotime(out->common.cfg, bytes);
DEBUG("emulate a2dp write delay (%d us)", us_delay);
TEMP_FAILURE_RETRY(usleep(us_delay));
pthread_mutex_unlock(&out->common.lock);
return -1;
}
}
else if (out->common.state != AUDIO_A2DP_STATE_STARTED)
{
ERROR("stream not in stopped or standby");
pthread_mutex_unlock(&out->common.lock);
return -1;
}
pthread_mutex_unlock(&out->common.lock);
sent = skt_write(out->common.audio_fd, buffer, bytes);
if (sent == -1) {
skt_disconnect(out->common.audio_fd);
out->common.audio_fd = AUDIO_SKT_DISCONNECTED;
if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED)
out->common.state = AUDIO_A2DP_STATE_STOPPED;
else
ERROR("write failed : stream suspended, avoid resetting state");
} else {
const size_t frames = bytes / audio_stream_out_frame_size(stream);
out->frames_rendered += frames;
out->frames_presented += frames;
}
DEBUG("wrote %d bytes out of %zu bytes", sent, bytes);
return sent;
}
| 173,427 |
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: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
ND_PRINT((ndo," orig=("));
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
break;
case ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN:
if (ikev1_sub_print(ndo, ISAKMP_NPTYPE_SA,
(const struct isakmp_gen *)cp, ep, phase, doi, proto,
depth) == NULL)
return NULL;
break;
default:
/* NULL is dummy */
isakmp_print(ndo, cp,
item_len - sizeof(*p) - n.spi_size,
NULL);
}
ND_PRINT((ndo,")"));
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-835 | ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
| 167,924 |
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 PHP_NAMED_FUNCTION(zif_zip_entry_read)
{
zval * zip_entry;
zend_long len = 0;
zip_read_rsrc * zr_rsrc;
zend_string *buffer;
int n = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &zip_entry, &len) == FAILURE) {
return;
}
if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) {
RETURN_FALSE;
}
if (len <= 0) {
len = 1024;
}
if (zr_rsrc->zf) {
buffer = zend_string_alloc(len, 0);
n = zip_fread(zr_rsrc->zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer));
if (n > 0) {
ZSTR_VAL(buffer)[n] = '\0';
ZSTR_LEN(buffer) = n;
RETURN_NEW_STR(buffer);
} else {
zend_string_free(buffer);
RETURN_EMPTY_STRING()
}
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom*
CWE ID: CWE-190 | static PHP_NAMED_FUNCTION(zif_zip_entry_read)
{
zval * zip_entry;
zend_long len = 0;
zip_read_rsrc * zr_rsrc;
zend_string *buffer;
int n = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &zip_entry, &len) == FAILURE) {
return;
}
if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) {
RETURN_FALSE;
}
if (len <= 0) {
len = 1024;
}
if (zr_rsrc->zf) {
buffer = zend_string_safe_alloc(1, len, 0, 0);
n = zip_fread(zr_rsrc->zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer));
if (n > 0) {
ZSTR_VAL(buffer)[n] = '\0';
ZSTR_LEN(buffer) = n;
RETURN_NEW_STR(buffer);
} else {
zend_string_free(buffer);
RETURN_EMPTY_STRING()
}
} else {
RETURN_FALSE;
}
}
| 167,380 |
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 show_object(struct object *obj,
struct strbuf *path, const char *component,
void *cb_data)
{
struct rev_list_info *info = cb_data;
finish_object(obj, path, component, cb_data);
if (info->flags & REV_LIST_QUIET)
return;
show_object_with_name(stdout, obj, path, component);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static void show_object(struct object *obj,
static void show_object(struct object *obj, const char *name, void *cb_data)
{
struct rev_list_info *info = cb_data;
finish_object(obj, name, cb_data);
if (info->flags & REV_LIST_QUIET)
return;
show_object_with_name(stdout, obj, name);
}
| 167,417 |
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: setup_efi_state(struct boot_params *params, unsigned long params_load_addr,
unsigned int efi_map_offset, unsigned int efi_map_sz,
unsigned int efi_setup_data_offset)
{
struct efi_info *current_ei = &boot_params.efi_info;
struct efi_info *ei = ¶ms->efi_info;
if (!current_ei->efi_memmap_size)
return 0;
/*
* If 1:1 mapping is not enabled, second kernel can not setup EFI
* and use EFI run time services. User space will have to pass
* acpi_rsdp=<addr> on kernel command line to make second kernel boot
* without efi.
*/
if (efi_enabled(EFI_OLD_MEMMAP))
return 0;
ei->efi_loader_signature = current_ei->efi_loader_signature;
ei->efi_systab = current_ei->efi_systab;
ei->efi_systab_hi = current_ei->efi_systab_hi;
ei->efi_memdesc_version = current_ei->efi_memdesc_version;
ei->efi_memdesc_size = efi_get_runtime_map_desc_size();
setup_efi_info_memmap(params, params_load_addr, efi_map_offset,
efi_map_sz);
prepare_add_efi_setup_data(params, params_load_addr,
efi_setup_data_offset);
return 0;
}
Commit Message: kexec/uefi: copy secure_boot flag in boot params across kexec reboot
Kexec reboot in case secure boot being enabled does not keep the secure
boot mode in new kernel, so later one can load unsigned kernel via legacy
kexec_load. In this state, the system is missing the protections provided
by secure boot. Adding a patch to fix this by retain the secure_boot flag
in original kernel.
secure_boot flag in boot_params is set in EFI stub, but kexec bypasses the
stub. Fixing this issue by copying secure_boot flag across kexec reboot.
Signed-off-by: Dave Young <[email protected]>
CWE ID: CWE-254 | setup_efi_state(struct boot_params *params, unsigned long params_load_addr,
unsigned int efi_map_offset, unsigned int efi_map_sz,
unsigned int efi_setup_data_offset)
{
struct efi_info *current_ei = &boot_params.efi_info;
struct efi_info *ei = ¶ms->efi_info;
if (!current_ei->efi_memmap_size)
return 0;
/*
* If 1:1 mapping is not enabled, second kernel can not setup EFI
* and use EFI run time services. User space will have to pass
* acpi_rsdp=<addr> on kernel command line to make second kernel boot
* without efi.
*/
if (efi_enabled(EFI_OLD_MEMMAP))
return 0;
params->secure_boot = boot_params.secure_boot;
ei->efi_loader_signature = current_ei->efi_loader_signature;
ei->efi_systab = current_ei->efi_systab;
ei->efi_systab_hi = current_ei->efi_systab_hi;
ei->efi_memdesc_version = current_ei->efi_memdesc_version;
ei->efi_memdesc_size = efi_get_runtime_map_desc_size();
setup_efi_info_memmap(params, params_load_addr, efi_map_offset,
efi_map_sz);
prepare_add_efi_setup_data(params, params_load_addr,
efi_setup_data_offset);
return 0;
}
| 168,868 |
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 Browser::FindInPage(bool find_next, bool forward_direction) {
ShowFindBar();
if (find_next) {
string16 find_text;
#if defined(OS_MACOSX)
find_text = GetFindPboardText();
#endif
GetSelectedTabContentsWrapper()->
GetFindManager()->StartFinding(find_text,
forward_direction,
false); // Not case sensitive.
}
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void Browser::FindInPage(bool find_next, bool forward_direction) {
ShowFindBar();
if (find_next) {
string16 find_text;
#if defined(OS_MACOSX)
find_text = GetFindPboardText();
#endif
GetSelectedTabContentsWrapper()->
find_tab_helper()->StartFinding(find_text,
forward_direction,
false); // Not case sensitive.
}
}
| 170,656 |
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 impeg2d_next_code(dec_state_t *ps_dec, UWORD32 u4_start_code_val)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush_to_byte_boundary(ps_stream);
while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != u4_start_code_val)
&& (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset))
{
if (impeg2d_bit_stream_get(ps_stream,8) != 0)
{
/* Ignore stuffing bit errors. */
}
}
return;
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | void impeg2d_next_code(dec_state_t *ps_dec, UWORD32 u4_start_code_val)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush_to_byte_boundary(ps_stream);
while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != u4_start_code_val) &&
(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset))
{
if (impeg2d_bit_stream_get(ps_stream,8) != 0)
{
/* Ignore stuffing bit errors. */
}
}
return;
}
| 173,950 |
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 __kprobes do_page_fault(unsigned long addr, unsigned int esr,
struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
unsigned long vm_flags = VM_READ | VM_WRITE;
unsigned int mm_flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
tsk = current;
mm = tsk->mm;
/* Enable interrupts if they were enabled in the parent context. */
if (interrupts_enabled(regs))
local_irq_enable();
/*
* If we're in an interrupt or have no user context, we must not take
* the fault.
*/
if (in_atomic() || !mm)
goto no_context;
if (user_mode(regs))
mm_flags |= FAULT_FLAG_USER;
if (esr & ESR_LNX_EXEC) {
vm_flags = VM_EXEC;
} else if ((esr & ESR_EL1_WRITE) && !(esr & ESR_EL1_CM)) {
vm_flags = VM_WRITE;
mm_flags |= FAULT_FLAG_WRITE;
}
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in which
* case, we'll have missed the might_sleep() from down_read().
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, mm_flags, vm_flags, tsk);
/*
* If we need to retry but a fatal signal is pending, handle the
* signal first. We do not need to release the mmap_sem because it
* would already be released in __lock_page_or_retry in mm/filemap.c.
*/
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return 0;
/*
* Major/minor page fault accounting is only done on the initial
* attempt. If we go through a retry, it is extremely likely that the
* page will be found in page cache at that point.
*/
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (mm_flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs,
addr);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs,
addr);
}
if (fault & VM_FAULT_RETRY) {
/*
* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk of
* starvation.
*/
mm_flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP |
VM_FAULT_BADACCESS))))
return 0;
/*
* If we are in kernel mode at this point, we have no context to
* handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we got
* oom-killed).
*/
pagefault_out_of_memory();
return 0;
}
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to successfully fix up
* this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that isn't in our memory
* map.
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, esr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, esr, regs);
return 0;
}
Commit Message: Revert "arm64: Introduce execute-only page access permissions"
This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08.
While the aim is increased security for --x memory maps, it does not
protect against kernel level reads. Until SECCOMP is implemented for
arm64, revert this patch to avoid giving a false idea of execute-only
mappings.
Signed-off-by: Catalin Marinas <[email protected]>
CWE ID: CWE-19 | static int __kprobes do_page_fault(unsigned long addr, unsigned int esr,
struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
unsigned long vm_flags = VM_READ | VM_WRITE | VM_EXEC;
unsigned int mm_flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
tsk = current;
mm = tsk->mm;
/* Enable interrupts if they were enabled in the parent context. */
if (interrupts_enabled(regs))
local_irq_enable();
/*
* If we're in an interrupt or have no user context, we must not take
* the fault.
*/
if (in_atomic() || !mm)
goto no_context;
if (user_mode(regs))
mm_flags |= FAULT_FLAG_USER;
if (esr & ESR_LNX_EXEC) {
vm_flags = VM_EXEC;
} else if ((esr & ESR_EL1_WRITE) && !(esr & ESR_EL1_CM)) {
vm_flags = VM_WRITE;
mm_flags |= FAULT_FLAG_WRITE;
}
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in which
* case, we'll have missed the might_sleep() from down_read().
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, mm_flags, vm_flags, tsk);
/*
* If we need to retry but a fatal signal is pending, handle the
* signal first. We do not need to release the mmap_sem because it
* would already be released in __lock_page_or_retry in mm/filemap.c.
*/
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return 0;
/*
* Major/minor page fault accounting is only done on the initial
* attempt. If we go through a retry, it is extremely likely that the
* page will be found in page cache at that point.
*/
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (mm_flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs,
addr);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs,
addr);
}
if (fault & VM_FAULT_RETRY) {
/*
* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk of
* starvation.
*/
mm_flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP |
VM_FAULT_BADACCESS))))
return 0;
/*
* If we are in kernel mode at this point, we have no context to
* handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we got
* oom-killed).
*/
pagefault_out_of_memory();
return 0;
}
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to successfully fix up
* this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that isn't in our memory
* map.
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, esr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, esr, regs);
return 0;
}
| 167,584 |
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: iakerb_gss_accept_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_cred_id_t verifier_cred_handle,
gss_buffer_t input_token,
gss_channel_bindings_t input_chan_bindings,
gss_name_t *src_name,
gss_OID *mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec,
gss_cred_id_t *delegated_cred_handle)
{
OM_uint32 major_status = GSS_S_FAILURE;
OM_uint32 code;
iakerb_ctx_id_t ctx;
int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);
if (initialContextToken) {
code = iakerb_alloc_context(&ctx);
if (code != 0)
goto cleanup;
} else
ctx = (iakerb_ctx_id_t)*context_handle;
if (iakerb_is_iakerb_token(input_token)) {
if (ctx->gssc != GSS_C_NO_CONTEXT) {
/* We shouldn't get an IAKERB token now. */
code = G_WRONG_TOKID;
major_status = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
code = iakerb_acceptor_step(ctx, initialContextToken,
input_token, output_token);
if (code == (OM_uint32)KRB5_BAD_MSIZE)
major_status = GSS_S_DEFECTIVE_TOKEN;
if (code != 0)
goto cleanup;
if (initialContextToken) {
*context_handle = (gss_ctx_id_t)ctx;
ctx = NULL;
}
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_iakerb;
if (ret_flags != NULL)
*ret_flags = 0;
if (time_rec != NULL)
*time_rec = 0;
if (delegated_cred_handle != NULL)
*delegated_cred_handle = GSS_C_NO_CREDENTIAL;
major_status = GSS_S_CONTINUE_NEEDED;
} else {
krb5_gss_ctx_ext_rec exts;
iakerb_make_exts(ctx, &exts);
major_status = krb5_gss_accept_sec_context_ext(&code,
&ctx->gssc,
verifier_cred_handle,
input_token,
input_chan_bindings,
src_name,
NULL,
output_token,
ret_flags,
time_rec,
delegated_cred_handle,
&exts);
if (major_status == GSS_S_COMPLETE) {
*context_handle = ctx->gssc;
ctx->gssc = NULL;
iakerb_release_context(ctx);
}
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_krb5;
}
cleanup:
if (initialContextToken && GSS_ERROR(major_status)) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
*minor_status = code;
return major_status;
}
Commit Message: Fix IAKERB context aliasing bugs [CVE-2015-2696]
The IAKERB mechanism currently replaces its context handle with the
krb5 mechanism handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the IAKERB context structure after context
establishment and add new IAKERB entry points to refer to it with that
type. Add initiate and established flags to the IAKERB context
structure for use in gss_inquire_context() prior to context
establishment.
CVE-2015-2696:
In MIT krb5 1.9 and later, applications which call
gss_inquire_context() on a partially-established IAKERB context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. Java server applications using the
native JGSS provider are vulnerable to this bug. A carefully crafted
IAKERB packet might allow the gss_inquire_context() call to succeed
with attacker-determined results, but applications should not make
access control decisions based on gss_inquire_context() results prior
to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | iakerb_gss_accept_sec_context(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_cred_id_t verifier_cred_handle,
gss_buffer_t input_token,
gss_channel_bindings_t input_chan_bindings,
gss_name_t *src_name,
gss_OID *mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec,
gss_cred_id_t *delegated_cred_handle)
{
OM_uint32 major_status = GSS_S_FAILURE;
OM_uint32 code;
iakerb_ctx_id_t ctx;
int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);
if (initialContextToken) {
code = iakerb_alloc_context(&ctx, 0);
if (code != 0)
goto cleanup;
} else
ctx = (iakerb_ctx_id_t)*context_handle;
if (iakerb_is_iakerb_token(input_token)) {
if (ctx->gssc != GSS_C_NO_CONTEXT) {
/* We shouldn't get an IAKERB token now. */
code = G_WRONG_TOKID;
major_status = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
code = iakerb_acceptor_step(ctx, initialContextToken,
input_token, output_token);
if (code == (OM_uint32)KRB5_BAD_MSIZE)
major_status = GSS_S_DEFECTIVE_TOKEN;
if (code != 0)
goto cleanup;
if (initialContextToken) {
*context_handle = (gss_ctx_id_t)ctx;
ctx = NULL;
}
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_iakerb;
if (ret_flags != NULL)
*ret_flags = 0;
if (time_rec != NULL)
*time_rec = 0;
if (delegated_cred_handle != NULL)
*delegated_cred_handle = GSS_C_NO_CREDENTIAL;
major_status = GSS_S_CONTINUE_NEEDED;
} else {
krb5_gss_ctx_ext_rec exts;
iakerb_make_exts(ctx, &exts);
major_status = krb5_gss_accept_sec_context_ext(&code,
&ctx->gssc,
verifier_cred_handle,
input_token,
input_chan_bindings,
src_name,
NULL,
output_token,
ret_flags,
time_rec,
delegated_cred_handle,
&exts);
if (major_status == GSS_S_COMPLETE)
ctx->established = 1;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_krb5;
}
cleanup:
if (initialContextToken && GSS_ERROR(major_status)) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
*minor_status = code;
return major_status;
}
| 166,644 |
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: TestFlashMessageLoop::TestFlashMessageLoop(TestingInstance* instance)
: TestCase(instance),
message_loop_(NULL),
callback_factory_(this) {
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264 | TestFlashMessageLoop::TestFlashMessageLoop(TestingInstance* instance)
: TestCase(instance),
| 172,127 |
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 GpuChannelHost::Connect(
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle client_process_for_gpu) {
DCHECK(factory_->IsMainThread());
scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
channel_.reset(new IPC::SyncChannel(
channel_handle, IPC::Channel::MODE_CLIENT, NULL,
io_loop, true,
factory_->GetShutDownEvent()));
sync_filter_ = new IPC::SyncMessageFilter(
factory_->GetShutDownEvent());
channel_->AddFilter(sync_filter_.get());
channel_filter_ = new MessageFilter(this);
channel_->AddFilter(channel_filter_.get());
state_ = kConnected;
Send(new GpuChannelMsg_Initialize(client_process_for_gpu));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuChannelHost::Connect(
const IPC::ChannelHandle& channel_handle) {
DCHECK(factory_->IsMainThread());
scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
channel_.reset(new IPC::SyncChannel(
channel_handle, IPC::Channel::MODE_CLIENT, NULL,
io_loop, true,
factory_->GetShutDownEvent()));
sync_filter_ = new IPC::SyncMessageFilter(
factory_->GetShutDownEvent());
channel_->AddFilter(sync_filter_.get());
channel_filter_ = new MessageFilter(this);
channel_->AddFilter(channel_filter_.get());
state_ = kConnected;
}
| 170,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
Commit Message: crypto: algif - suppress sending source address information in recvmsg
The current code does not set the msg_namelen member to 0 and therefore
makes net/socket.c leak the local sockaddr_storage variable to userland
-- 128 bytes of kernel stack memory. Fix that.
Cc: <[email protected]> # 2.6.38
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-200 | static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
msg->msg_namelen = 0;
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
| 166,047 |
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 BrowserEventRouter::TabUpdated(WebContents* contents, bool did_navigate) {
TabEntry* entry = GetTabEntry(contents);
DictionaryValue* changed_properties = NULL;
DCHECK(entry);
if (did_navigate)
changed_properties = entry->DidNavigate(contents);
else
changed_properties = entry->UpdateLoadState(contents);
if (changed_properties)
DispatchTabUpdatedEvent(contents, changed_properties);
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void BrowserEventRouter::TabUpdated(WebContents* contents, bool did_navigate) {
TabEntry* entry = GetTabEntry(contents);
scoped_ptr<DictionaryValue> changed_properties;
DCHECK(entry);
if (did_navigate)
changed_properties.reset(entry->DidNavigate(contents));
else
changed_properties.reset(entry->UpdateLoadState(contents));
if (changed_properties)
DispatchTabUpdatedEvent(contents, changed_properties.Pass());
}
| 171,452 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 16;
fwd_txfm_ref = fht16x16_ref;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
bit_depth_ = GET_PARAM(3);
pitch_ = 16;
fwd_txfm_ref = fht16x16_ref;
inv_txfm_ref = iht16x16_ref;
mask_ = (1 << bit_depth_) - 1;
#if CONFIG_VP9_HIGHBITDEPTH
switch (bit_depth_) {
case VPX_BITS_10:
inv_txfm_ref = iht16x16_10;
break;
case VPX_BITS_12:
inv_txfm_ref = iht16x16_12;
break;
default:
inv_txfm_ref = iht16x16_ref;
break;
}
#else
inv_txfm_ref = iht16x16_ref;
#endif
}
| 174,528 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: FT_Bitmap_Copy( FT_Library library,
const FT_Bitmap *source,
FT_Bitmap *target)
{
FT_Memory memory = library->memory;
FT_Error error = FT_Err_Ok;
FT_Int pitch = source->pitch;
FT_ULong size;
if ( source == target )
return FT_Err_Ok;
if ( source->buffer == NULL )
{
*target = *source;
return FT_Err_Ok;
}
if ( pitch < 0 )
pitch = -pitch;
size = (FT_ULong)( pitch * source->rows );
if ( target->buffer )
{
FT_Int target_pitch = target->pitch;
FT_ULong target_size;
if ( target_pitch < 0 )
target_pitch = -target_pitch;
target_size = (FT_ULong)( target_pitch * target->rows );
if ( target_size != size )
(void)FT_QREALLOC( target->buffer, target_size, size );
}
else
(void)FT_QALLOC( target->buffer, size );
if ( !error )
{
unsigned char *p;
p = target->buffer;
*target = *source;
target->buffer = p;
FT_MEM_COPY( target->buffer, source->buffer, size );
}
return error;
}
Commit Message:
CWE ID: CWE-119 | FT_Bitmap_Copy( FT_Library library,
const FT_Bitmap *source,
FT_Bitmap *target)
{
FT_Memory memory = library->memory;
FT_Error error = FT_Err_Ok;
FT_Int pitch = source->pitch;
FT_ULong size;
if ( source == target )
return FT_Err_Ok;
if ( source->buffer == NULL )
{
*target = *source;
return FT_Err_Ok;
}
if ( pitch < 0 )
pitch = -pitch;
size = (FT_ULong)pitch * source->rows;
if ( target->buffer )
{
FT_Int target_pitch = target->pitch;
FT_ULong target_size;
if ( target_pitch < 0 )
target_pitch = -target_pitch;
target_size = (FT_ULong)target_pitch * target->rows;
if ( target_size != size )
(void)FT_QREALLOC( target->buffer, target_size, size );
}
else
(void)FT_QALLOC( target->buffer, size );
if ( !error )
{
unsigned char *p;
p = target->buffer;
*target = *source;
target->buffer = p;
FT_MEM_COPY( target->buffer, source->buffer, size );
}
return error;
}
| 164,848 |
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 MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length)
{
ALOGV("setDataSource(%d, %" PRId64 ", %" PRId64 ")", fd, offset, length);
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(fd, offset, length))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476 | status_t MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length)
{
ALOGV("setDataSource(%d, %" PRId64 ", %" PRId64 ")", fd, offset, length);
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService> service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(fd, offset, length))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
| 173,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 __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg, u8 cpl, bool in_task_switch)
{
struct desc_struct seg_desc, old_desc;
u8 dpl, rpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
ulong desc_addr;
int ret;
u16 dummy;
u32 base3 = 0;
memset(&seg_desc, 0, sizeof seg_desc);
if (ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor (keep limit etc. for
* unreal mode) */
ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
set_desc_base(&seg_desc, selector << 4);
goto load;
} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
/* VM86 needs a clean new segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = 3;
goto load;
}
rpl = selector & 3;
/* NULL selector is not valid for TR, CS and SS (except for long mode) */
if ((seg == VCPU_SREG_CS
|| (seg == VCPU_SREG_SS
&& (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl))
|| seg == VCPU_SREG_TR)
&& null_selector)
goto exception;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
if (null_selector) /* for NULL selector skip all following checks */
goto load;
ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = in_task_switch ? TS_VECTOR : GP_VECTOR;
/* can't load system descriptor into segment selector */
if (seg <= VCPU_SREG_GS && !seg_desc.s)
goto exception;
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
dpl = seg_desc.dpl;
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* in long-mode d/b must be clear if l is set */
if (seg_desc.d && seg_desc.l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
old_desc = seg_desc;
seg_desc.type |= 2; /* busy */
ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
sizeof(seg_desc), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, selector, &seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,
sizeof(base3), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
}
load:
ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
return X86EMUL_CONTINUE;
exception:
return emulate_exception(ctxt, err_vec, err_code, true);
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg, u8 cpl,
bool in_task_switch,
struct desc_struct *desc)
{
struct desc_struct seg_desc, old_desc;
u8 dpl, rpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
ulong desc_addr;
int ret;
u16 dummy;
u32 base3 = 0;
memset(&seg_desc, 0, sizeof seg_desc);
if (ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor (keep limit etc. for
* unreal mode) */
ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
set_desc_base(&seg_desc, selector << 4);
goto load;
} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
/* VM86 needs a clean new segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = 3;
goto load;
}
rpl = selector & 3;
/* NULL selector is not valid for TR, CS and SS (except for long mode) */
if ((seg == VCPU_SREG_CS
|| (seg == VCPU_SREG_SS
&& (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl))
|| seg == VCPU_SREG_TR)
&& null_selector)
goto exception;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
if (null_selector) /* for NULL selector skip all following checks */
goto load;
ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = in_task_switch ? TS_VECTOR : GP_VECTOR;
/* can't load system descriptor into segment selector */
if (seg <= VCPU_SREG_GS && !seg_desc.s)
goto exception;
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
dpl = seg_desc.dpl;
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* in long-mode d/b must be clear if l is set */
if (seg_desc.d && seg_desc.l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
old_desc = seg_desc;
seg_desc.type |= 2; /* busy */
ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
sizeof(seg_desc), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, selector, &seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,
sizeof(base3), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
}
load:
ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
if (desc)
*desc = seg_desc;
return X86EMUL_CONTINUE;
exception:
return emulate_exception(ctxt, err_vec, err_code, true);
}
| 166,337 |
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 GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0));
RenderWidgetHostViewPort* view =
GetRenderWidgetHostViewFromSurfaceID(params.surface_id);
if (!view)
return;
delayed_send.Cancel();
view->AcceleratedSurfacePostSubBuffer(params, host_id_);
}
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 GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BufferPresented(params.route_id,
params.surface_handle,
0));
RenderWidgetHostViewPort* view =
GetRenderWidgetHostViewFromSurfaceID(params.surface_id);
if (!view)
return;
delayed_send.Cancel();
view->AcceleratedSurfacePostSubBuffer(params, host_id_);
}
| 171,359 |
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 *gdImageJpegPtr (gdImagePtr im, int *size, int quality)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
gdImageJpegCtx (im, out, quality);
rv = gdDPExtractData (out, size);
out->gd_free (out);
return rv;
}
Commit Message: Sync with upstream
Even though libgd/libgd#492 is not a relevant bug fix for PHP, since
the binding doesn't use the `gdImage*Ptr()` functions at all, we're
porting the fix to stay in sync here.
CWE ID: CWE-415 | void *gdImageJpegPtr (gdImagePtr im, int *size, int quality)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
if (!_gdImageJpegCtx(im, out, quality)) {
rv = gdDPExtractData(out, size);
} else {
rv = NULL;
}
out->gd_free (out);
return rv;
}
| 169,736 |
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 IPCThreadState::executeCommand(int32_t cmd)
{
BBinder* obj;
RefBase::weakref_type* refs;
status_t result = NO_ERROR;
switch ((uint32_t)cmd) {
case BR_ERROR:
result = mIn.readInt32();
break;
case BR_OK:
break;
case BR_ACQUIRE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
ALOG_ASSERT(refs->refBase() == obj,
"BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
obj->incStrong(mProcess.get());
IF_LOG_REMOTEREFS() {
LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
obj->printRefs();
}
mOut.writeInt32(BC_ACQUIRE_DONE);
mOut.writePointer((uintptr_t)refs);
mOut.writePointer((uintptr_t)obj);
break;
case BR_RELEASE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
ALOG_ASSERT(refs->refBase() == obj,
"BR_RELEASE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
IF_LOG_REMOTEREFS() {
LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
obj->printRefs();
}
mPendingStrongDerefs.push(obj);
break;
case BR_INCREFS:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
refs->incWeak(mProcess.get());
mOut.writeInt32(BC_INCREFS_DONE);
mOut.writePointer((uintptr_t)refs);
mOut.writePointer((uintptr_t)obj);
break;
case BR_DECREFS:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
mPendingWeakDerefs.push(refs);
break;
case BR_ATTEMPT_ACQUIRE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
{
const bool success = refs->attemptIncStrong(mProcess.get());
ALOG_ASSERT(success && refs->refBase() == obj,
"BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
mOut.writeInt32(BC_ACQUIRE_RESULT);
mOut.writeInt32((int32_t)success);
}
break;
case BR_TRANSACTION:
{
binder_transaction_data tr;
result = mIn.read(&tr, sizeof(tr));
ALOG_ASSERT(result == NO_ERROR,
"Not enough command data for brTRANSACTION");
if (result != NO_ERROR) break;
Parcel buffer;
buffer.ipcSetDataReference(
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
const pid_t origPid = mCallingPid;
const uid_t origUid = mCallingUid;
const int32_t origStrictModePolicy = mStrictModePolicy;
const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
mCallingPid = tr.sender_pid;
mCallingUid = tr.sender_euid;
mLastTransactionBinderFlags = tr.flags;
int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
if (gDisableBackgroundScheduling) {
if (curPrio > ANDROID_PRIORITY_NORMAL) {
setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
}
} else {
if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
set_sched_policy(mMyThreadId, SP_BACKGROUND);
}
}
Parcel reply;
status_t error;
IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BR_TRANSACTION thr " << (void*)pthread_self()
<< " / obj " << tr.target.ptr << " / code "
<< TypeCode(tr.code) << ": " << indent << buffer
<< dedent << endl
<< "Data addr = "
<< reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
<< ", offsets addr="
<< reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
}
if (tr.target.ptr) {
sp<BBinder> b((BBinder*)tr.cookie);
error = b->transact(tr.code, buffer, &reply, tr.flags);
} else {
error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
}
if ((tr.flags & TF_ONE_WAY) == 0) {
LOG_ONEWAY("Sending reply to %d!", mCallingPid);
if (error < NO_ERROR) reply.setError(error);
sendReply(reply, 0);
} else {
LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
}
mCallingPid = origPid;
mCallingUid = origUid;
mStrictModePolicy = origStrictModePolicy;
mLastTransactionBinderFlags = origTransactionBinderFlags;
IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
<< tr.target.ptr << ": " << indent << reply << dedent << endl;
}
}
break;
case BR_DEAD_BINDER:
{
BpBinder *proxy = (BpBinder*)mIn.readPointer();
proxy->sendObituary();
mOut.writeInt32(BC_DEAD_BINDER_DONE);
mOut.writePointer((uintptr_t)proxy);
} break;
case BR_CLEAR_DEATH_NOTIFICATION_DONE:
{
BpBinder *proxy = (BpBinder*)mIn.readPointer();
proxy->getWeakRefs()->decWeak(proxy);
} break;
case BR_FINISHED:
result = TIMED_OUT;
break;
case BR_NOOP:
break;
case BR_SPAWN_LOOPER:
mProcess->spawnPooledThread(false);
break;
default:
printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
result = UNKNOWN_ERROR;
break;
}
if (result != NO_ERROR) {
mLastError = result;
}
return result;
}
Commit Message: Fix issue #27252896: Security Vulnerability -- weak binder
Sending transaction to freed BBinder through weak handle
can cause use of a (mostly) freed object. We need to try to
safely promote to a strong reference first.
Change-Id: Ic9c6940fa824980472e94ed2dfeca52a6b0fd342
(cherry picked from commit c11146106f94e07016e8e26e4f8628f9a0c73199)
CWE ID: CWE-264 | status_t IPCThreadState::executeCommand(int32_t cmd)
{
BBinder* obj;
RefBase::weakref_type* refs;
status_t result = NO_ERROR;
switch ((uint32_t)cmd) {
case BR_ERROR:
result = mIn.readInt32();
break;
case BR_OK:
break;
case BR_ACQUIRE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
ALOG_ASSERT(refs->refBase() == obj,
"BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
obj->incStrong(mProcess.get());
IF_LOG_REMOTEREFS() {
LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
obj->printRefs();
}
mOut.writeInt32(BC_ACQUIRE_DONE);
mOut.writePointer((uintptr_t)refs);
mOut.writePointer((uintptr_t)obj);
break;
case BR_RELEASE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
ALOG_ASSERT(refs->refBase() == obj,
"BR_RELEASE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
IF_LOG_REMOTEREFS() {
LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
obj->printRefs();
}
mPendingStrongDerefs.push(obj);
break;
case BR_INCREFS:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
refs->incWeak(mProcess.get());
mOut.writeInt32(BC_INCREFS_DONE);
mOut.writePointer((uintptr_t)refs);
mOut.writePointer((uintptr_t)obj);
break;
case BR_DECREFS:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
mPendingWeakDerefs.push(refs);
break;
case BR_ATTEMPT_ACQUIRE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
{
const bool success = refs->attemptIncStrong(mProcess.get());
ALOG_ASSERT(success && refs->refBase() == obj,
"BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
mOut.writeInt32(BC_ACQUIRE_RESULT);
mOut.writeInt32((int32_t)success);
}
break;
case BR_TRANSACTION:
{
binder_transaction_data tr;
result = mIn.read(&tr, sizeof(tr));
ALOG_ASSERT(result == NO_ERROR,
"Not enough command data for brTRANSACTION");
if (result != NO_ERROR) break;
Parcel buffer;
buffer.ipcSetDataReference(
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
const pid_t origPid = mCallingPid;
const uid_t origUid = mCallingUid;
const int32_t origStrictModePolicy = mStrictModePolicy;
const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
mCallingPid = tr.sender_pid;
mCallingUid = tr.sender_euid;
mLastTransactionBinderFlags = tr.flags;
int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
if (gDisableBackgroundScheduling) {
if (curPrio > ANDROID_PRIORITY_NORMAL) {
setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
}
} else {
if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
set_sched_policy(mMyThreadId, SP_BACKGROUND);
}
}
Parcel reply;
status_t error;
IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BR_TRANSACTION thr " << (void*)pthread_self()
<< " / obj " << tr.target.ptr << " / code "
<< TypeCode(tr.code) << ": " << indent << buffer
<< dedent << endl
<< "Data addr = "
<< reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
<< ", offsets addr="
<< reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
}
if (tr.target.ptr) {
// We only have a weak reference on the target object, so we must first try to
// safely acquire a strong reference before doing anything else with it.
if (reinterpret_cast<RefBase::weakref_type*>(
tr.target.ptr)->attemptIncStrong(this)) {
error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
&reply, tr.flags);
reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
} else {
error = UNKNOWN_TRANSACTION;
}
} else {
error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
}
if ((tr.flags & TF_ONE_WAY) == 0) {
LOG_ONEWAY("Sending reply to %d!", mCallingPid);
if (error < NO_ERROR) reply.setError(error);
sendReply(reply, 0);
} else {
LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
}
mCallingPid = origPid;
mCallingUid = origUid;
mStrictModePolicy = origStrictModePolicy;
mLastTransactionBinderFlags = origTransactionBinderFlags;
IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
<< tr.target.ptr << ": " << indent << reply << dedent << endl;
}
}
break;
case BR_DEAD_BINDER:
{
BpBinder *proxy = (BpBinder*)mIn.readPointer();
proxy->sendObituary();
mOut.writeInt32(BC_DEAD_BINDER_DONE);
mOut.writePointer((uintptr_t)proxy);
} break;
case BR_CLEAR_DEATH_NOTIFICATION_DONE:
{
BpBinder *proxy = (BpBinder*)mIn.readPointer();
proxy->getWeakRefs()->decWeak(proxy);
} break;
case BR_FINISHED:
result = TIMED_OUT;
break;
case BR_NOOP:
break;
case BR_SPAWN_LOOPER:
mProcess->spawnPooledThread(false);
break;
default:
printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
result = UNKNOWN_ERROR;
break;
}
if (result != NO_ERROR) {
mLastError = result;
}
return result;
}
| 173,885 |
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 BrowserMainLoop::PreCreateThreads() {
if (parts_) {
TRACE_EVENT0("startup",
"BrowserMainLoop::CreateThreads:PreCreateThreads");
result_code_ = parts_->PreCreateThreads();
}
if (!base::SequencedWorkerPool::IsEnabled())
base::SequencedWorkerPool::EnableForProcess();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
base::FeatureList::InitializeInstance(
command_line->GetSwitchValueASCII(switches::kEnableFeatures),
command_line->GetSwitchValueASCII(switches::kDisableFeatures));
InitializeMemoryManagementComponent();
#if defined(OS_MACOSX)
if (base::CommandLine::InitializedForCurrentProcess() &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableHeapProfiling)) {
base::allocator::PeriodicallyShimNewMallocZones();
}
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
{
TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
PluginService::GetInstance()->Init();
}
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
CdmRegistry::GetInstance()->Init();
#endif
#if defined(OS_MACOSX)
ui::WindowResizeHelperMac::Get()->Init(base::ThreadTaskRunnerHandle::Get());
#endif
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
#if defined(USE_X11)
gpu_data_manager_visual_proxy_.reset(
new internal::GpuDataManagerVisualProxy(gpu_data_manager));
#endif
gpu_data_manager->Initialize();
#if !defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID)
if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
RenderProcessHost::SetRunRendererInProcess(true);
#endif
std::vector<url::Origin> origins =
GetContentClient()->browser()->GetOriginsRequiringDedicatedProcess();
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
for (auto origin : origins)
policy->AddIsolatedOrigin(origin);
EVP_set_buggy_rsa_parser(
base::FeatureList::IsEnabled(features::kBuggyRSAParser));
return result_code_;
}
Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6
https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604
BUG=778101
Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c
Reviewed-on: https://chromium-review.googlesource.com/747941
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: David Benjamin <[email protected]>
Commit-Queue: Steven Valdez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513774}
CWE ID: CWE-310 | int BrowserMainLoop::PreCreateThreads() {
if (parts_) {
TRACE_EVENT0("startup",
"BrowserMainLoop::CreateThreads:PreCreateThreads");
result_code_ = parts_->PreCreateThreads();
}
if (!base::SequencedWorkerPool::IsEnabled())
base::SequencedWorkerPool::EnableForProcess();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
base::FeatureList::InitializeInstance(
command_line->GetSwitchValueASCII(switches::kEnableFeatures),
command_line->GetSwitchValueASCII(switches::kDisableFeatures));
InitializeMemoryManagementComponent();
#if defined(OS_MACOSX)
if (base::CommandLine::InitializedForCurrentProcess() &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableHeapProfiling)) {
base::allocator::PeriodicallyShimNewMallocZones();
}
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
{
TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
PluginService::GetInstance()->Init();
}
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
CdmRegistry::GetInstance()->Init();
#endif
#if defined(OS_MACOSX)
ui::WindowResizeHelperMac::Get()->Init(base::ThreadTaskRunnerHandle::Get());
#endif
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
#if defined(USE_X11)
gpu_data_manager_visual_proxy_.reset(
new internal::GpuDataManagerVisualProxy(gpu_data_manager));
#endif
gpu_data_manager->Initialize();
#if !defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID)
if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
RenderProcessHost::SetRunRendererInProcess(true);
#endif
std::vector<url::Origin> origins =
GetContentClient()->browser()->GetOriginsRequiringDedicatedProcess();
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
for (auto origin : origins)
policy->AddIsolatedOrigin(origin);
return result_code_;
}
| 172,933 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: char *enl_ipc_get(const char *msg_data)
{
static char *message = NULL;
static unsigned short len = 0;
char buff[13], *ret_msg = NULL;
register unsigned char i;
unsigned char blen;
if (msg_data == IPC_TIMEOUT) {
return(IPC_TIMEOUT);
}
for (i = 0; i < 12; i++) {
buff[i] = msg_data[i];
}
buff[12] = 0;
blen = strlen(buff);
if (message != NULL) {
len += blen;
message = (char *) erealloc(message, len + 1);
strcat(message, buff);
} else {
len = blen;
message = (char *) emalloc(len + 1);
strcpy(message, buff);
}
if (blen < 12) {
ret_msg = message;
message = NULL;
D(("Received complete reply: \"%s\"\n", ret_msg));
}
return(ret_msg);
}
Commit Message: Fix double-free/OOB-write while receiving IPC data
If a malicious client pretends to be the E17 window manager, it is
possible to trigger an out of boundary heap write while receiving an
IPC message.
The length of the already received message is stored in an unsigned
short, which overflows after receiving 64 KB of data. It's comparably
small amount of data and therefore achievable for an attacker.
When len overflows, realloc() will either be called with a small value
and therefore chars will be appended out of bounds, or len + 1 will be
exactly 0, in which case realloc() behaves like free(). This could be
abused for a later double-free attack as it's even possible to overwrite
the free information -- but this depends on the malloc implementation.
Signed-off-by: Tobias Stoeckmann <[email protected]>
CWE ID: CWE-787 | char *enl_ipc_get(const char *msg_data)
{
static char *message = NULL;
static size_t len = 0;
char buff[13], *ret_msg = NULL;
register unsigned char i;
unsigned char blen;
if (msg_data == IPC_TIMEOUT) {
return(IPC_TIMEOUT);
}
for (i = 0; i < 12; i++) {
buff[i] = msg_data[i];
}
buff[12] = 0;
blen = strlen(buff);
if (message != NULL) {
len += blen;
message = (char *) erealloc(message, len + 1);
strcat(message, buff);
} else {
len = blen;
message = (char *) emalloc(len + 1);
strcpy(message, buff);
}
if (blen < 12) {
ret_msg = message;
message = NULL;
D(("Received complete reply: \"%s\"\n", ret_msg));
}
return(ret_msg);
}
| 168,244 |
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_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
Commit Message: bpf: force strict alignment checks for stack pointers
Force strict alignment checks for stack pointers because the tracking of
stack spills relies on it; unaligned stack accesses can lead to corruption
of spilled registers, which is exploitable.
Fixes: f1174f77b50c ("bpf/verifier: rework value tracking")
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-119 | static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
/* The stack spill tracking logic in check_stack_write()
* and check_stack_read() relies on stack accesses being
* aligned.
*/
strict = true;
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
| 167,641 |
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 nlmclnt_unlock_callback(struct rpc_task *task, void *data)
{
struct nlm_rqst *req = data;
u32 status = ntohl(req->a_res.status);
if (RPC_ASSASSINATED(task))
goto die;
if (task->tk_status < 0) {
dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status);
goto retry_rebind;
}
if (status == NLM_LCK_DENIED_GRACE_PERIOD) {
rpc_delay(task, NLMCLNT_GRACE_WAIT);
goto retry_unlock;
}
if (status != NLM_LCK_GRANTED)
printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status);
die:
return;
retry_rebind:
nlm_rebind_host(req->a_host);
retry_unlock:
rpc_restart_call(task);
}
Commit Message: NLM: Don't hang forever on NLM unlock requests
If the NLM daemon is killed on the NFS server, we can currently end up
hanging forever on an 'unlock' request, instead of aborting. Basically,
if the rpcbind request fails, or the server keeps returning garbage, we
really want to quit instead of retrying.
Tested-by: Vasily Averin <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
Cc: [email protected]
CWE ID: CWE-399 | static void nlmclnt_unlock_callback(struct rpc_task *task, void *data)
{
struct nlm_rqst *req = data;
u32 status = ntohl(req->a_res.status);
if (RPC_ASSASSINATED(task))
goto die;
if (task->tk_status < 0) {
dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status);
switch (task->tk_status) {
case -EACCES:
case -EIO:
goto die;
default:
goto retry_rebind;
}
}
if (status == NLM_LCK_DENIED_GRACE_PERIOD) {
rpc_delay(task, NLMCLNT_GRACE_WAIT);
goto retry_unlock;
}
if (status != NLM_LCK_GRANTED)
printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status);
die:
return;
retry_rebind:
nlm_rebind_host(req->a_host);
retry_unlock:
rpc_restart_call(task);
}
| 166,221 |
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: bit_in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarBit *result; /* The resulting bit string */
char *sp; /* pointer into the character string */
bits8 *r; /* pointer into the result */
int len, /* Length of the whole data structure */
bitlen, /* Number of bits in the bit string */
slen; /* Length of the input string */
bool bit_not_hex; /* false = hex string true = bit string */
int bc;
bits8 x = 0;
/* Check that the first character is a b or an x */
if (input_string[0] == 'b' || input_string[0] == 'B')
{
bit_not_hex = true;
sp = input_string + 1;
}
else if (input_string[0] == 'x' || input_string[0] == 'X')
{
bit_not_hex = false;
sp = input_string + 1;
}
else
{
/*
* Otherwise it's binary. This allows things like cast('1001' as bit)
* to work transparently.
*/
bit_not_hex = true;
sp = input_string;
}
slen = strlen(sp);
/* Determine bitlength from input string */
if (bit_not_hex)
bitlen = slen;
else
bitlen = slen * 4;
/*
* Sometimes atttypmod is not supplied. If it is supplied we need to make
* sure that the bitstring fits.
*/
if (atttypmod <= 0)
atttypmod = bitlen;
else if (bitlen != atttypmod)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
errmsg("bit string length %d does not match type bit(%d)",
bitlen, atttypmod)));
len = VARBITTOTALLEN(atttypmod);
/* set to 0 so that *r is always initialised and string is zero-padded */
result = (VarBit *) palloc0(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = atttypmod;
r = VARBITS(result);
if (bit_not_hex)
{
/* Parse the bit representation of the string */
/* We know it fits, as bitlen was compared to atttypmod */
x = HIGHBIT;
for (; *sp; sp++)
{
if (*sp == '1')
*r |= x;
else if (*sp != '0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid binary digit",
*sp)));
x >>= 1;
if (x == 0)
{
x = HIGHBIT;
r++;
}
}
}
else
{
/* Parse the hex representation of the string */
for (bc = 0; *sp; sp++)
{
if (*sp >= '0' && *sp <= '9')
x = (bits8) (*sp - '0');
else if (*sp >= 'A' && *sp <= 'F')
x = (bits8) (*sp - 'A') + 10;
else if (*sp >= 'a' && *sp <= 'f')
x = (bits8) (*sp - 'a') + 10;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid hexadecimal digit",
*sp)));
if (bc)
{
*r++ |= x;
bc = 0;
}
else
{
*r = x << 4;
bc = 1;
}
}
}
PG_RETURN_VARBIT_P(result);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | bit_in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarBit *result; /* The resulting bit string */
char *sp; /* pointer into the character string */
bits8 *r; /* pointer into the result */
int len, /* Length of the whole data structure */
bitlen, /* Number of bits in the bit string */
slen; /* Length of the input string */
bool bit_not_hex; /* false = hex string true = bit string */
int bc;
bits8 x = 0;
/* Check that the first character is a b or an x */
if (input_string[0] == 'b' || input_string[0] == 'B')
{
bit_not_hex = true;
sp = input_string + 1;
}
else if (input_string[0] == 'x' || input_string[0] == 'X')
{
bit_not_hex = false;
sp = input_string + 1;
}
else
{
/*
* Otherwise it's binary. This allows things like cast('1001' as bit)
* to work transparently.
*/
bit_not_hex = true;
sp = input_string;
}
/*
* Determine bitlength from input string. MaxAllocSize ensures a regular
* input is small enough, but we must check hex input.
*/
slen = strlen(sp);
if (bit_not_hex)
bitlen = slen;
else
{
if (slen > VARBITMAXLEN / 4)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("bit string length exceeds the maximum allowed (%d)",
VARBITMAXLEN)));
bitlen = slen * 4;
}
/*
* Sometimes atttypmod is not supplied. If it is supplied we need to make
* sure that the bitstring fits.
*/
if (atttypmod <= 0)
atttypmod = bitlen;
else if (bitlen != atttypmod)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
errmsg("bit string length %d does not match type bit(%d)",
bitlen, atttypmod)));
len = VARBITTOTALLEN(atttypmod);
/* set to 0 so that *r is always initialised and string is zero-padded */
result = (VarBit *) palloc0(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = atttypmod;
r = VARBITS(result);
if (bit_not_hex)
{
/* Parse the bit representation of the string */
/* We know it fits, as bitlen was compared to atttypmod */
x = HIGHBIT;
for (; *sp; sp++)
{
if (*sp == '1')
*r |= x;
else if (*sp != '0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid binary digit",
*sp)));
x >>= 1;
if (x == 0)
{
x = HIGHBIT;
r++;
}
}
}
else
{
/* Parse the hex representation of the string */
for (bc = 0; *sp; sp++)
{
if (*sp >= '0' && *sp <= '9')
x = (bits8) (*sp - '0');
else if (*sp >= 'A' && *sp <= 'F')
x = (bits8) (*sp - 'A') + 10;
else if (*sp >= 'a' && *sp <= 'f')
x = (bits8) (*sp - 'a') + 10;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid hexadecimal digit",
*sp)));
if (bc)
{
*r++ |= x;
bc = 0;
}
else
{
*r = x << 4;
bc = 1;
}
}
}
PG_RETURN_VARBIT_P(result);
}
| 166,418 |
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 __init files_init(unsigned long mempages)
{
unsigned long n;
filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
/*
* One file with associated inode and dcache is very roughly 1K.
* Per default don't use more than 10% of our memory for files.
*/
n = (mempages * (PAGE_SIZE / 1024)) / 10;
files_stat.max_files = max_t(unsigned long, n, NR_FILE);
files_defer_init();
lg_lock_init(&files_lglock, "files_lglock");
percpu_counter_init(&nr_files, 0);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void __init files_init(unsigned long mempages)
{
unsigned long n;
filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
/*
* One file with associated inode and dcache is very roughly 1K.
* Per default don't use more than 10% of our memory for files.
*/
n = (mempages * (PAGE_SIZE / 1024)) / 10;
files_stat.max_files = max_t(unsigned long, n, NR_FILE);
files_defer_init();
percpu_counter_init(&nr_files, 0);
}
| 166,800 |
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: AudioRendererHostTest()
: log_factory(base::MakeUnique<media::FakeAudioLogFactory>()),
audio_manager_(base::MakeUnique<FakeAudioManagerWithAssociations>(
base::ThreadTaskRunnerHandle::Get(),
log_factory.get())),
render_process_host_(&browser_context_, &auth_run_loop_) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
host_ = new MockAudioRendererHost(
&auth_run_loop_, render_process_host_.GetID(), audio_manager_.get(),
&mirroring_manager_, media_stream_manager_.get(), kSalt);
host_->set_peer_process_for_testing(base::Process::Current());
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID: | AudioRendererHostTest()
: log_factory(base::MakeUnique<media::FakeAudioLogFactory>()),
audio_manager_(base::MakeUnique<FakeAudioManagerWithAssociations>(
base::ThreadTaskRunnerHandle::Get(),
log_factory.get())),
audio_system_(media::AudioSystemImpl::Create(audio_manager_.get())),
render_process_host_(&browser_context_, &auth_run_loop_) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
host_ = new MockAudioRendererHost(
&auth_run_loop_, render_process_host_.GetID(), audio_manager_.get(),
audio_system_.get(), &mirroring_manager_, media_stream_manager_.get(),
kSalt);
host_->set_peer_process_for_testing(base::Process::Current());
}
| 171,985 |
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: xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData,
name);
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
ctxt->instate = XML_PARSER_EOF;
return;
}
}
}
}
ctxt->hasPErefs = 1;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
ctxt->instate = XML_PARSER_EOF;
return;
}
}
}
}
ctxt->hasPErefs = 1;
}
| 171,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: int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
const unsigned char *old_name;
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
if (source == target)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename)
return -EPERM;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry, flags);
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
fsnotify_oldname_free(old_name);
return error;
}
Commit Message: dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-362 | int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
struct name_snapshot old_name;
if (source == target)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename)
return -EPERM;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
take_dentry_name_snapshot(&old_name, old_dentry);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry, flags);
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name.name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
release_dentry_name_snapshot(&old_name);
return error;
}
| 168,263 |
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 git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0;
#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }
if (cmd & 0x01) ADD_DELTA(off, 0UL);
if (cmd & 0x02) ADD_DELTA(off, 8UL);
if (cmd & 0x04) ADD_DELTA(off, 16UL);
if (cmd & 0x08) ADD_DELTA(off, 24UL);
if (cmd & 0x10) ADD_DELTA(len, 0UL);
if (cmd & 0x20) ADD_DELTA(len, 8UL);
if (cmd & 0x40) ADD_DELTA(len, 16UL);
if (!len) len = 0x10000;
#undef ADD_DELTA
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
Commit Message: delta: fix overflow when computing limit
When checking whether a delta base offset and length fit into the base
we have in memory already, we can trigger an overflow which breaks the
check. This would subsequently result in us reading memory from out of
bounds of the base.
The issue is easily fixed by checking for overflow when adding `off` and
`len`, thus guaranteeting that we are never indexing beyond `base_len`.
This corresponds to the git patch 8960844a7 (check patch_delta bounds
more carefully, 2006-04-07), which adds these overflow checks.
Reported-by: Riccardo Schirone <[email protected]>
CWE ID: CWE-125 | int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0, end;
#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }
if (cmd & 0x01) ADD_DELTA(off, 0UL);
if (cmd & 0x02) ADD_DELTA(off, 8UL);
if (cmd & 0x04) ADD_DELTA(off, 16UL);
if (cmd & 0x08) ADD_DELTA(off, 24UL);
if (cmd & 0x10) ADD_DELTA(len, 0UL);
if (cmd & 0x20) ADD_DELTA(len, 8UL);
if (cmd & 0x40) ADD_DELTA(len, 16UL);
if (!len) len = 0x10000;
#undef ADD_DELTA
if (GIT_ADD_SIZET_OVERFLOW(&end, off, len) ||
base_len < end || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
| 169,245 |
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 unimac_mdio_probe(struct platform_device *pdev)
{
struct unimac_mdio_pdata *pdata = pdev->dev.platform_data;
struct unimac_mdio_priv *priv;
struct device_node *np;
struct mii_bus *bus;
struct resource *r;
int ret;
np = pdev->dev.of_node;
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
/* Just ioremap, as this MDIO block is usually integrated into an
* Ethernet MAC controller register range
*/
priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!priv->base) {
dev_err(&pdev->dev, "failed to remap register\n");
return -ENOMEM;
}
priv->mii_bus = mdiobus_alloc();
if (!priv->mii_bus)
return -ENOMEM;
bus = priv->mii_bus;
bus->priv = priv;
if (pdata) {
bus->name = pdata->bus_name;
priv->wait_func = pdata->wait_func;
priv->wait_func_data = pdata->wait_func_data;
bus->phy_mask = ~pdata->phy_mask;
} else {
bus->name = "unimac MII bus";
priv->wait_func_data = priv;
priv->wait_func = unimac_mdio_poll;
}
bus->parent = &pdev->dev;
bus->read = unimac_mdio_read;
bus->write = unimac_mdio_write;
bus->reset = unimac_mdio_reset;
snprintf(bus->id, MII_BUS_ID_SIZE, "%s-%d", pdev->name, pdev->id);
ret = of_mdiobus_register(bus, np);
if (ret) {
dev_err(&pdev->dev, "MDIO bus registration failed\n");
goto out_mdio_free;
}
platform_set_drvdata(pdev, priv);
dev_info(&pdev->dev, "Broadcom UniMAC MDIO bus at 0x%p\n", priv->base);
return 0;
out_mdio_free:
mdiobus_free(bus);
return ret;
}
Commit Message: net: phy: mdio-bcm-unimac: fix potential NULL dereference in unimac_mdio_probe()
platform_get_resource() may fail and return NULL, so we should
better check it's return value to avoid a NULL pointer dereference
a bit later in the code.
This is detected by Coccinelle semantic patch.
@@
expression pdev, res, n, t, e, e1, e2;
@@
res = platform_get_resource(pdev, t, n);
+ if (!res)
+ return -EINVAL;
... when != res == NULL
e = devm_ioremap(e1, res->start, e2);
Signed-off-by: Wei Yongjun <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | static int unimac_mdio_probe(struct platform_device *pdev)
{
struct unimac_mdio_pdata *pdata = pdev->dev.platform_data;
struct unimac_mdio_priv *priv;
struct device_node *np;
struct mii_bus *bus;
struct resource *r;
int ret;
np = pdev->dev.of_node;
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r)
return -EINVAL;
/* Just ioremap, as this MDIO block is usually integrated into an
* Ethernet MAC controller register range
*/
priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!priv->base) {
dev_err(&pdev->dev, "failed to remap register\n");
return -ENOMEM;
}
priv->mii_bus = mdiobus_alloc();
if (!priv->mii_bus)
return -ENOMEM;
bus = priv->mii_bus;
bus->priv = priv;
if (pdata) {
bus->name = pdata->bus_name;
priv->wait_func = pdata->wait_func;
priv->wait_func_data = pdata->wait_func_data;
bus->phy_mask = ~pdata->phy_mask;
} else {
bus->name = "unimac MII bus";
priv->wait_func_data = priv;
priv->wait_func = unimac_mdio_poll;
}
bus->parent = &pdev->dev;
bus->read = unimac_mdio_read;
bus->write = unimac_mdio_write;
bus->reset = unimac_mdio_reset;
snprintf(bus->id, MII_BUS_ID_SIZE, "%s-%d", pdev->name, pdev->id);
ret = of_mdiobus_register(bus, np);
if (ret) {
dev_err(&pdev->dev, "MDIO bus registration failed\n");
goto out_mdio_free;
}
platform_set_drvdata(pdev, priv);
dev_info(&pdev->dev, "Broadcom UniMAC MDIO bus at 0x%p\n", priv->base);
return 0;
out_mdio_free:
mdiobus_free(bus);
return ret;
}
| 169,303 |
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 size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) {
ut32 i = 0;
while (buf + i < max && buf[i] != eoc) {
i += 1;
}
if (buf[i] != eoc) {
return 0;
}
if (offset) {
*offset += i + 1;
}
return i + 1;
}
Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr
CWE ID: CWE-125 | static size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) {
ut32 i = 0;
while (buf + i < max && buf[i] != eoc) {
i++;
}
if (buf[i] != eoc) {
return 0;
}
if (offset) {
*offset += i + 1;
}
return i + 1;
}
| 168,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: void ResetPaddingKeyForTesting() {
*GetPaddingKey() = SymmetricKey::GenerateRandomKey(kPaddingKeyAlgorithm, 128);
}
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 ResetPaddingKeyForTesting() {
*GetPaddingKeyInternal() =
SymmetricKey::GenerateRandomKey(kPaddingKeyAlgorithm, 128);
}
| 173,001 |
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: swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
TIFFSwabArrayOfLong(wp, wc);
horAcc32(tif, cp0, cc);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
TIFFSwabArrayOfLong(wp, wc);
return horAcc32(tif, cp0, cc);
}
| 166,889 |
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: krb5_ldap_get_password_policy_from_dn(krb5_context context, char *pol_name,
char *pol_dn, osa_policy_ent_t *policy)
{
krb5_error_code st=0, tempst=0;
LDAP *ld=NULL;
LDAPMessage *result=NULL,*ent=NULL;
kdb5_dal_handle *dal_handle=NULL;
krb5_ldap_context *ldap_context=NULL;
krb5_ldap_server_handle *ldap_server_handle=NULL;
/* Clear the global error string */
krb5_clear_error_message(context);
/* validate the input parameters */
if (pol_dn == NULL)
return EINVAL;
*policy = NULL;
SETUP_CONTEXT();
GET_HANDLE();
*(policy) = (osa_policy_ent_t) malloc(sizeof(osa_policy_ent_rec));
if (*policy == NULL) {
st = ENOMEM;
goto cleanup;
}
memset(*policy, 0, sizeof(osa_policy_ent_rec));
LDAP_SEARCH(pol_dn, LDAP_SCOPE_BASE, "(objectclass=krbPwdPolicy)", password_policy_attributes);
ent=ldap_first_entry(ld, result);
if (ent != NULL) {
if ((st = populate_policy(context, ld, ent, pol_name, *policy)) != 0)
goto cleanup;
}
cleanup:
ldap_msgfree(result);
if (st != 0) {
if (*policy != NULL) {
krb5_ldap_free_password_policy(context, *policy);
*policy = NULL;
}
}
krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle);
return st;
}
Commit Message: Fix LDAP misused policy name crash [CVE-2014-5353]
In krb5_ldap_get_password_policy_from_dn, if LDAP_SEARCH returns
successfully with no results, return KRB5_KDB_NOENTRY instead of
returning success with a zeroed-out policy object. This fixes a null
dereference when an admin attempts to use an LDAP ticket policy name
as a password policy name.
CVE-2014-5353:
In MIT krb5, when kadmind is configured to use LDAP for the KDC
database, an authenticated remote attacker can cause a NULL dereference
by attempting to use a named ticket policy object as a password policy
for a principal. The attacker needs to be authenticated as a user who
has the elevated privilege for setting password policy by adding or
modifying principals.
Queries to LDAP scoped to the krbPwdPolicy object class will correctly
not return entries of other classes, such as ticket policy objects, but
may return success with no returned elements if an object with the
requested DN exists in a different object class. In this case, the
routine to retrieve a password policy returned success with a password
policy object that consisted entirely of zeroed memory. In particular,
accesses to the policy name will dereference a NULL pointer. KDC
operation does not access the policy name field, but most kadmin
operations involving the principal with incorrect password policy
will trigger the crash.
Thanks to Patrik Kis for reporting this problem.
CVSSv2 Vector: AV:N/AC:M/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:C
[[email protected]: CVE description and CVSS score]
ticket: 8051 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | krb5_ldap_get_password_policy_from_dn(krb5_context context, char *pol_name,
char *pol_dn, osa_policy_ent_t *policy)
{
krb5_error_code st=0, tempst=0;
LDAP *ld=NULL;
LDAPMessage *result=NULL,*ent=NULL;
kdb5_dal_handle *dal_handle=NULL;
krb5_ldap_context *ldap_context=NULL;
krb5_ldap_server_handle *ldap_server_handle=NULL;
/* Clear the global error string */
krb5_clear_error_message(context);
/* validate the input parameters */
if (pol_dn == NULL)
return EINVAL;
*policy = NULL;
SETUP_CONTEXT();
GET_HANDLE();
*(policy) = (osa_policy_ent_t) malloc(sizeof(osa_policy_ent_rec));
if (*policy == NULL) {
st = ENOMEM;
goto cleanup;
}
memset(*policy, 0, sizeof(osa_policy_ent_rec));
LDAP_SEARCH(pol_dn, LDAP_SCOPE_BASE, "(objectclass=krbPwdPolicy)", password_policy_attributes);
ent=ldap_first_entry(ld, result);
if (ent == NULL) {
st = KRB5_KDB_NOENTRY;
goto cleanup;
}
st = populate_policy(context, ld, ent, pol_name, *policy);
cleanup:
ldap_msgfree(result);
if (st != 0) {
if (*policy != NULL) {
krb5_ldap_free_password_policy(context, *policy);
*policy = NULL;
}
}
krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle);
return st;
}
| 166,274 |
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 iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb)
{
int error = 0;
struct cxio_rdev *rdev;
rdev = (struct cxio_rdev *)tdev->ulp;
if (cxio_fatal_error(rdev)) {
kfree_skb(skb);
return -EIO;
}
error = cxgb3_ofld_send(tdev, skb);
if (error < 0)
kfree_skb(skb);
return error;
}
Commit Message: iw_cxgb3: Fix incorrectly returning error on success
The cxgb3_*_send() functions return NET_XMIT_ values, which are
positive integers values. So don't treat positive return values
as an error.
Signed-off-by: Steve Wise <[email protected]>
Signed-off-by: Hariprasad Shenai <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: | int iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb)
{
int error = 0;
struct cxio_rdev *rdev;
rdev = (struct cxio_rdev *)tdev->ulp;
if (cxio_fatal_error(rdev)) {
kfree_skb(skb);
return -EIO;
}
error = cxgb3_ofld_send(tdev, skb);
if (error < 0)
kfree_skb(skb);
return error < 0 ? error : 0;
}
| 167,495 |
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 ixheaacd_esbr_postradixcompute2(WORD32 *ptr_y, WORD32 *ptr_x,
const WORD32 *pdig_rev_tbl,
WORD32 npoints) {
WORD32 i, k;
WORD32 h2;
WORD32 x_0, x_1, x_2, x_3;
WORD32 x_4, x_5, x_6, x_7;
WORD32 x_8, x_9, x_a, x_b, x_c, x_d, x_e, x_f;
WORD32 n00, n10, n20, n30, n01, n11, n21, n31;
WORD32 n02, n12, n22, n32, n03, n13, n23, n33;
WORD32 n0, j0;
WORD32 *x2, *x0;
WORD32 *y0, *y1, *y2, *y3;
y0 = ptr_y;
y2 = ptr_y + (WORD32)npoints;
x0 = ptr_x;
x2 = ptr_x + (WORD32)(npoints >> 1);
y1 = y0 + (WORD32)(npoints >> 2);
y3 = y2 + (WORD32)(npoints >> 2);
j0 = 8;
n0 = npoints >> 1;
for (k = 0; k < 2; k++) {
for (i = 0; i<npoints>> 1; i += 8) {
h2 = *pdig_rev_tbl++ >> 2;
x_0 = *x0++;
x_1 = *x0++;
x_2 = *x0++;
x_3 = *x0++;
x_4 = *x0++;
x_5 = *x0++;
x_6 = *x0++;
x_7 = *x0++;
n00 = x_0 + x_2;
n01 = x_1 + x_3;
n20 = x_0 - x_2;
n21 = x_1 - x_3;
n10 = x_4 + x_6;
n11 = x_5 + x_7;
n30 = x_4 - x_6;
n31 = x_5 - x_7;
y0[h2] = n00;
y0[h2 + 1] = n01;
y1[h2] = n10;
y1[h2 + 1] = n11;
y2[h2] = n20;
y2[h2 + 1] = n21;
y3[h2] = n30;
y3[h2 + 1] = n31;
x_8 = *x2++;
x_9 = *x2++;
x_a = *x2++;
x_b = *x2++;
x_c = *x2++;
x_d = *x2++;
x_e = *x2++;
x_f = *x2++;
n02 = x_8 + x_a;
n03 = x_9 + x_b;
n22 = x_8 - x_a;
n23 = x_9 - x_b;
n12 = x_c + x_e;
n13 = x_d + x_f;
n32 = x_c - x_e;
n33 = x_d - x_f;
y0[h2 + 2] = n02;
y0[h2 + 3] = n03;
y1[h2 + 2] = n12;
y1[h2 + 3] = n13;
y2[h2 + 2] = n22;
y2[h2 + 3] = n23;
y3[h2 + 2] = n32;
y3[h2 + 3] = n33;
}
x0 += (WORD32)npoints >> 1;
x2 += (WORD32)npoints >> 1;
}
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787 | VOID ixheaacd_esbr_postradixcompute2(WORD32 *ptr_y, WORD32 *ptr_x,
const WORD32 *pdig_rev_tbl,
WORD32 npoints) {
WORD32 i, k;
WORD32 h2;
WORD32 x_0, x_1, x_2, x_3;
WORD32 x_4, x_5, x_6, x_7;
WORD32 x_8, x_9, x_a, x_b, x_c, x_d, x_e, x_f;
WORD32 n0, j0;
WORD32 *x2, *x0;
WORD32 *y0, *y1, *y2, *y3;
y0 = ptr_y;
y2 = ptr_y + (WORD32)npoints;
x0 = ptr_x;
x2 = ptr_x + (WORD32)(npoints >> 1);
y1 = y0 + (WORD32)(npoints >> 2);
y3 = y2 + (WORD32)(npoints >> 2);
j0 = 8;
n0 = npoints >> 1;
for (k = 0; k < 2; k++) {
for (i = 0; i<npoints>> 1; i += 8) {
h2 = *pdig_rev_tbl++ >> 2;
x_0 = *x0++;
x_1 = *x0++;
x_2 = *x0++;
x_3 = *x0++;
x_4 = *x0++;
x_5 = *x0++;
x_6 = *x0++;
x_7 = *x0++;
y0[h2] = ixheaacd_add32_sat(x_0, x_2);
y0[h2 + 1] = ixheaacd_add32_sat(x_1, x_3);
y1[h2] = ixheaacd_add32_sat(x_4, x_6);
y1[h2 + 1] = ixheaacd_add32_sat(x_5, x_7);
y2[h2] = ixheaacd_sub32_sat(x_0, x_2);
y2[h2 + 1] = ixheaacd_sub32_sat(x_1, x_3);
y3[h2] = ixheaacd_sub32_sat(x_4, x_6);
y3[h2 + 1] = ixheaacd_sub32_sat(x_5, x_7);
x_8 = *x2++;
x_9 = *x2++;
x_a = *x2++;
x_b = *x2++;
x_c = *x2++;
x_d = *x2++;
x_e = *x2++;
x_f = *x2++;
y0[h2 + 2] = ixheaacd_add32_sat(x_8, x_a);
y0[h2 + 3] = ixheaacd_add32_sat(x_9, x_b);
y1[h2 + 2] = ixheaacd_add32_sat(x_c, x_e);
y1[h2 + 3] = ixheaacd_add32_sat(x_d, x_f);
y2[h2 + 2] = ixheaacd_sub32_sat(x_8, x_a);
y2[h2 + 3] = ixheaacd_sub32_sat(x_9, x_b);
y3[h2 + 2] = ixheaacd_sub32_sat(x_c, x_e);
y3[h2 + 3] = ixheaacd_sub32_sat(x_d, x_f);
}
x0 += (WORD32)npoints >> 1;
x2 += (WORD32)npoints >> 1;
}
}
| 174,087 |
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 do_free_upto(BIO *f, BIO *upto)
{
if (upto)
{
BIO *tbio;
do
{
tbio = BIO_pop(f);
BIO_free(f);
f = tbio;
}
while (f != upto);
}
else
BIO_free_all(f);
}
Commit Message: Canonicalise input in CMS_verify.
If content is detached and not binary mode translate the input to
CRLF format. Before this change the input was verified verbatim
which lead to a discrepancy between sign and verify.
CWE ID: CWE-399 | static void do_free_upto(BIO *f, BIO *upto)
{
if (upto)
{
BIO *tbio;
do
{
tbio = BIO_pop(f);
BIO_free(f);
f = tbio;
}
while (f && f != upto);
}
else
BIO_free_all(f);
}
| 166,690 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
png_size_t png_struct_size)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* to save current jump buffer */
#endif
int i = 0;
png_structp png_ptr=*ptr_ptr;
if (png_ptr == NULL)
return;
do
{
if (user_png_ver[i] != png_libpng_ver[i])
{
#ifdef PNG_LEGACY_SUPPORTED
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
#else
png_ptr->warning_fn = NULL;
png_warning(png_ptr,
"Application uses deprecated png_read_init() and should be"
" recompiled.");
break;
#endif
}
} while (png_libpng_ver[i++]);
png_debug(1, "in png_read_init_3");
#ifdef PNG_SETJMP_SUPPORTED
/* Save jump buffer and error functions */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
if (png_sizeof(png_struct) > png_struct_size)
{
png_destroy_struct(png_ptr);
*ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
png_ptr = *ptr_ptr;
}
/* Reset all variables to 0 */
png_memset(png_ptr, 0, png_sizeof(png_struct));
#ifdef PNG_SETJMP_SUPPORTED
/* Restore jump buffer */
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
/* Added at libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
png_ptr->user_width_max = PNG_USER_WIDTH_MAX;
png_ptr->user_height_max = PNG_USER_HEIGHT_MAX;
#endif
/* Initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error");
break;
default: png_error(png_ptr, "Unknown zlib error");
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
png_size_t png_struct_size)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* to save current jump buffer */
#endif
int i = 0;
png_structp png_ptr=*ptr_ptr;
if (png_ptr == NULL)
return;
do
{
if (user_png_ver == NULL || user_png_ver[i] != png_libpng_ver[i])
{
#ifdef PNG_LEGACY_SUPPORTED
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
#else
png_ptr->warning_fn = NULL;
png_warning(png_ptr,
"Application uses deprecated png_read_init() and should be"
" recompiled.");
break;
#endif
}
} while (png_libpng_ver[i++]);
png_debug(1, "in png_read_init_3");
#ifdef PNG_SETJMP_SUPPORTED
/* Save jump buffer and error functions */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
if (png_sizeof(png_struct) > png_struct_size)
{
png_destroy_struct(png_ptr);
*ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
png_ptr = *ptr_ptr;
}
/* Reset all variables to 0 */
png_memset(png_ptr, 0, png_sizeof(png_struct));
#ifdef PNG_SETJMP_SUPPORTED
/* Restore jump buffer */
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
/* Added at libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
png_ptr->user_width_max = PNG_USER_WIDTH_MAX;
png_ptr->user_height_max = PNG_USER_HEIGHT_MAX;
#endif
/* Initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error");
break;
default: png_error(png_ptr, "Unknown zlib error");
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
}
| 172,169 |
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: vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect,
const guint8 * data, int len, gboolean decode)
{
GstVideoFormat format;
gint bpp, tc;
guint32 redmask, greenmask, bluemask;
guint32 endianness, dataendianness;
GstVideoCodecState *state;
/* A WMVi rectangle has a 16byte payload */
if (len < 16) {
GST_DEBUG_OBJECT (dec, "Bad WMVi rect: too short");
return ERROR_INSUFFICIENT_DATA;
}
/* We only compare 13 bytes; ignoring the 3 padding bytes at the end */
if (dec->have_format && memcmp (data, dec->format.descriptor, 13) == 0) {
/* Nothing changed, so just exit */
return 16;
}
/* Store the whole block for simple comparison later */
memcpy (dec->format.descriptor, data, 16);
if (rect->x != 0 || rect->y != 0) {
GST_WARNING_OBJECT (dec, "Bad WMVi rect: wrong coordinates");
return ERROR_INVALID;
}
bpp = data[0];
dec->format.depth = data[1];
dec->format.big_endian = data[2];
dataendianness = data[2] ? G_BIG_ENDIAN : G_LITTLE_ENDIAN;
tc = data[3];
if (bpp != 8 && bpp != 16 && bpp != 32) {
GST_WARNING_OBJECT (dec, "Bad bpp value: %d", bpp);
return ERROR_INVALID;
}
if (!tc) {
GST_WARNING_OBJECT (dec, "Paletted video not supported");
return ERROR_INVALID;
}
dec->format.bytes_per_pixel = bpp / 8;
dec->format.width = rect->width;
dec->format.height = rect->height;
redmask = (guint32) (RFB_GET_UINT16 (data + 4)) << data[10];
greenmask = (guint32) (RFB_GET_UINT16 (data + 6)) << data[11];
bluemask = (guint32) (RFB_GET_UINT16 (data + 8)) << data[12];
GST_DEBUG_OBJECT (dec, "Red: mask %d, shift %d",
RFB_GET_UINT16 (data + 4), data[10]);
GST_DEBUG_OBJECT (dec, "Green: mask %d, shift %d",
RFB_GET_UINT16 (data + 6), data[11]);
GST_DEBUG_OBJECT (dec, "Blue: mask %d, shift %d",
RFB_GET_UINT16 (data + 8), data[12]);
GST_DEBUG_OBJECT (dec, "BPP: %d. endianness: %s", bpp,
data[2] ? "big" : "little");
/* GStreamer's RGB caps are a bit weird. */
if (bpp == 8) {
endianness = G_BYTE_ORDER; /* Doesn't matter */
} else if (bpp == 16) {
/* We require host-endian. */
endianness = G_BYTE_ORDER;
} else { /* bpp == 32 */
/* We require big endian */
endianness = G_BIG_ENDIAN;
if (endianness != dataendianness) {
redmask = GUINT32_SWAP_LE_BE (redmask);
greenmask = GUINT32_SWAP_LE_BE (greenmask);
bluemask = GUINT32_SWAP_LE_BE (bluemask);
}
}
format = gst_video_format_from_masks (dec->format.depth, bpp, endianness,
redmask, greenmask, bluemask, 0);
GST_DEBUG_OBJECT (dec, "From depth: %d bpp: %u endianess: %s redmask: %X "
"greenmask: %X bluemask: %X got format %s",
dec->format.depth, bpp, endianness == G_BIG_ENDIAN ? "BE" : "LE",
GUINT32_FROM_BE (redmask), GUINT32_FROM_BE (greenmask),
GUINT32_FROM_BE (bluemask),
format == GST_VIDEO_FORMAT_UNKNOWN ? "UNKOWN" :
gst_video_format_to_string (format));
if (format == GST_VIDEO_FORMAT_UNKNOWN) {
GST_WARNING_OBJECT (dec, "Video format unknown to GStreamer");
return ERROR_INVALID;
}
dec->have_format = TRUE;
if (!decode) {
GST_LOG_OBJECT (dec, "Parsing, not setting caps");
return 16;
}
state = gst_video_decoder_set_output_state (GST_VIDEO_DECODER (dec), format,
rect->width, rect->height, dec->input_state);
gst_video_codec_state_unref (state);
g_free (dec->imagedata);
dec->imagedata = g_malloc (dec->format.width * dec->format.height *
dec->format.bytes_per_pixel);
GST_DEBUG_OBJECT (dec, "Allocated image data at %p", dec->imagedata);
dec->format.stride = dec->format.width * dec->format.bytes_per_pixel;
return 16;
}
Commit Message:
CWE ID: CWE-200 | vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect,
const guint8 * data, int len, gboolean decode)
{
GstVideoFormat format;
gint bpp, tc;
guint32 redmask, greenmask, bluemask;
guint32 endianness, dataendianness;
GstVideoCodecState *state;
/* A WMVi rectangle has a 16byte payload */
if (len < 16) {
GST_DEBUG_OBJECT (dec, "Bad WMVi rect: too short");
return ERROR_INSUFFICIENT_DATA;
}
/* We only compare 13 bytes; ignoring the 3 padding bytes at the end */
if (dec->have_format && memcmp (data, dec->format.descriptor, 13) == 0) {
/* Nothing changed, so just exit */
return 16;
}
/* Store the whole block for simple comparison later */
memcpy (dec->format.descriptor, data, 16);
if (rect->x != 0 || rect->y != 0) {
GST_WARNING_OBJECT (dec, "Bad WMVi rect: wrong coordinates");
return ERROR_INVALID;
}
bpp = data[0];
dec->format.depth = data[1];
dec->format.big_endian = data[2];
dataendianness = data[2] ? G_BIG_ENDIAN : G_LITTLE_ENDIAN;
tc = data[3];
if (bpp != 8 && bpp != 16 && bpp != 32) {
GST_WARNING_OBJECT (dec, "Bad bpp value: %d", bpp);
return ERROR_INVALID;
}
if (!tc) {
GST_WARNING_OBJECT (dec, "Paletted video not supported");
return ERROR_INVALID;
}
dec->format.bytes_per_pixel = bpp / 8;
dec->format.width = rect->width;
dec->format.height = rect->height;
redmask = (guint32) (RFB_GET_UINT16 (data + 4)) << data[10];
greenmask = (guint32) (RFB_GET_UINT16 (data + 6)) << data[11];
bluemask = (guint32) (RFB_GET_UINT16 (data + 8)) << data[12];
GST_DEBUG_OBJECT (dec, "Red: mask %d, shift %d",
RFB_GET_UINT16 (data + 4), data[10]);
GST_DEBUG_OBJECT (dec, "Green: mask %d, shift %d",
RFB_GET_UINT16 (data + 6), data[11]);
GST_DEBUG_OBJECT (dec, "Blue: mask %d, shift %d",
RFB_GET_UINT16 (data + 8), data[12]);
GST_DEBUG_OBJECT (dec, "BPP: %d. endianness: %s", bpp,
data[2] ? "big" : "little");
/* GStreamer's RGB caps are a bit weird. */
if (bpp == 8) {
endianness = G_BYTE_ORDER; /* Doesn't matter */
} else if (bpp == 16) {
/* We require host-endian. */
endianness = G_BYTE_ORDER;
} else { /* bpp == 32 */
/* We require big endian */
endianness = G_BIG_ENDIAN;
if (endianness != dataendianness) {
redmask = GUINT32_SWAP_LE_BE (redmask);
greenmask = GUINT32_SWAP_LE_BE (greenmask);
bluemask = GUINT32_SWAP_LE_BE (bluemask);
}
}
format = gst_video_format_from_masks (dec->format.depth, bpp, endianness,
redmask, greenmask, bluemask, 0);
GST_DEBUG_OBJECT (dec, "From depth: %d bpp: %u endianess: %s redmask: %X "
"greenmask: %X bluemask: %X got format %s",
dec->format.depth, bpp, endianness == G_BIG_ENDIAN ? "BE" : "LE",
GUINT32_FROM_BE (redmask), GUINT32_FROM_BE (greenmask),
GUINT32_FROM_BE (bluemask),
format == GST_VIDEO_FORMAT_UNKNOWN ? "UNKOWN" :
gst_video_format_to_string (format));
if (format == GST_VIDEO_FORMAT_UNKNOWN) {
GST_WARNING_OBJECT (dec, "Video format unknown to GStreamer");
return ERROR_INVALID;
}
dec->have_format = TRUE;
if (!decode) {
GST_LOG_OBJECT (dec, "Parsing, not setting caps");
return 16;
}
state = gst_video_decoder_set_output_state (GST_VIDEO_DECODER (dec), format,
rect->width, rect->height, dec->input_state);
gst_video_codec_state_unref (state);
g_free (dec->imagedata);
dec->imagedata = g_malloc0 (dec->format.width * dec->format.height *
dec->format.bytes_per_pixel);
GST_DEBUG_OBJECT (dec, "Allocated image data at %p", dec->imagedata);
dec->format.stride = dec->format.width * dec->format.bytes_per_pixel;
return 16;
}
| 165,252 |
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: perform_transform_test(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
while (next_format(&colour_type, &bit_depth, &palette_number, 0))
{
png_uint_32 counter = 0;
size_t base_pos;
char name[64];
base_pos = safecat(name, sizeof name, 0, "transform:");
for (;;)
{
size_t pos = base_pos;
PNG_CONST image_transform *list = 0;
/* 'max' is currently hardwired to '1'; this should be settable on the
* command line.
*/
counter = image_transform_add(&list, 1/*max*/, counter,
name, sizeof name, &pos, colour_type, bit_depth);
if (counter == 0)
break;
/* The command line can change this to checking interlaced images. */
do
{
pm->repeat = 0;
transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
pm->interlace_type, 0, 0, 0), list, name);
if (fail(pm))
return;
}
while (pm->repeat);
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | perform_transform_test(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
pm->test_tRNS))
{
png_uint_32 counter = 0;
size_t base_pos;
char name[64];
base_pos = safecat(name, sizeof name, 0, "transform:");
for (;;)
{
size_t pos = base_pos;
const image_transform *list = 0;
/* 'max' is currently hardwired to '1'; this should be settable on the
* command line.
*/
counter = image_transform_add(&list, 1/*max*/, counter,
name, sizeof name, &pos, colour_type, bit_depth);
if (counter == 0)
break;
/* The command line can change this to checking interlaced images. */
do
{
pm->repeat = 0;
transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
pm->interlace_type, 0, 0, 0), list, name);
if (fail(pm))
return;
}
while (pm->repeat);
}
}
}
| 173,684 |
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 BluetoothDeviceChromeOS::RequestConfirmation(
const dbus::ObjectPath& device_path,
uint32 passkey,
const ConfirmationCallback& callback) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": RequestConfirmation: " << passkey;
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_CONFIRM_PASSKEY,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
DCHECK(confirmation_callback_.is_null());
confirmation_callback_ = callback;
pairing_delegate_->ConfirmPasskey(this, passkey);
pairing_delegate_used_ = true;
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::RequestConfirmation(
| 171,235 |
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: ExtensionsGuestViewMessageFilter::FrameNavigationHelper::FrameNavigationHelper(
RenderFrameHost* plugin_rfh,
int32_t guest_instance_id,
int32_t element_instance_id,
bool is_full_page_plugin,
ExtensionsGuestViewMessageFilter* filter)
: content::WebContentsObserver(
content::WebContents::FromRenderFrameHost(plugin_rfh)),
frame_tree_node_id_(plugin_rfh->GetFrameTreeNodeId()),
guest_instance_id_(guest_instance_id),
element_instance_id_(element_instance_id),
is_full_page_plugin_(is_full_page_plugin),
filter_(filter),
parent_site_instance_(plugin_rfh->GetParent()->GetSiteInstance()),
weak_factory_(this) {
DCHECK(GetGuestView());
NavigateToAboutBlank();
base::PostDelayedTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&ExtensionsGuestViewMessageFilter::FrameNavigationHelper::
CancelPendingTask,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kAttachFailureDelayMS));
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | ExtensionsGuestViewMessageFilter::FrameNavigationHelper::FrameNavigationHelper(
| 173,041 |
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 bpf_int_jit_compile(struct bpf_prog *prog)
{
struct bpf_binary_header *header = NULL;
int proglen, oldproglen = 0;
struct jit_context ctx = {};
u8 *image = NULL;
int *addrs;
int pass;
int i;
if (!bpf_jit_enable)
return;
if (!prog || !prog->len)
return;
addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL);
if (!addrs)
return;
/* Before first pass, make a rough estimation of addrs[]
* each bpf instruction is translated to less than 64 bytes
*/
for (proglen = 0, i = 0; i < prog->len; i++) {
proglen += 64;
addrs[i] = proglen;
}
ctx.cleanup_addr = proglen;
for (pass = 0; pass < 10; pass++) {
proglen = do_jit(prog, addrs, image, oldproglen, &ctx);
if (proglen <= 0) {
image = NULL;
if (header)
bpf_jit_binary_free(header);
goto out;
}
if (image) {
if (proglen != oldproglen) {
pr_err("bpf_jit: proglen=%d != oldproglen=%d\n",
proglen, oldproglen);
goto out;
}
break;
}
if (proglen == oldproglen) {
header = bpf_jit_binary_alloc(proglen, &image,
1, jit_fill_hole);
if (!header)
goto out;
}
oldproglen = proglen;
}
if (bpf_jit_enable > 1)
bpf_jit_dump(prog->len, proglen, 0, image);
if (image) {
bpf_flush_icache(header, image + proglen);
set_memory_ro((unsigned long)header, header->pages);
prog->bpf_func = (void *)image;
prog->jited = true;
}
out:
kfree(addrs);
}
Commit Message: x86: bpf_jit: fix compilation of large bpf programs
x86 has variable length encoding. x86 JIT compiler is trying
to pick the shortest encoding for given bpf instruction.
While doing so the jump targets are changing, so JIT is doing
multiple passes over the program. Typical program needs 3 passes.
Some very short programs converge with 2 passes. Large programs
may need 4 or 5. But specially crafted bpf programs may hit the
pass limit and if the program converges on the last iteration
the JIT compiler will be producing an image full of 'int 3' insns.
Fix this corner case by doing final iteration over bpf program.
Fixes: 0a14842f5a3c ("net: filter: Just In Time compiler for x86-64")
Reported-by: Daniel Borkmann <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Tested-by: Daniel Borkmann <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-17 | void bpf_int_jit_compile(struct bpf_prog *prog)
{
struct bpf_binary_header *header = NULL;
int proglen, oldproglen = 0;
struct jit_context ctx = {};
u8 *image = NULL;
int *addrs;
int pass;
int i;
if (!bpf_jit_enable)
return;
if (!prog || !prog->len)
return;
addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL);
if (!addrs)
return;
/* Before first pass, make a rough estimation of addrs[]
* each bpf instruction is translated to less than 64 bytes
*/
for (proglen = 0, i = 0; i < prog->len; i++) {
proglen += 64;
addrs[i] = proglen;
}
ctx.cleanup_addr = proglen;
/* JITed image shrinks with every pass and the loop iterates
* until the image stops shrinking. Very large bpf programs
* may converge on the last pass. In such case do one more
* pass to emit the final image
*/
for (pass = 0; pass < 10 || image; pass++) {
proglen = do_jit(prog, addrs, image, oldproglen, &ctx);
if (proglen <= 0) {
image = NULL;
if (header)
bpf_jit_binary_free(header);
goto out;
}
if (image) {
if (proglen != oldproglen) {
pr_err("bpf_jit: proglen=%d != oldproglen=%d\n",
proglen, oldproglen);
goto out;
}
break;
}
if (proglen == oldproglen) {
header = bpf_jit_binary_alloc(proglen, &image,
1, jit_fill_hole);
if (!header)
goto out;
}
oldproglen = proglen;
}
if (bpf_jit_enable > 1)
bpf_jit_dump(prog->len, proglen, 0, image);
if (image) {
bpf_flush_icache(header, image + proglen);
set_memory_ro((unsigned long)header, header->pages);
prog->bpf_func = (void *)image;
prog->jited = true;
}
out:
kfree(addrs);
}
| 166,611 |
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::sendCommand(
OMX_COMMANDTYPE cmd, OMX_S32 param) {
if (cmd == OMX_CommandStateSet) {
mSailed = true;
}
const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && cmd == OMX_CommandStateSet) {
if (param == OMX_StateIdle) {
bufferSource->omxIdle();
} else if (param == OMX_StateLoaded) {
bufferSource->omxLoaded();
setGraphicBufferSource(NULL);
}
}
Mutex::Autolock autoLock(mLock);
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
const char *paramString =
cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param);
CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL);
CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
return StatusFromOMXError(err);
}
Commit Message: IOMX: allow configuration after going to loaded state
This was disallowed recently but we still use it as MediaCodcec.stop
only goes to loaded state, and does not free component.
Bug: 31450460
Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d
(cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b)
CWE ID: CWE-200 | status_t OMXNodeInstance::sendCommand(
OMX_COMMANDTYPE cmd, OMX_S32 param) {
if (cmd == OMX_CommandStateSet) {
// There are no configurations past first StateSet command.
mSailed = true;
}
const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && cmd == OMX_CommandStateSet) {
if (param == OMX_StateIdle) {
bufferSource->omxIdle();
} else if (param == OMX_StateLoaded) {
bufferSource->omxLoaded();
setGraphicBufferSource(NULL);
}
}
Mutex::Autolock autoLock(mLock);
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
const char *paramString =
cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param);
CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL);
CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
return StatusFromOMXError(err);
}
| 173,380 |
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 TestingPlatformSupport::cryptographicallyRandomValues(unsigned char* buffer, size_t length)
{
}
Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used.
These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect.
BUG=552749
Review URL: https://codereview.chromium.org/1419293005
Cr-Commit-Position: refs/heads/master@{#359229}
CWE ID: CWE-310 | void TestingPlatformSupport::cryptographicallyRandomValues(unsigned char* buffer, size_t length)
{
RELEASE_ASSERT_NOT_REACHED();
}
| 172,239 |
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: OMX_ERRORTYPE SoftFlacEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
ALOGV("SoftFlacEncoder::internalGetParameter(index=0x%x)", index);
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSampleRate;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioFlac:
{
OMX_AUDIO_PARAM_FLACTYPE *flacParams = (OMX_AUDIO_PARAM_FLACTYPE *)params;
flacParams->nCompressionLevel = mCompressionLevel;
flacParams->nChannels = mNumChannels;
flacParams->nSampleRate = mSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftFlacEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
ALOGV("SoftFlacEncoder::internalGetParameter(index=0x%x)", index);
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSampleRate;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioFlac:
{
OMX_AUDIO_PARAM_FLACTYPE *flacParams = (OMX_AUDIO_PARAM_FLACTYPE *)params;
if (!isValidOMXParam(flacParams)) {
return OMX_ErrorBadParameter;
}
flacParams->nCompressionLevel = mCompressionLevel;
flacParams->nChannels = mNumChannels;
flacParams->nSampleRate = mSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,203 |
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 copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
Commit Message: xfrm_user: fix info leak in copy_to_user_policy()
The memory reserved to dump the xfrm policy includes multiple padding
bytes added by the compiler for alignment (padding bytes in struct
xfrm_selector and struct xfrm_userpolicy_info). Add an explicit
memset(0) before filling the buffer to avoid the heap info leak.
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memset(p, 0, sizeof(*p));
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
| 169,902 |
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 user_manager::UserList UserSelectionScreen::PrepareUserListForSending(
const user_manager::UserList& users,
const AccountId& owner,
bool is_signin_to_add) {
user_manager::UserList users_to_send;
bool has_owner = owner.is_valid();
size_t max_non_owner_users = has_owner ? kMaxUsers - 1 : kMaxUsers;
size_t non_owner_count = 0;
for (user_manager::UserList::const_iterator it = users.begin();
it != users.end(); ++it) {
bool is_owner = ((*it)->GetAccountId() == owner);
bool is_public_account =
((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT);
if ((is_public_account && !is_signin_to_add) || is_owner ||
(!is_public_account && non_owner_count < max_non_owner_users)) {
if (!is_owner)
++non_owner_count;
if (is_owner && users_to_send.size() > kMaxUsers) {
users_to_send.insert(users_to_send.begin() + (kMaxUsers - 1), *it);
while (users_to_send.size() > kMaxUsers)
users_to_send.erase(users_to_send.begin() + kMaxUsers);
} else if (users_to_send.size() < kMaxUsers) {
users_to_send.push_back(*it);
}
}
}
return users_to_send;
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID: | const user_manager::UserList UserSelectionScreen::PrepareUserListForSending(
const user_manager::UserList& users,
const AccountId& owner,
bool is_signin_to_add) {
user_manager::UserList users_to_send;
bool has_owner = owner.is_valid();
size_t max_non_owner_users = has_owner ? kMaxUsers - 1 : kMaxUsers;
size_t non_owner_count = 0;
for (user_manager::User* user : users) {
bool is_owner = user->GetAccountId() == owner;
bool is_public_account =
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
if ((is_public_account && !is_signin_to_add) || is_owner ||
(!is_public_account && non_owner_count < max_non_owner_users)) {
if (!is_owner)
++non_owner_count;
if (is_owner && users_to_send.size() > kMaxUsers) {
users_to_send.insert(users_to_send.begin() + (kMaxUsers - 1), user);
while (users_to_send.size() > kMaxUsers)
users_to_send.erase(users_to_send.begin() + kMaxUsers);
} else if (users_to_send.size() < kMaxUsers) {
users_to_send.push_back(user);
}
}
}
return users_to_send;
}
| 172,203 |
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 setup_token_decoder(VP8D_COMP *pbi,
const unsigned char* token_part_sizes)
{
vp8_reader *bool_decoder = &pbi->mbc[0];
unsigned int partition_idx;
unsigned int fragment_idx;
unsigned int num_token_partitions;
const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
TOKEN_PARTITION multi_token_partition =
(TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2);
if (!vp8dx_bool_error(&pbi->mbc[8]))
pbi->common.multi_token_partition = multi_token_partition;
num_token_partitions = 1 << pbi->common.multi_token_partition;
/* Check for partitions within the fragments and unpack the fragments
* so that each fragment pointer points to its corresponding partition. */
for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx)
{
unsigned int fragment_size = pbi->fragments.sizes[fragment_idx];
const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] +
fragment_size;
/* Special case for handling the first partition since we have already
* read its size. */
if (fragment_idx == 0)
{
/* Size of first partition + token partition sizes element */
ptrdiff_t ext_first_part_size = token_part_sizes -
pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1);
fragment_size -= (unsigned int)ext_first_part_size;
if (fragment_size > 0)
{
pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size;
/* The fragment contains an additional partition. Move to
* next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
}
}
/* Split the chunk into partitions read from the bitstream */
while (fragment_size > 0)
{
ptrdiff_t partition_size = read_available_partition_size(
pbi,
token_part_sizes,
pbi->fragments.ptrs[fragment_idx],
first_fragment_end,
fragment_end,
fragment_idx - 1,
num_token_partitions);
pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size;
fragment_size -= (unsigned int)partition_size;
assert(fragment_idx <= num_token_partitions);
if (fragment_size > 0)
{
/* The fragment contains an additional partition.
* Move to next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] =
pbi->fragments.ptrs[fragment_idx - 1] + partition_size;
}
}
}
pbi->fragments.count = num_token_partitions + 1;
for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx)
{
if (vp8dx_start_decode(bool_decoder,
pbi->fragments.ptrs[partition_idx],
pbi->fragments.sizes[partition_idx],
pbi->decrypt_cb, pbi->decrypt_state))
vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
"Failed to allocate bool decoder %d",
partition_idx);
bool_decoder++;
}
#if CONFIG_MULTITHREAD
/* Clamp number of decoder threads */
if (pbi->decoding_thread_count > num_token_partitions - 1)
pbi->decoding_thread_count = num_token_partitions - 1;
#endif
}
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: | static void setup_token_decoder(VP8D_COMP *pbi,
const unsigned char* token_part_sizes)
{
vp8_reader *bool_decoder = &pbi->mbc[0];
unsigned int partition_idx;
unsigned int fragment_idx;
unsigned int num_token_partitions;
const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
TOKEN_PARTITION multi_token_partition =
(TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2);
if (!vp8dx_bool_error(&pbi->mbc[8]))
pbi->common.multi_token_partition = multi_token_partition;
num_token_partitions = 1 << pbi->common.multi_token_partition;
/* Check for partitions within the fragments and unpack the fragments
* so that each fragment pointer points to its corresponding partition. */
for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx)
{
unsigned int fragment_size = pbi->fragments.sizes[fragment_idx];
const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] +
fragment_size;
/* Special case for handling the first partition since we have already
* read its size. */
if (fragment_idx == 0)
{
/* Size of first partition + token partition sizes element */
ptrdiff_t ext_first_part_size = token_part_sizes -
pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1);
fragment_size -= (unsigned int)ext_first_part_size;
if (fragment_size > 0)
{
pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size;
/* The fragment contains an additional partition. Move to
* next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
}
}
/* Split the chunk into partitions read from the bitstream */
while (fragment_size > 0)
{
ptrdiff_t partition_size = read_available_partition_size(
pbi,
token_part_sizes,
pbi->fragments.ptrs[fragment_idx],
first_fragment_end,
fragment_end,
fragment_idx - 1,
num_token_partitions);
pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size;
fragment_size -= (unsigned int)partition_size;
assert(fragment_idx <= num_token_partitions);
if (fragment_size > 0)
{
/* The fragment contains an additional partition.
* Move to next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] =
pbi->fragments.ptrs[fragment_idx - 1] + partition_size;
}
}
}
pbi->fragments.count = num_token_partitions + 1;
for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx)
{
if (vp8dx_start_decode(bool_decoder,
pbi->fragments.ptrs[partition_idx],
pbi->fragments.sizes[partition_idx],
pbi->decrypt_cb, pbi->decrypt_state))
vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
"Failed to allocate bool decoder %d",
partition_idx);
bool_decoder++;
}
#if CONFIG_MULTITHREAD
/* Clamp number of decoder threads */
if (pbi->decoding_thread_count > num_token_partitions - 1) {
pbi->decoding_thread_count = num_token_partitions - 1;
}
if (pbi->decoding_thread_count > pbi->common.mb_rows - 1) {
pbi->decoding_thread_count = pbi->common.mb_rows - 1;
}
#endif
}
| 174,064 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, Blob* blob)
{
m_urlForReading = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin());
if (m_urlForReading.isEmpty()) {
failed(FileError::SECURITY_ERR);
return;
}
ThreadableBlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, blob->url());
ResourceRequest request(m_urlForReading);
request.setHTTPMethod("GET");
if (m_hasRange)
request.setHTTPHeaderField("Range", String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd));
ThreadableLoaderOptions options;
options.sendLoadCallbacks = SendCallbacks;
options.sniffContent = DoNotSniffContent;
options.preflightPolicy = ConsiderPreflight;
options.allowCredentials = AllowStoredCredentials;
options.crossOriginRequestPolicy = DenyCrossOriginRequests;
options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
if (m_client)
m_loader = ThreadableLoader::create(scriptExecutionContext, this, request, options);
else
ThreadableLoader::loadResourceSynchronously(scriptExecutionContext, request, *this, options);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, Blob* blob)
{
m_urlForReading = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin());
if (m_urlForReading.isEmpty()) {
failed(FileError::SECURITY_ERR);
return;
}
BlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, blob->url());
ResourceRequest request(m_urlForReading);
request.setHTTPMethod("GET");
if (m_hasRange)
request.setHTTPHeaderField("Range", String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd));
ThreadableLoaderOptions options;
options.sendLoadCallbacks = SendCallbacks;
options.sniffContent = DoNotSniffContent;
options.preflightPolicy = ConsiderPreflight;
options.allowCredentials = AllowStoredCredentials;
options.crossOriginRequestPolicy = DenyCrossOriginRequests;
options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
if (m_client)
m_loader = ThreadableLoader::create(scriptExecutionContext, this, request, options);
else
ThreadableLoader::loadResourceSynchronously(scriptExecutionContext, request, *this, options);
}
| 170,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: static void set_active_map(const vpx_codec_enc_cfg_t *cfg,
vpx_codec_ctx_t *codec) {
unsigned int i;
vpx_active_map_t map = {0};
map.rows = (cfg->g_h + 15) / 16;
map.cols = (cfg->g_w + 15) / 16;
map.active_map = (uint8_t *)malloc(map.rows * map.cols);
for (i = 0; i < map.rows * map.cols; ++i)
map.active_map[i] = i % 2;
if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map))
die_codec(codec, "Failed to set active map");
free(map.active_map);
}
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 | static void set_active_map(const vpx_codec_enc_cfg_t *cfg,
vpx_codec_ctx_t *codec) {
unsigned int i;
vpx_active_map_t map = {0, 0, 0};
map.rows = (cfg->g_h + 15) / 16;
map.cols = (cfg->g_w + 15) / 16;
map.active_map = (uint8_t *)malloc(map.rows * map.cols);
for (i = 0; i < map.rows * map.cols; ++i)
map.active_map[i] = i % 2;
if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map))
die_codec(codec, "Failed to set active map");
free(map.active_map);
}
| 174,483 |
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: SendTabToSelfInfoBarDelegate::SendTabToSelfInfoBarDelegate(
const SendTabToSelfEntry* entry) {
entry_ = entry;
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190 | SendTabToSelfInfoBarDelegate::SendTabToSelfInfoBarDelegate(
content::WebContents* web_contents,
const SendTabToSelfEntry* entry) {
web_contents_ = web_contents;
entry_ = entry;
}
| 172,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: static void uipc_check_interrupt_locked(void)
{
if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set))
{
char sig_recv = 0;
recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
}
}
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 void uipc_check_interrupt_locked(void)
{
if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set))
{
char sig_recv = 0;
TEMP_FAILURE_RETRY(recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL));
}
}
| 173,496 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Init(const IPC::ChannelHandle& channel_handle,
PP_Module pp_module,
PP_GetInterface_Func local_get_interface,
const ppapi::Preferences& preferences,
SyncMessageStatusReceiver* status_receiver) {
dispatcher_delegate_.reset(new ProxyChannelDelegate);
dispatcher_.reset(new ppapi::proxy::HostDispatcher(
pp_module, local_get_interface, status_receiver));
if (!dispatcher_->InitHostWithChannel(dispatcher_delegate_.get(),
channel_handle,
true, // Client.
preferences)) {
dispatcher_.reset();
dispatcher_delegate_.reset();
return false;
}
return true;
}
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 | bool Init(const IPC::ChannelHandle& channel_handle,
| 170,735 |
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: gimp_write_and_read_file (Gimp *gimp,
gboolean with_unusual_stuff,
gboolean compat_paths,
gboolean use_gimp_2_8_features)
{
GimpImage *image;
GimpImage *loaded_image;
GimpPlugInProcedure *proc;
gchar *filename;
GFile *file;
/* Create the image */
image = gimp_create_mainimage (gimp,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Assert valid state */
gimp_assert_mainimage (image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Write to file */
filename = g_build_filename (g_get_tmp_dir (), "gimp-test.xcf", NULL);
file = g_file_new_for_path (filename);
g_free (filename);
proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager,
GIMP_FILE_PROCEDURE_GROUP_SAVE,
file,
NULL /*error*/);
file_save (gimp,
image,
NULL /*progress*/,
file,
proc,
GIMP_RUN_NONINTERACTIVE,
FALSE /*change_saved_state*/,
FALSE /*export_backward*/,
FALSE /*export_forward*/,
NULL /*error*/);
/* Load from file */
loaded_image = gimp_test_load_image (image->gimp, file);
/* Assert on the loaded file. If success, it means that there is no
* significant information loss when we wrote the image to a file
* and loaded it again
*/
gimp_assert_mainimage (loaded_image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
g_file_delete (file, NULL, NULL);
g_object_unref (file);
}
Commit Message: Issue #1689: create unique temporary file with g_file_open_tmp().
Not sure this is really solving the issue reported, which is that
`g_get_tmp_dir()` uses environment variables (yet as g_file_open_tmp()
uses g_get_tmp_dir()…). But at least g_file_open_tmp() should create
unique temporary files, which prevents overriding existing files (which
is most likely the only real attack possible here, or at least the only
one I can think of unless some weird vulnerabilities exist in glib).
CWE ID: CWE-20 | gimp_write_and_read_file (Gimp *gimp,
gboolean with_unusual_stuff,
gboolean compat_paths,
gboolean use_gimp_2_8_features)
{
GimpImage *image;
GimpImage *loaded_image;
GimpPlugInProcedure *proc;
gchar *filename = NULL;
gint file_handle;
GFile *file;
/* Create the image */
image = gimp_create_mainimage (gimp,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Assert valid state */
gimp_assert_mainimage (image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Write to file */
file_handle = g_file_open_tmp ("gimp-test-XXXXXX.xcf", &filename, NULL);
g_assert (file_handle != -1);
close (file_handle);
file = g_file_new_for_path (filename);
g_free (filename);
proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager,
GIMP_FILE_PROCEDURE_GROUP_SAVE,
file,
NULL /*error*/);
file_save (gimp,
image,
NULL /*progress*/,
file,
proc,
GIMP_RUN_NONINTERACTIVE,
FALSE /*change_saved_state*/,
FALSE /*export_backward*/,
FALSE /*export_forward*/,
NULL /*error*/);
/* Load from file */
loaded_image = gimp_test_load_image (image->gimp, file);
/* Assert on the loaded file. If success, it means that there is no
* significant information loss when we wrote the image to a file
* and loaded it again
*/
gimp_assert_mainimage (loaded_image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
g_file_delete (file, NULL, NULL);
g_object_unref (file);
}
| 169,187 |
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 ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)
{
struct cm_id_private *cm_id_priv;
cm_id_priv = container_of(id, struct cm_id_private, id);
if (smac != NULL)
memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac));
if (alt_smac != NULL)
memcpy(cm_id_priv->alt_av.smac, alt_smac,
sizeof(cm_id_priv->alt_av.smac));
return 0;
}
Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler
The code that resolves the passive side source MAC within the rdma_cm
connection request handler was both redundant and buggy, so remove it.
It was redundant since later, when an RC QP is modified to RTR state,
the resolution will take place in the ib_core module. It was buggy
because this callback also deals with UD SIDR exchange, for which we
incorrectly looked at the REQ member of the CM event and dereferenced
a random value.
Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures")
Signed-off-by: Moni Shoua <[email protected]>
Signed-off-by: Or Gerlitz <[email protected]>
Signed-off-by: Roland Dreier <[email protected]>
CWE ID: CWE-20 | int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)
| 166,389 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx)
{
struct desc_struct *desc;
unsigned long limit;
short sel;
sel = get_segment_selector(regs, seg_reg_idx);
if (sel < 0)
return 0;
if (user_64bit_mode(regs) || v8086_mode(regs))
return -1L;
if (!sel)
return 0;
desc = get_desc(sel);
if (!desc)
return 0;
/*
* If the granularity bit is set, the limit is given in multiples
* of 4096. This also means that the 12 least significant bits are
* not tested when checking the segment limits. In practice,
* this means that the segment ends in (limit << 12) + 0xfff.
*/
limit = get_desc_limit(desc);
if (desc->g)
limit = (limit << 12) + 0xfff;
return limit;
}
Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry
get_desc() computes a pointer into the LDT while holding a lock that
protects the LDT from being freed, but then drops the lock and returns the
(now potentially dangling) pointer to its caller.
Fix it by giving the caller a copy of the LDT entry instead.
Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx)
{
struct desc_struct desc;
unsigned long limit;
short sel;
sel = get_segment_selector(regs, seg_reg_idx);
if (sel < 0)
return 0;
if (user_64bit_mode(regs) || v8086_mode(regs))
return -1L;
if (!sel)
return 0;
if (!get_desc(&desc, sel))
return 0;
/*
* If the granularity bit is set, the limit is given in multiples
* of 4096. This also means that the 12 least significant bits are
* not tested when checking the segment limits. In practice,
* this means that the segment ends in (limit << 12) + 0xfff.
*/
limit = get_desc_limit(&desc);
if (desc.g)
limit = (limit << 12) + 0xfff;
return limit;
}
| 169,608 |
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_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-416 | PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
| 164,973 |
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 do_stack_segment(struct pt_regs *regs, long error_code)
{
enum ctx_state prev_state;
prev_state = exception_enter();
if (notify_die(DIE_TRAP, "stack segment", regs, error_code,
X86_TRAP_SS, SIGBUS) != NOTIFY_STOP) {
preempt_conditional_sti(regs);
do_trap(X86_TRAP_SS, SIGBUS, "stack segment", regs, error_code, NULL);
preempt_conditional_cli(regs);
}
exception_exit(prev_state);
}
Commit Message: x86_64, traps: Stop using IST for #SS
On a 32-bit kernel, this has no effect, since there are no IST stacks.
On a 64-bit kernel, #SS can only happen in user code, on a failed iret
to user space, a canonical violation on access via RSP or RBP, or a
genuine stack segment violation in 32-bit kernel code. The first two
cases don't need IST, and the latter two cases are unlikely fatal bugs,
and promoting them to double faults would be fine.
This fixes a bug in which the espfix64 code mishandles a stack segment
violation.
This saves 4k of memory per CPU and a tiny bit of code.
Signed-off-by: Andy Lutomirski <[email protected]>
Reviewed-by: Thomas Gleixner <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code)
| 166,238 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
CATEnum cat_enum;
char *sep;
cat_enum.dest = dest;
cat_enum.import_flags = import_flags;
cat_enum.force_fps = force_fps;
cat_enum.frames_per_sample = frames_per_sample;
cat_enum.tmp_dir = tmp_dir;
cat_enum.force_cat = force_cat;
cat_enum.align_timelines = align_timelines;
cat_enum.allow_add_in_command = allow_add_in_command;
strcpy(cat_enum.szPath, fileName);
sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);
if (!sep) sep = strrchr(cat_enum.szPath, '/');
if (!sep) {
strcpy(cat_enum.szPath, ".");
strcpy(cat_enum.szRad1, fileName);
} else {
strcpy(cat_enum.szRad1, sep+1);
sep[0] = 0;
}
sep = strchr(cat_enum.szRad1, '*');
strcpy(cat_enum.szRad2, sep+1);
sep[0] = 0;
sep = strchr(cat_enum.szRad2, '%');
if (!sep) sep = strchr(cat_enum.szRad2, '#');
if (!sep) sep = strchr(cat_enum.szRad2, ':');
strcpy(cat_enum.szOpt, "");
if (sep) {
strcpy(cat_enum.szOpt, sep);
sep[0] = 0;
}
return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);
}
Commit Message: fix some overflows due to strcpy
fixes #1184, #1186, #1187 among other things
CWE ID: CWE-119 | GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
CATEnum cat_enum;
char *sep;
cat_enum.dest = dest;
cat_enum.import_flags = import_flags;
cat_enum.force_fps = force_fps;
cat_enum.frames_per_sample = frames_per_sample;
cat_enum.tmp_dir = tmp_dir;
cat_enum.force_cat = force_cat;
cat_enum.align_timelines = align_timelines;
cat_enum.allow_add_in_command = allow_add_in_command;
if (strlen(fileName) >= sizeof(cat_enum.szPath)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", fileName));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szPath, fileName);
sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);
if (!sep) sep = strrchr(cat_enum.szPath, '/');
if (!sep) {
strcpy(cat_enum.szPath, ".");
if (strlen(fileName) >= sizeof(cat_enum.szRad1)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", fileName));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szRad1, fileName);
} else {
if (strlen(sep + 1) >= sizeof(cat_enum.szRad1)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", (sep + 1)));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szRad1, sep+1);
sep[0] = 0;
}
sep = strchr(cat_enum.szRad1, '*');
if (strlen(sep + 1) >= sizeof(cat_enum.szRad2)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", (sep + 1)));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szRad2, sep+1);
sep[0] = 0;
sep = strchr(cat_enum.szRad2, '%');
if (!sep) sep = strchr(cat_enum.szRad2, '#');
if (!sep) sep = strchr(cat_enum.szRad2, ':');
strcpy(cat_enum.szOpt, "");
if (sep) {
if (strlen(sep) >= sizeof(cat_enum.szOpt)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Invalid option: %s.\n", sep));
return GF_NOT_SUPPORTED;
}
strcpy(cat_enum.szOpt, sep);
sep[0] = 0;
}
return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);
}
| 169,788 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadNULLImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickPixelPacket
background;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if (image->columns == 0)
image->columns=1;
if (image->rows == 0)
image->rows=1;
image->matte=MagickTrue;
GetMagickPixelPacket(image,&background);
background.opacity=(MagickRealType) TransparentOpacity;
if (image->colorspace == CMYKColorspace)
ConvertRGBToCMYK(&background);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelPacket(image,&background,q,indexes);
q++;
indexes++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadNULLImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickPixelPacket
background;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if (image->columns == 0)
image->columns=1;
if (image->rows == 0)
image->rows=1;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->matte=MagickTrue;
GetMagickPixelPacket(image,&background);
background.opacity=(MagickRealType) TransparentOpacity;
if (image->colorspace == CMYKColorspace)
ConvertRGBToCMYK(&background);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelPacket(image,&background,q,indexes);
q++;
indexes++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(GetFirstImageInList(image));
}
| 168,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long SegmentInfo::Parse() {
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0AD7B1) { // Timecode Scale
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0489) { // Segment duration
const long status = UnserializeFloat(pReader, pos, size, m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0D80) { // MuxingApp
const long status =
UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
if (status)
return status;
} else if (id == 0x1741) { // WritingApp
const long status =
UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
if (status)
return status;
} else if (id == 0x3BA9) { // Title
const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long SegmentInfo::Parse() {
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0AD7B1) { // Timecode Scale
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0489) { // Segment duration
const long status = UnserializeFloat(pReader, pos, size, m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0D80) { // MuxingApp
const long status =
UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
if (status)
return status;
} else if (id == 0x1741) { // WritingApp
const long status =
UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
if (status)
return status;
} else if (id == 0x3BA9) { // Title
const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
const double rollover_check = m_duration * m_timecodeScale;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,842 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Segment::Load()
{
assert(m_clusters == NULL);
assert(m_clusterSize == 0);
assert(m_clusterCount == 0);
const long long header_status = ParseHeaders();
if (header_status < 0) //error
return static_cast<long>(header_status);
if (header_status > 0) //underflow
return E_BUFFER_NOT_FULL;
assert(m_pInfo);
assert(m_pTracks);
for (;;)
{
const int status = LoadCluster();
if (status < 0) //error
return status;
if (status >= 1) //no more clusters
return 0;
}
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Segment::Load()
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new Cluster* [n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
}
| 174,394 |
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: init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
int in_depth, int out_depth)
{
PNG_CONST unsigned int outmax = (1U<<out_depth)-1;
vi->pp = pp;
vi->dp = dp;
if (dp->sbit > 0 && dp->sbit < in_depth)
{
vi->sbit = dp->sbit;
vi->isbit_shift = in_depth - dp->sbit;
}
else
{
vi->sbit = (png_byte)in_depth;
vi->isbit_shift = 0;
}
vi->sbit_max = (1U << vi->sbit)-1;
/* This mimics the libpng threshold test, '0' is used to prevent gamma
* correction in the validation test.
*/
vi->screen_gamma = dp->screen_gamma;
if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
vi->screen_gamma = vi->screen_inverse = 0;
else
vi->screen_inverse = 1/vi->screen_gamma;
vi->use_input_precision = dp->use_input_precision;
vi->outmax = outmax;
vi->maxabs = abserr(dp->pm, in_depth, out_depth);
vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
vi->maxout = outerr(dp->pm, in_depth, out_depth);
vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
vi->maxout_total = vi->maxout + vi->outquant * .5;
vi->outlog = outlog(dp->pm, in_depth, out_depth);
if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
(dp->this.colour_type == 3 && dp->this.is_transparent))
{
vi->do_background = dp->do_background;
if (vi->do_background != 0)
{
PNG_CONST double bg_inverse = 1/dp->background_gamma;
double r, g, b;
/* Caller must at least put the gray value into the red channel */
r = dp->background_color.red; r /= outmax;
g = dp->background_color.green; g /= outmax;
b = dp->background_color.blue; b /= outmax;
# if 0
/* libpng doesn't do this optimization, if we do pngvalid will fail.
*/
if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
# endif
{
r = pow(r, bg_inverse);
g = pow(g, bg_inverse);
b = pow(b, bg_inverse);
}
vi->background_red = r;
vi->background_green = g;
vi->background_blue = b;
}
}
else
vi->do_background = 0;
if (vi->do_background == 0)
vi->background_red = vi->background_green = vi->background_blue = 0;
vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
vi->gamma_correction = 0;
vi->file_inverse = 1/dp->file_gamma;
if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
vi->file_inverse = 0;
vi->scale16 = dp->scale16;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
int in_depth, int out_depth)
{
const unsigned int outmax = (1U<<out_depth)-1;
vi->pp = pp;
vi->dp = dp;
if (dp->sbit > 0 && dp->sbit < in_depth)
{
vi->sbit = dp->sbit;
vi->isbit_shift = in_depth - dp->sbit;
}
else
{
vi->sbit = (png_byte)in_depth;
vi->isbit_shift = 0;
}
vi->sbit_max = (1U << vi->sbit)-1;
/* This mimics the libpng threshold test, '0' is used to prevent gamma
* correction in the validation test.
*/
vi->screen_gamma = dp->screen_gamma;
if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
vi->screen_gamma = vi->screen_inverse = 0;
else
vi->screen_inverse = 1/vi->screen_gamma;
vi->use_input_precision = dp->use_input_precision;
vi->outmax = outmax;
vi->maxabs = abserr(dp->pm, in_depth, out_depth);
vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
vi->maxout = outerr(dp->pm, in_depth, out_depth);
vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
vi->maxout_total = vi->maxout + vi->outquant * .5;
vi->outlog = outlog(dp->pm, in_depth, out_depth);
if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
(dp->this.colour_type == 3 && dp->this.is_transparent) ||
((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
dp->this.has_tRNS))
{
vi->do_background = dp->do_background;
if (vi->do_background != 0)
{
const double bg_inverse = 1/dp->background_gamma;
double r, g, b;
/* Caller must at least put the gray value into the red channel */
r = dp->background_color.red; r /= outmax;
g = dp->background_color.green; g /= outmax;
b = dp->background_color.blue; b /= outmax;
# if 0
/* libpng doesn't do this optimization, if we do pngvalid will fail.
*/
if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
# endif
{
r = pow(r, bg_inverse);
g = pow(g, bg_inverse);
b = pow(b, bg_inverse);
}
vi->background_red = r;
vi->background_green = g;
vi->background_blue = b;
}
}
else /* Do not expect any background processing */
vi->do_background = 0;
if (vi->do_background == 0)
vi->background_red = vi->background_green = vi->background_blue = 0;
vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
vi->gamma_correction = 0;
vi->file_inverse = 1/dp->file_gamma;
if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
vi->file_inverse = 0;
vi->scale16 = dp->scale16;
}
| 173,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: ssize_t NuPlayer::NuPlayerStreamListener::read(
void *data, size_t size, sp<AMessage> *extra) {
CHECK_GT(size, 0u);
extra->clear();
Mutex::Autolock autoLock(mLock);
if (mEOS) {
return 0;
}
if (mQueue.empty()) {
mSendDataNotification = true;
return -EWOULDBLOCK;
}
QueueEntry *entry = &*mQueue.begin();
if (entry->mIsCommand) {
switch (entry->mCommand) {
case EOS:
{
mQueue.erase(mQueue.begin());
entry = NULL;
mEOS = true;
return 0;
}
case DISCONTINUITY:
{
*extra = entry->mExtra;
mQueue.erase(mQueue.begin());
entry = NULL;
return INFO_DISCONTINUITY;
}
default:
TRESPASS();
break;
}
}
size_t copy = entry->mSize;
if (copy > size) {
copy = size;
}
memcpy(data,
(const uint8_t *)mBuffers.editItemAt(entry->mIndex)->pointer()
+ entry->mOffset,
copy);
entry->mOffset += copy;
entry->mSize -= copy;
if (entry->mSize == 0) {
mSource->onBufferAvailable(entry->mIndex);
mQueue.erase(mQueue.begin());
entry = NULL;
}
return copy;
}
Commit Message: NuPlayerStreamListener: NULL and bounds check before memcpy
Bug: 27533704
Change-Id: I992a7709b92b1cbc3114c97bec48a3fc5b22ba6e
CWE ID: CWE-264 | ssize_t NuPlayer::NuPlayerStreamListener::read(
void *data, size_t size, sp<AMessage> *extra) {
CHECK_GT(size, 0u);
extra->clear();
Mutex::Autolock autoLock(mLock);
if (mEOS) {
return 0;
}
if (mQueue.empty()) {
mSendDataNotification = true;
return -EWOULDBLOCK;
}
QueueEntry *entry = &*mQueue.begin();
if (entry->mIsCommand) {
switch (entry->mCommand) {
case EOS:
{
mQueue.erase(mQueue.begin());
entry = NULL;
mEOS = true;
return 0;
}
case DISCONTINUITY:
{
*extra = entry->mExtra;
mQueue.erase(mQueue.begin());
entry = NULL;
return INFO_DISCONTINUITY;
}
default:
TRESPASS();
break;
}
}
size_t copy = entry->mSize;
if (copy > size) {
copy = size;
}
if (entry->mIndex >= mBuffers.size()) {
return ERROR_MALFORMED;
}
sp<IMemory> mem = mBuffers.editItemAt(entry->mIndex);
if (mem == NULL || mem->size() < copy || mem->size() - copy < entry->mOffset) {
return ERROR_MALFORMED;
}
memcpy(data,
(const uint8_t *)mem->pointer()
+ entry->mOffset,
copy);
entry->mOffset += copy;
entry->mSize -= copy;
if (entry->mSize == 0) {
mSource->onBufferAvailable(entry->mIndex);
mQueue.erase(mQueue.begin());
entry = NULL;
}
return copy;
}
| 173,884 |
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 MessageService::OpenChannelToExtension(
int source_process_id, int source_routing_id, int receiver_port_id,
const std::string& source_extension_id,
const std::string& target_extension_id,
const std::string& channel_name) {
content::RenderProcessHost* source =
content::RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
MessagePort* receiver = new ExtensionMessagePort(
GetExtensionProcess(profile, target_extension_id), MSG_ROUTING_CONTROL,
target_extension_id);
WebContents* source_contents = tab_util::GetWebContentsByID(
source_process_id, source_routing_id);
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue(
source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS));
base::JSONWriter::Write(tab_value.get(), &tab_json);
}
OpenChannelParams* params = new OpenChannelParams(source, tab_json, receiver,
receiver_port_id,
source_extension_id,
target_extension_id,
channel_name);
if (MaybeAddPendingOpenChannelTask(profile, params)) {
return;
}
OpenChannelImpl(scoped_ptr<OpenChannelParams>(params));
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void MessageService::OpenChannelToExtension(
int source_process_id, int source_routing_id, int receiver_port_id,
const std::string& source_extension_id,
const std::string& target_extension_id,
const std::string& channel_name) {
content::RenderProcessHost* source =
content::RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext());
MessagePort* receiver = new ExtensionMessagePort(
GetExtensionProcess(profile, target_extension_id), MSG_ROUTING_CONTROL,
target_extension_id);
WebContents* source_contents = tab_util::GetWebContentsByID(
source_process_id, source_routing_id);
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue(
source_contents));
base::JSONWriter::Write(tab_value.get(), &tab_json);
}
OpenChannelParams* params = new OpenChannelParams(source, tab_json, receiver,
receiver_port_id,
source_extension_id,
target_extension_id,
channel_name);
if (MaybeAddPendingOpenChannelTask(profile, params)) {
return;
}
OpenChannelImpl(scoped_ptr<OpenChannelParams>(params));
}
| 171,446 |
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 ProfilingService::DumpProcessesForTracing(
bool keep_small_allocations,
bool strip_path_from_mapped_files,
DumpProcessesForTracingCallback callback) {
memory_instrumentation::MemoryInstrumentation::GetInstance()
->GetVmRegionsForHeapProfiler(base::Bind(
&ProfilingService::OnGetVmRegionsCompleteForDumpProcessesForTracing,
weak_factory_.GetWeakPtr(), keep_small_allocations,
strip_path_from_mapped_files, base::Passed(&callback)));
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void ProfilingService::DumpProcessesForTracing(
bool keep_small_allocations,
bool strip_path_from_mapped_files,
DumpProcessesForTracingCallback callback) {
if (!helper_) {
context()->connector()->BindInterface(
resource_coordinator::mojom::kServiceName, &helper_);
}
helper_->GetVmRegionsForHeapProfiler(base::Bind(
&ProfilingService::OnGetVmRegionsCompleteForDumpProcessesForTracing,
weak_factory_.GetWeakPtr(), keep_small_allocations,
strip_path_from_mapped_files, base::Passed(&callback)));
}
| 172,913 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
struct dev_pagemap *pgmap = NULL;
int nr_start = *nr, ret = 0;
pte_t *ptep, *ptem;
ptem = ptep = pte_offset_map(&pmd, addr);
do {
pte_t pte = gup_get_pte(ptep);
struct page *head, *page;
/*
* Similar to the PMD case below, NUMA hinting must take slow
* path using the pte_protnone check.
*/
if (pte_protnone(pte))
goto pte_unmap;
if (!pte_access_permitted(pte, write))
goto pte_unmap;
if (pte_devmap(pte)) {
pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
if (unlikely(!pgmap)) {
undo_dev_pagemap(nr, nr_start, pages);
goto pte_unmap;
}
} else if (pte_special(pte))
goto pte_unmap;
VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
page = pte_page(pte);
head = compound_head(page);
if (!page_cache_get_speculative(head))
goto pte_unmap;
if (unlikely(pte_val(pte) != pte_val(*ptep))) {
put_page(head);
goto pte_unmap;
}
VM_BUG_ON_PAGE(compound_head(page) != head, page);
SetPageReferenced(page);
pages[*nr] = page;
(*nr)++;
} while (ptep++, addr += PAGE_SIZE, addr != end);
ret = 1;
pte_unmap:
if (pgmap)
put_dev_pagemap(pgmap);
pte_unmap(ptem);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
struct dev_pagemap *pgmap = NULL;
int nr_start = *nr, ret = 0;
pte_t *ptep, *ptem;
ptem = ptep = pte_offset_map(&pmd, addr);
do {
pte_t pte = gup_get_pte(ptep);
struct page *head, *page;
/*
* Similar to the PMD case below, NUMA hinting must take slow
* path using the pte_protnone check.
*/
if (pte_protnone(pte))
goto pte_unmap;
if (!pte_access_permitted(pte, write))
goto pte_unmap;
if (pte_devmap(pte)) {
pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
if (unlikely(!pgmap)) {
undo_dev_pagemap(nr, nr_start, pages);
goto pte_unmap;
}
} else if (pte_special(pte))
goto pte_unmap;
VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
page = pte_page(pte);
head = try_get_compound_head(page, 1);
if (!head)
goto pte_unmap;
if (unlikely(pte_val(pte) != pte_val(*ptep))) {
put_page(head);
goto pte_unmap;
}
VM_BUG_ON_PAGE(compound_head(page) != head, page);
SetPageReferenced(page);
pages[*nr] = page;
(*nr)++;
} while (ptep++, addr += PAGE_SIZE, addr != end);
ret = 1;
pte_unmap:
if (pgmap)
put_dev_pagemap(pgmap);
pte_unmap(ptem);
return ret;
}
| 170,228 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dump_threads(void)
{
FILE *fp;
char time_buf[26];
element e;
vrrp_t *vrrp;
char *file_name;
file_name = make_file_name("/tmp/thread_dump.dat",
"vrrp",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
fp = fopen(file_name, "a");
FREE(file_name);
set_time_now();
ctime_r(&time_now.tv_sec, time_buf);
fprintf(fp, "\n%.19s.%6.6ld: Thread dump\n", time_buf, time_now.tv_usec);
dump_thread_data(master, fp);
fprintf(fp, "alloc = %lu\n", master->alloc);
fprintf(fp, "\n");
LIST_FOREACH(vrrp_data->vrrp, vrrp, e) {
ctime_r(&vrrp->sands.tv_sec, time_buf);
fprintf(fp, "VRRP instance %s, sands %.19s.%6.6lu, status %s\n", vrrp->iname, time_buf, vrrp->sands.tv_usec,
vrrp->state == VRRP_STATE_INIT ? "INIT" :
vrrp->state == VRRP_STATE_BACK ? "BACKUP" :
vrrp->state == VRRP_STATE_MAST ? "MASTER" :
vrrp->state == VRRP_STATE_FAULT ? "FAULT" :
vrrp->state == VRRP_STATE_STOP ? "STOP" :
vrrp->state == VRRP_DISPATCHER ? "DISPATCHER" : "unknown");
}
fclose(fp);
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | dump_threads(void)
{
FILE *fp;
char time_buf[26];
element e;
vrrp_t *vrrp;
char *file_name;
file_name = make_file_name("/tmp/thread_dump.dat",
"vrrp",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
fp = fopen_safe(file_name, "a");
FREE(file_name);
set_time_now();
ctime_r(&time_now.tv_sec, time_buf);
fprintf(fp, "\n%.19s.%6.6ld: Thread dump\n", time_buf, time_now.tv_usec);
dump_thread_data(master, fp);
fprintf(fp, "alloc = %lu\n", master->alloc);
fprintf(fp, "\n");
LIST_FOREACH(vrrp_data->vrrp, vrrp, e) {
ctime_r(&vrrp->sands.tv_sec, time_buf);
fprintf(fp, "VRRP instance %s, sands %.19s.%6.6lu, status %s\n", vrrp->iname, time_buf, vrrp->sands.tv_usec,
vrrp->state == VRRP_STATE_INIT ? "INIT" :
vrrp->state == VRRP_STATE_BACK ? "BACKUP" :
vrrp->state == VRRP_STATE_MAST ? "MASTER" :
vrrp->state == VRRP_STATE_FAULT ? "FAULT" :
vrrp->state == VRRP_STATE_STOP ? "STOP" :
vrrp->state == VRRP_DISPATCHER ? "DISPATCHER" : "unknown");
}
fclose(fp);
}
| 168,993 |
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: Resource::~Resource() {
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | Resource::~Resource() {
ResourceTracker::Get()->ResourceDestroyed(this);
}
| 170,415 |
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: hook_print (struct t_weechat_plugin *plugin, struct t_gui_buffer *buffer,
const char *tags, const char *message, int strip_colors,
t_hook_callback_print *callback, void *callback_data)
{
struct t_hook *new_hook;
struct t_hook_print *new_hook_print;
if (!callback)
return NULL;
new_hook = malloc (sizeof (*new_hook));
if (!new_hook)
return NULL;
new_hook_print = malloc (sizeof (*new_hook_print));
if (!new_hook_print)
{
rc = (int) (HOOK_CONNECT(ptr_hook, gnutls_cb))
(ptr_hook->callback_data, tls_session, req_ca, nreq,
pk_algos, pk_algos_len, answer);
break;
}
ptr_hook = ptr_hook->next_hook;
new_hook->hook_data = new_hook_print;
new_hook_print->callback = callback;
new_hook_print->buffer = buffer;
if (tags)
{
new_hook_print->tags_array = string_split (tags, ",", 0, 0,
&new_hook_print->tags_count);
}
else
{
new_hook_print->tags_count = 0;
new_hook_print->tags_array = NULL;
}
new_hook_print->message = (message) ? strdup (message) : NULL;
new_hook_print->strip_colors = strip_colors;
hook_add_to_list (new_hook);
return new_hook;
}
Commit Message:
CWE ID: CWE-20 | hook_print (struct t_weechat_plugin *plugin, struct t_gui_buffer *buffer,
const char *tags, const char *message, int strip_colors,
t_hook_callback_print *callback, void *callback_data)
{
struct t_hook *new_hook;
struct t_hook_print *new_hook_print;
if (!callback)
return NULL;
new_hook = malloc (sizeof (*new_hook));
if (!new_hook)
return NULL;
new_hook_print = malloc (sizeof (*new_hook_print));
if (!new_hook_print)
{
rc = (int) (HOOK_CONNECT(ptr_hook, gnutls_cb))
(ptr_hook->callback_data, tls_session, req_ca, nreq,
pk_algos, pk_algos_len, answer,
WEECHAT_HOOK_CONNECT_GNUTLS_CB_SET_CERT);
break;
}
ptr_hook = ptr_hook->next_hook;
new_hook->hook_data = new_hook_print;
new_hook_print->callback = callback;
new_hook_print->buffer = buffer;
if (tags)
{
new_hook_print->tags_array = string_split (tags, ",", 0, 0,
&new_hook_print->tags_count);
}
else
{
new_hook_print->tags_count = 0;
new_hook_print->tags_array = NULL;
}
new_hook_print->message = (message) ? strdup (message) : NULL;
new_hook_print->strip_colors = strip_colors;
hook_add_to_list (new_hook);
return new_hook;
}
| 164,711 |
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 DebuggerAttachFunction::RunAsync() {
std::unique_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsAgentHost::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (FindClientHost()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
new ExtensionDevToolsClientHost(GetProfile(), agent_host_.get(),
extension()->id(), extension()->name(),
debuggee_);
SendResponse(true);
return true;
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | bool DebuggerAttachFunction::RunAsync() {
std::unique_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsAgentHost::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (FindClientHost()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
auto host = std::make_unique<ExtensionDevToolsClientHost>(
GetProfile(), agent_host_.get(), extension()->id(), extension()->name(),
debuggee_);
if (!host->Attach()) {
FormatErrorMessage(keys::kRestrictedError);
return false;
}
host.release(); // An attached client host manages its own lifetime.
SendResponse(true);
return true;
}
| 173,239 |
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: ConflictResolver::ProcessSimpleConflict(WriteTransaction* trans,
const Id& id,
const Cryptographer* cryptographer,
StatusController* status) {
MutableEntry entry(trans, syncable::GET_BY_ID, id);
CHECK(entry.good());
if (!entry.Get(syncable::IS_UNAPPLIED_UPDATE) ||
!entry.Get(syncable::IS_UNSYNCED)) {
return NO_SYNC_PROGRESS;
}
if (entry.Get(syncable::IS_DEL) && entry.Get(syncable::SERVER_IS_DEL)) {
entry.Put(syncable::IS_UNSYNCED, false);
entry.Put(syncable::IS_UNAPPLIED_UPDATE, false);
return NO_SYNC_PROGRESS;
}
if (!entry.Get(syncable::SERVER_IS_DEL)) {
bool name_matches = entry.Get(syncable::NON_UNIQUE_NAME) ==
entry.Get(syncable::SERVER_NON_UNIQUE_NAME);
bool parent_matches = entry.Get(syncable::PARENT_ID) ==
entry.Get(syncable::SERVER_PARENT_ID);
bool entry_deleted = entry.Get(syncable::IS_DEL);
syncable::Id server_prev_id = entry.ComputePrevIdFromServerPosition(
entry.Get(syncable::SERVER_PARENT_ID));
bool needs_reinsertion = !parent_matches ||
server_prev_id != entry.Get(syncable::PREV_ID);
DVLOG_IF(1, needs_reinsertion) << "Insertion needed, server prev id "
<< " is " << server_prev_id << ", local prev id is "
<< entry.Get(syncable::PREV_ID);
const sync_pb::EntitySpecifics& specifics =
entry.Get(syncable::SPECIFICS);
const sync_pb::EntitySpecifics& server_specifics =
entry.Get(syncable::SERVER_SPECIFICS);
const sync_pb::EntitySpecifics& base_server_specifics =
entry.Get(syncable::BASE_SERVER_SPECIFICS);
std::string decrypted_specifics, decrypted_server_specifics;
bool specifics_match = false;
bool server_encrypted_with_default_key = false;
if (specifics.has_encrypted()) {
DCHECK(cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted()));
decrypted_specifics = cryptographer->DecryptToString(
specifics.encrypted());
} else {
decrypted_specifics = specifics.SerializeAsString();
}
if (server_specifics.has_encrypted()) {
server_encrypted_with_default_key =
cryptographer->CanDecryptUsingDefaultKey(
server_specifics.encrypted());
decrypted_server_specifics = cryptographer->DecryptToString(
server_specifics.encrypted());
} else {
decrypted_server_specifics = server_specifics.SerializeAsString();
}
if (decrypted_server_specifics == decrypted_specifics &&
server_encrypted_with_default_key == specifics.has_encrypted()) {
specifics_match = true;
}
bool base_server_specifics_match = false;
if (server_specifics.has_encrypted() &&
IsRealDataType(GetModelTypeFromSpecifics(base_server_specifics))) {
std::string decrypted_base_server_specifics;
if (!base_server_specifics.has_encrypted()) {
decrypted_base_server_specifics =
base_server_specifics.SerializeAsString();
} else {
decrypted_base_server_specifics = cryptographer->DecryptToString(
base_server_specifics.encrypted());
}
if (decrypted_server_specifics == decrypted_base_server_specifics)
base_server_specifics_match = true;
}
if (entry.GetModelType() == syncable::NIGORI) {
sync_pb::EntitySpecifics specifics =
entry.Get(syncable::SERVER_SPECIFICS);
sync_pb::NigoriSpecifics* server_nigori = specifics.mutable_nigori();
cryptographer->UpdateNigoriFromEncryptedTypes(server_nigori);
if (cryptographer->is_ready()) {
cryptographer->GetKeys(server_nigori->mutable_encrypted());
server_nigori->set_using_explicit_passphrase(
entry.Get(syncable::SPECIFICS).nigori().
using_explicit_passphrase());
}
if (entry.Get(syncable::SPECIFICS).nigori().sync_tabs()) {
server_nigori->set_sync_tabs(true);
}
entry.Put(syncable::SPECIFICS, specifics);
DVLOG(1) << "Resolving simple conflict, merging nigori nodes: " << entry;
status->increment_num_server_overwrites();
OverwriteServerChanges(trans, &entry);
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
NIGORI_MERGE,
CONFLICT_RESOLUTION_SIZE);
} else if (!entry_deleted && name_matches && parent_matches &&
specifics_match && !needs_reinsertion) {
DVLOG(1) << "Resolving simple conflict, everything matches, ignoring "
<< "changes for: " << entry;
OverwriteServerChanges(trans, &entry);
IgnoreLocalChanges(&entry);
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
CHANGES_MATCH,
CONFLICT_RESOLUTION_SIZE);
} else if (base_server_specifics_match) {
DVLOG(1) << "Resolving simple conflict, ignoring server encryption "
<< " changes for: " << entry;
status->increment_num_server_overwrites();
OverwriteServerChanges(trans, &entry);
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
IGNORE_ENCRYPTION,
CONFLICT_RESOLUTION_SIZE);
} else if (entry_deleted || !name_matches || !parent_matches) {
OverwriteServerChanges(trans, &entry);
status->increment_num_server_overwrites();
DVLOG(1) << "Resolving simple conflict, overwriting server changes "
<< "for: " << entry;
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
OVERWRITE_SERVER,
CONFLICT_RESOLUTION_SIZE);
} else {
DVLOG(1) << "Resolving simple conflict, ignoring local changes for: "
<< entry;
IgnoreLocalChanges(&entry);
status->increment_num_local_overwrites();
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
OVERWRITE_LOCAL,
CONFLICT_RESOLUTION_SIZE);
}
entry.Put(syncable::BASE_SERVER_SPECIFICS, sync_pb::EntitySpecifics());
return SYNC_PROGRESS;
} else { // SERVER_IS_DEL is true
if (entry.Get(syncable::IS_DIR)) {
Directory::ChildHandles children;
trans->directory()->GetChildHandlesById(trans,
entry.Get(syncable::ID),
&children);
if (0 != children.size()) {
DVLOG(1) << "Entry is a server deleted directory with local contents, "
<< "should be a hierarchy conflict. (race condition).";
return NO_SYNC_PROGRESS;
}
}
if (!entry.Get(syncable::UNIQUE_CLIENT_TAG).empty()) {
DCHECK_EQ(entry.Get(syncable::SERVER_VERSION), 0) << "For the server to "
"know to re-create, client-tagged items should revert to version 0 "
"when server-deleted.";
OverwriteServerChanges(trans, &entry);
status->increment_num_server_overwrites();
DVLOG(1) << "Resolving simple conflict, undeleting server entry: "
<< entry;
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
OVERWRITE_SERVER,
CONFLICT_RESOLUTION_SIZE);
entry.Put(syncable::SERVER_VERSION, 0);
entry.Put(syncable::BASE_VERSION, 0);
} else {
SyncerUtil::SplitServerInformationIntoNewEntry(trans, &entry);
MutableEntry server_update(trans, syncable::GET_BY_ID, id);
CHECK(server_update.good());
CHECK(server_update.Get(syncable::META_HANDLE) !=
entry.Get(syncable::META_HANDLE))
<< server_update << entry;
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
UNDELETE,
CONFLICT_RESOLUTION_SIZE);
}
return SYNC_PROGRESS;
}
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | ConflictResolver::ProcessSimpleConflict(WriteTransaction* trans,
const Id& id,
const Cryptographer* cryptographer,
StatusController* status) {
MutableEntry entry(trans, syncable::GET_BY_ID, id);
CHECK(entry.good());
if (!entry.Get(syncable::IS_UNAPPLIED_UPDATE) ||
!entry.Get(syncable::IS_UNSYNCED)) {
return NO_SYNC_PROGRESS;
}
if (entry.Get(syncable::IS_DEL) && entry.Get(syncable::SERVER_IS_DEL)) {
entry.Put(syncable::IS_UNSYNCED, false);
entry.Put(syncable::IS_UNAPPLIED_UPDATE, false);
return NO_SYNC_PROGRESS;
}
if (!entry.Get(syncable::SERVER_IS_DEL)) {
bool name_matches = entry.Get(syncable::NON_UNIQUE_NAME) ==
entry.Get(syncable::SERVER_NON_UNIQUE_NAME);
bool parent_matches = entry.Get(syncable::PARENT_ID) ==
entry.Get(syncable::SERVER_PARENT_ID);
bool entry_deleted = entry.Get(syncable::IS_DEL);
syncable::Id server_prev_id = entry.ComputePrevIdFromServerPosition(
entry.Get(syncable::SERVER_PARENT_ID));
bool needs_reinsertion = !parent_matches ||
server_prev_id != entry.Get(syncable::PREV_ID);
DVLOG_IF(1, needs_reinsertion) << "Insertion needed, server prev id "
<< " is " << server_prev_id << ", local prev id is "
<< entry.Get(syncable::PREV_ID);
const sync_pb::EntitySpecifics& specifics =
entry.Get(syncable::SPECIFICS);
const sync_pb::EntitySpecifics& server_specifics =
entry.Get(syncable::SERVER_SPECIFICS);
const sync_pb::EntitySpecifics& base_server_specifics =
entry.Get(syncable::BASE_SERVER_SPECIFICS);
std::string decrypted_specifics, decrypted_server_specifics;
bool specifics_match = false;
bool server_encrypted_with_default_key = false;
if (specifics.has_encrypted()) {
DCHECK(cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted()));
decrypted_specifics = cryptographer->DecryptToString(
specifics.encrypted());
} else {
decrypted_specifics = specifics.SerializeAsString();
}
if (server_specifics.has_encrypted()) {
server_encrypted_with_default_key =
cryptographer->CanDecryptUsingDefaultKey(
server_specifics.encrypted());
decrypted_server_specifics = cryptographer->DecryptToString(
server_specifics.encrypted());
} else {
decrypted_server_specifics = server_specifics.SerializeAsString();
}
if (decrypted_server_specifics == decrypted_specifics &&
server_encrypted_with_default_key == specifics.has_encrypted()) {
specifics_match = true;
}
bool base_server_specifics_match = false;
if (server_specifics.has_encrypted() &&
IsRealDataType(GetModelTypeFromSpecifics(base_server_specifics))) {
std::string decrypted_base_server_specifics;
if (!base_server_specifics.has_encrypted()) {
decrypted_base_server_specifics =
base_server_specifics.SerializeAsString();
} else {
decrypted_base_server_specifics = cryptographer->DecryptToString(
base_server_specifics.encrypted());
}
if (decrypted_server_specifics == decrypted_base_server_specifics)
base_server_specifics_match = true;
}
if (entry.GetModelType() == syncable::NIGORI) {
sync_pb::EntitySpecifics specifics =
entry.Get(syncable::SERVER_SPECIFICS);
sync_pb::NigoriSpecifics* server_nigori = specifics.mutable_nigori();
cryptographer->UpdateNigoriFromEncryptedTypes(server_nigori);
if (cryptographer->is_ready()) {
cryptographer->GetKeys(server_nigori->mutable_encrypted());
server_nigori->set_using_explicit_passphrase(
entry.Get(syncable::SPECIFICS).nigori().
using_explicit_passphrase());
}
entry.Put(syncable::SPECIFICS, specifics);
DVLOG(1) << "Resolving simple conflict, merging nigori nodes: " << entry;
status->increment_num_server_overwrites();
OverwriteServerChanges(trans, &entry);
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
NIGORI_MERGE,
CONFLICT_RESOLUTION_SIZE);
} else if (!entry_deleted && name_matches && parent_matches &&
specifics_match && !needs_reinsertion) {
DVLOG(1) << "Resolving simple conflict, everything matches, ignoring "
<< "changes for: " << entry;
OverwriteServerChanges(trans, &entry);
IgnoreLocalChanges(&entry);
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
CHANGES_MATCH,
CONFLICT_RESOLUTION_SIZE);
} else if (base_server_specifics_match) {
DVLOG(1) << "Resolving simple conflict, ignoring server encryption "
<< " changes for: " << entry;
status->increment_num_server_overwrites();
OverwriteServerChanges(trans, &entry);
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
IGNORE_ENCRYPTION,
CONFLICT_RESOLUTION_SIZE);
} else if (entry_deleted || !name_matches || !parent_matches) {
OverwriteServerChanges(trans, &entry);
status->increment_num_server_overwrites();
DVLOG(1) << "Resolving simple conflict, overwriting server changes "
<< "for: " << entry;
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
OVERWRITE_SERVER,
CONFLICT_RESOLUTION_SIZE);
} else {
DVLOG(1) << "Resolving simple conflict, ignoring local changes for: "
<< entry;
IgnoreLocalChanges(&entry);
status->increment_num_local_overwrites();
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
OVERWRITE_LOCAL,
CONFLICT_RESOLUTION_SIZE);
}
entry.Put(syncable::BASE_SERVER_SPECIFICS, sync_pb::EntitySpecifics());
return SYNC_PROGRESS;
} else { // SERVER_IS_DEL is true
if (entry.Get(syncable::IS_DIR)) {
Directory::ChildHandles children;
trans->directory()->GetChildHandlesById(trans,
entry.Get(syncable::ID),
&children);
if (0 != children.size()) {
DVLOG(1) << "Entry is a server deleted directory with local contents, "
<< "should be a hierarchy conflict. (race condition).";
return NO_SYNC_PROGRESS;
}
}
if (!entry.Get(syncable::UNIQUE_CLIENT_TAG).empty()) {
DCHECK_EQ(entry.Get(syncable::SERVER_VERSION), 0) << "For the server to "
"know to re-create, client-tagged items should revert to version 0 "
"when server-deleted.";
OverwriteServerChanges(trans, &entry);
status->increment_num_server_overwrites();
DVLOG(1) << "Resolving simple conflict, undeleting server entry: "
<< entry;
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
OVERWRITE_SERVER,
CONFLICT_RESOLUTION_SIZE);
entry.Put(syncable::SERVER_VERSION, 0);
entry.Put(syncable::BASE_VERSION, 0);
} else {
SyncerUtil::SplitServerInformationIntoNewEntry(trans, &entry);
MutableEntry server_update(trans, syncable::GET_BY_ID, id);
CHECK(server_update.good());
CHECK(server_update.Get(syncable::META_HANDLE) !=
entry.Get(syncable::META_HANDLE))
<< server_update << entry;
UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
UNDELETE,
CONFLICT_RESOLUTION_SIZE);
}
return SYNC_PROGRESS;
}
}
| 170,791 |
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 open_debug_log(void) {
/* don't do anything if we're not actually running... */
if(verify_config || test_scheduling == TRUE)
return OK;
/* don't do anything if we're not debugging */
if(debug_level == DEBUGL_NONE)
return OK;
if((debug_file_fp = fopen(debug_file, "a+")) == NULL)
return ERROR;
(void)fcntl(fileno(debug_file_fp), F_SETFD, FD_CLOEXEC);
return OK;
}
Commit Message: Merge branch 'maint'
CWE ID: CWE-264 | int open_debug_log(void) {
int open_debug_log(void)
{
int fh;
struct stat st;
/* don't do anything if we're not actually running... */
if(verify_config || test_scheduling == TRUE)
return OK;
/* don't do anything if we're not debugging */
if(debug_level == DEBUGL_NONE)
return OK;
if ((fh = open(debug_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1)
return ERROR;
if((debug_file_fp = fdopen(fh, "a+")) == NULL)
return ERROR;
if ((fstat(fh, &st)) == -1) {
debug_file_fp = NULL;
close(fh);
return ERROR;
}
if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) {
debug_file_fp = NULL;
close(fh);
return ERROR;
}
(void)fcntl(fh, F_SETFD, FD_CLOEXEC);
return OK;
}
| 166,859 |
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 SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
Commit Message: Add Android SDK version to crash reports.
Bug: 911669
Change-Id: I62a97d76a0b88099a5a42b93463307f03be9b3e2
Reviewed-on: https://chromium-review.googlesource.com/c/1361104
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: Peter Conn <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Michael van Ouwerkerk <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615851}
CWE ID: CWE-189 | void SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["sdk"] = base::StringPrintf("%d", info->sdk_int());
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
| 172,546 |
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 spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */
{
zend_fcall_info fci;
zend_fcall_info_cache fcic;
zval z_fname;
zval * zresource_ptr = &intern->u.file.zresource, *retval;
int result;
int num_args = pass_num_args + (arg2 ? 2 : 1);
zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0);
params[0] = &zresource_ptr;
if (arg2) {
params[1] = &arg2;
}
zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1));
ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
fci.object_ptr = NULL;
fci.function_name = &z_fname;
fci.retval_ptr_ptr = &retval;
fci.param_count = num_args;
fci.params = params;
fci.no_separation = 1;
fci.symbol_table = NULL;
fcic.initialized = 1;
fcic.function_handler = func_ptr;
fcic.calling_scope = NULL;
fcic.called_scope = NULL;
fcic.object_ptr = NULL;
result = zend_call_function(&fci, &fcic TSRMLS_CC);
if (result == FAILURE) {
RETVAL_FALSE;
} else {
ZVAL_ZVAL(return_value, retval, 1, 1);
}
efree(params);
return result;
} /* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */
{
zend_fcall_info fci;
zend_fcall_info_cache fcic;
zval z_fname;
zval * zresource_ptr = &intern->u.file.zresource, *retval;
int result;
int num_args = pass_num_args + (arg2 ? 2 : 1);
zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0);
params[0] = &zresource_ptr;
if (arg2) {
params[1] = &arg2;
}
zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1));
ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
fci.object_ptr = NULL;
fci.function_name = &z_fname;
fci.retval_ptr_ptr = &retval;
fci.param_count = num_args;
fci.params = params;
fci.no_separation = 1;
fci.symbol_table = NULL;
fcic.initialized = 1;
fcic.function_handler = func_ptr;
fcic.calling_scope = NULL;
fcic.called_scope = NULL;
fcic.object_ptr = NULL;
result = zend_call_function(&fci, &fcic TSRMLS_CC);
if (result == FAILURE) {
RETVAL_FALSE;
} else {
ZVAL_ZVAL(return_value, retval, 1, 1);
}
efree(params);
return result;
} /* }}} */
| 167,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: xfs_file_splice_write(
struct pipe_inode_info *pipe,
struct file *outfilp,
loff_t *ppos,
size_t count,
unsigned int flags)
{
struct inode *inode = outfilp->f_mapping->host;
struct xfs_inode *ip = XFS_I(inode);
int ioflags = 0;
ssize_t ret;
XFS_STATS_INC(xs_write_calls);
if (outfilp->f_mode & FMODE_NOCMTIME)
ioflags |= IO_INVIS;
if (XFS_FORCED_SHUTDOWN(ip->i_mount))
return -EIO;
xfs_ilock(ip, XFS_IOLOCK_EXCL);
trace_xfs_file_splice_write(ip, count, *ppos, ioflags);
ret = generic_file_splice_write(pipe, outfilp, ppos, count, flags);
if (ret > 0)
XFS_STATS_ADD(xs_write_bytes, ret);
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return ret;
}
Commit Message: ->splice_write() via ->write_iter()
iter_file_splice_write() - a ->splice_write() instance that gathers the
pipe buffers, builds a bio_vec-based iov_iter covering those and feeds
it to ->write_iter(). A bunch of simple cases coverted to that...
[AV: fixed the braino spotted by Cyrill]
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-264 | xfs_file_splice_write(
| 166,810 |
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 Browser::TabDetachedAt(TabContents* contents, int index) {
TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void Browser::TabDetachedAt(TabContents* contents, int index) {
void Browser::TabDetachedAt(WebContents* contents, int index) {
TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
}
| 171,507 |
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 __videobuf_mmap_mapper(struct videobuf_queue *q,
struct vm_area_struct *vma)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_mapping *map;
unsigned int first;
int retval;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED))
return -EINVAL;
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (NULL == q->bufs[first])
continue;
if (V4L2_MEMORY_MMAP != q->bufs[first]->memory)
continue;
if (q->bufs[first]->boff == offset)
break;
}
if (VIDEO_MAX_FRAME == first) {
dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n",
(vma->vm_pgoff << PAGE_SHIFT));
return -EINVAL;
}
/* create mapping + update buffer list */
map = q->bufs[first]->map = kmalloc(sizeof(struct videobuf_mapping),GFP_KERNEL);
if (NULL == map)
return -ENOMEM;
map->start = vma->vm_start;
map->end = vma->vm_end;
map->q = q;
q->bufs[first]->baddr = vma->vm_start;
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED;
vma->vm_private_data = map;
mem=q->bufs[first]->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
/* Try to remap memory */
retval=remap_vmalloc_range(vma, mem->vmalloc,0);
if (retval<0) {
dprintk(1,"mmap: postponing remap_vmalloc_range\n");
mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL);
if (!mem->vma) {
kfree(map);
q->bufs[first]->map=NULL;
return -ENOMEM;
}
memcpy(mem->vma,vma,sizeof(*vma));
}
dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n",
map,q,vma->vm_start,vma->vm_end,
(long int) q->bufs[first]->bsize,
vma->vm_pgoff,first);
videobuf_vm_open(vma);
return (0);
}
Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap
This is pretty serious bug. map->count is never initialized after the
call to kmalloc making the count start at some random trash value. The
end result is leaking videobufs.
Also, fix up the debug statements to print unsigned values.
Pushed to http://ifup.org/hg/v4l-dvb too
Signed-off-by: Brandon Philips <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | static int __videobuf_mmap_mapper(struct videobuf_queue *q,
struct vm_area_struct *vma)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_mapping *map;
unsigned int first;
int retval;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED))
return -EINVAL;
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (NULL == q->bufs[first])
continue;
if (V4L2_MEMORY_MMAP != q->bufs[first]->memory)
continue;
if (q->bufs[first]->boff == offset)
break;
}
if (VIDEO_MAX_FRAME == first) {
dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n",
(vma->vm_pgoff << PAGE_SHIFT));
return -EINVAL;
}
/* create mapping + update buffer list */
map = q->bufs[first]->map = kzalloc(sizeof(struct videobuf_mapping),GFP_KERNEL);
if (NULL == map)
return -ENOMEM;
map->start = vma->vm_start;
map->end = vma->vm_end;
map->q = q;
q->bufs[first]->baddr = vma->vm_start;
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED;
vma->vm_private_data = map;
mem=q->bufs[first]->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
/* Try to remap memory */
retval=remap_vmalloc_range(vma, mem->vmalloc,0);
if (retval<0) {
dprintk(1,"mmap: postponing remap_vmalloc_range\n");
mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL);
if (!mem->vma) {
kfree(map);
q->bufs[first]->map=NULL;
return -ENOMEM;
}
memcpy(mem->vma,vma,sizeof(*vma));
}
dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n",
map,q,vma->vm_start,vma->vm_end,
(long int) q->bufs[first]->bsize,
vma->vm_pgoff,first);
videobuf_vm_open(vma);
return (0);
}
| 168,917 |
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: t1_parse_font_matrix( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 0 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale );
/* we need to scale the values by 1.0/temp_scale */
if ( temp_scale != 0x10000L )
{
temp[0] = FT_DivFix( temp[0], temp_scale );
temp[1] = FT_DivFix( temp[1], temp_scale );
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
}
Commit Message:
CWE ID: CWE-20 | t1_parse_font_matrix( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale );
/* we need to scale the values by 1.0/temp_scale */
if ( temp_scale != 0x10000L )
{
temp[0] = FT_DivFix( temp[0], temp_scale );
temp[1] = FT_DivFix( temp[1], temp_scale );
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
}
| 165,342 |
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 btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
pthread_mutex_lock(&slot_lock);
rfc_slot_t *slot = find_rfc_slot_by_id(user_id);
if (!slot)
goto out;
bool need_close = false;
if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
if (slot->f.connected) {
int size = 0;
if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size))
pthread_mutex_unlock(&slot_lock);
BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
} else {
LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (flags & SOCK_THREAD_FD_WR) {
if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
int size = 0;
if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size)
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
}
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 | void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
pthread_mutex_lock(&slot_lock);
rfc_slot_t *slot = find_rfc_slot_by_id(user_id);
if (!slot)
goto out;
bool need_close = false;
if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
if (slot->f.connected) {
int size = 0;
if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (TEMP_FAILURE_RETRY(ioctl(slot->fd, FIONREAD, &size)) == 0 && size)) {
BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
}
} else {
LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (flags & SOCK_THREAD_FD_WR) {
if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
int size = 0;
if (need_close || TEMP_FAILURE_RETRY(ioctl(slot->fd, FIONREAD, &size)) != 0 || !size)
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
}
| 173,457 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Chunk::Chunk( ContainerChunk* parent, RIFF_MetaHandler* handler, bool skip, ChunkType c )
{
chunkType = c; // base class assumption
this->parent = parent;
this->oldSize = 0;
this->hasChange = false; // [2414649] valid assumption at creation time
XMP_IO* file = handler->parent->ioRef;
this->oldPos = file->Offset();
this->id = XIO::ReadUns32_LE( file );
this->oldSize = XIO::ReadUns32_LE( file ) + 8;
XMP_Int64 chunkEnd = this->oldPos + this->oldSize;
if ( parent != 0 ) chunkLimit = parent->oldPos + parent->oldSize;
if ( chunkEnd > chunkLimit ) {
bool isUpdate = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenForUpdate );
bool repairFile = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenRepairFile );
if ( (! isUpdate) || (repairFile && (parent == 0)) ) {
this->oldSize = chunkLimit - this->oldPos;
} else {
XMP_Throw ( "Bad RIFF chunk size", kXMPErr_BadFileFormat );
}
}
this->newSize = this->oldSize;
this->needSizeFix = false;
if ( skip ) file->Seek ( (this->oldSize - 8), kXMP_SeekFromCurrent );
if ( this->parent != NULL )
{
this->parent->children.push_back( this );
if( this->chunkType == chunk_VALUE )
this->parent->childmap.insert( std::make_pair( this->id, (ValueChunk*) this ) );
}
}
Commit Message:
CWE ID: CWE-190 | Chunk::Chunk( ContainerChunk* parent, RIFF_MetaHandler* handler, bool skip, ChunkType c )
{
chunkType = c; // base class assumption
this->parent = parent;
this->oldSize = 0;
this->hasChange = false; // [2414649] valid assumption at creation time
XMP_IO* file = handler->parent->ioRef;
this->oldPos = file->Offset();
this->id = XIO::ReadUns32_LE( file );
this->oldSize = XIO::ReadUns32_LE( file );
this->oldSize += 8;
XMP_Int64 chunkEnd = this->oldPos + this->oldSize;
if ( parent != 0 ) chunkLimit = parent->oldPos + parent->oldSize;
if ( chunkEnd > chunkLimit ) {
bool isUpdate = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenForUpdate );
bool repairFile = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenRepairFile );
if ( (! isUpdate) || (repairFile && (parent == 0)) ) {
this->oldSize = chunkLimit - this->oldPos;
} else {
XMP_Throw ( "Bad RIFF chunk size", kXMPErr_BadFileFormat );
}
}
this->newSize = this->oldSize;
this->needSizeFix = false;
if ( skip ) file->Seek ( (this->oldSize - 8), kXMP_SeekFromCurrent );
if ( this->parent != NULL )
{
this->parent->children.push_back( this );
if( this->chunkType == chunk_VALUE )
this->parent->childmap.insert( std::make_pair( this->id, (ValueChunk*) this ) );
}
}
| 165,369 |
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 ID3::removeUnsynchronizationV2_4(bool iTunesHack) {
size_t oldSize = mSize;
size_t offset = 0;
while (mSize >= 10 && offset <= mSize - 10) {
if (!memcmp(&mData[offset], "\0\0\0\0", 4)) {
break;
}
size_t dataSize;
if (iTunesHack) {
dataSize = U32_AT(&mData[offset + 4]);
} else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) {
return false;
}
if (dataSize > mSize - 10 - offset) {
return false;
}
uint16_t flags = U16_AT(&mData[offset + 8]);
uint16_t prevFlags = flags;
if (flags & 1) {
if (mSize < 14 || mSize - 14 < offset || dataSize < 4) {
return false;
}
memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14);
mSize -= 4;
dataSize -= 4;
flags &= ~1;
}
if ((flags & 2) && (dataSize >= 2)) {
size_t readOffset = offset + 11;
size_t writeOffset = offset + 11;
for (size_t i = 0; i + 1 < dataSize; ++i) {
if (mData[readOffset - 1] == 0xff
&& mData[readOffset] == 0x00) {
++readOffset;
--mSize;
--dataSize;
}
mData[writeOffset++] = mData[readOffset++];
}
if (readOffset <= oldSize) {
memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset);
} else {
ALOGE("b/34618607 (%zu %zu %zu %zu)", readOffset, writeOffset, oldSize, mSize);
android_errorWriteLog(0x534e4554, "34618607");
}
}
flags &= ~2;
if (flags != prevFlags || iTunesHack) {
WriteSyncsafeInteger(&mData[offset + 4], dataSize);
mData[offset + 8] = flags >> 8;
mData[offset + 9] = flags & 0xff;
}
offset += 10 + dataSize;
}
memset(&mData[mSize], 0, oldSize - mSize);
return true;
}
Commit Message: Fix edge case when applying id3 unsynchronization
Bug: 63100526
Test: opened poc, other files
Change-Id: I0a51a2a11d0ea84ede0c075de650a7118f0e00c5
(cherry picked from commit 3e70296461c5f260988ab21854a6f43fdafea764)
CWE ID: CWE-200 | bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) {
size_t oldSize = mSize;
size_t offset = 0;
while (mSize >= 10 && offset <= mSize - 10) {
if (!memcmp(&mData[offset], "\0\0\0\0", 4)) {
break;
}
size_t dataSize;
if (iTunesHack) {
dataSize = U32_AT(&mData[offset + 4]);
} else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) {
return false;
}
if (dataSize > mSize - 10 - offset) {
return false;
}
uint16_t flags = U16_AT(&mData[offset + 8]);
uint16_t prevFlags = flags;
if (flags & 1) {
if (mSize < 14 || mSize - 14 < offset || dataSize < 4) {
return false;
}
memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14);
mSize -= 4;
dataSize -= 4;
flags &= ~1;
}
if ((flags & 2) && (dataSize >= 2)) {
size_t readOffset = offset + 11;
size_t writeOffset = offset + 11;
for (size_t i = 0; i + 1 < dataSize; ++i) {
if (mData[readOffset - 1] == 0xff
&& mData[readOffset] == 0x00) {
++readOffset;
--mSize;
--dataSize;
}
if (i + 1 < dataSize) {
// Only move data if there's actually something to move.
// This handles the special case of the data being only [0xff, 0x00]
// which should be converted to just 0xff if unsynchronization is on.
mData[writeOffset++] = mData[readOffset++];
}
}
if (readOffset <= oldSize) {
memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset);
} else {
ALOGE("b/34618607 (%zu %zu %zu %zu)", readOffset, writeOffset, oldSize, mSize);
android_errorWriteLog(0x534e4554, "34618607");
}
}
flags &= ~2;
if (flags != prevFlags || iTunesHack) {
WriteSyncsafeInteger(&mData[offset + 4], dataSize);
mData[offset + 8] = flags >> 8;
mData[offset + 9] = flags & 0xff;
}
offset += 10 + dataSize;
}
memset(&mData[mSize], 0, oldSize - mSize);
return true;
}
| 174,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: static int ipxitf_ioctl(unsigned int cmd, void __user *arg)
{
int rc = -EINVAL;
struct ifreq ifr;
int val;
switch (cmd) {
case SIOCSIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface_definition f;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
rc = -EINVAL;
if (sipx->sipx_family != AF_IPX)
break;
f.ipx_network = sipx->sipx_network;
memcpy(f.ipx_device, ifr.ifr_name,
sizeof(f.ipx_device));
memcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN);
f.ipx_dlink_type = sipx->sipx_type;
f.ipx_special = sipx->sipx_special;
if (sipx->sipx_action == IPX_DLTITF)
rc = ipxitf_delete(&f);
else
rc = ipxitf_create(&f);
break;
}
case SIOCGIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface *ipxif;
struct net_device *dev;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
dev = __dev_get_by_name(&init_net, ifr.ifr_name);
rc = -ENODEV;
if (!dev)
break;
ipxif = ipxitf_find_using_phys(dev,
ipx_map_frame_type(sipx->sipx_type));
rc = -EADDRNOTAVAIL;
if (!ipxif)
break;
sipx->sipx_family = AF_IPX;
sipx->sipx_network = ipxif->if_netnum;
memcpy(sipx->sipx_node, ipxif->if_node,
sizeof(sipx->sipx_node));
rc = -EFAULT;
if (copy_to_user(arg, &ifr, sizeof(ifr)))
break;
ipxitf_put(ipxif);
rc = 0;
break;
}
case SIOCAIPXITFCRT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_auto_create_interfaces = val;
break;
case SIOCAIPXPRISLT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_set_auto_select(val);
break;
}
return rc;
}
Commit Message: ipx: call ipxitf_put() in ioctl error path
We should call ipxitf_put() if the copy_to_user() fails.
Reported-by: 李强 <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static int ipxitf_ioctl(unsigned int cmd, void __user *arg)
{
int rc = -EINVAL;
struct ifreq ifr;
int val;
switch (cmd) {
case SIOCSIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface_definition f;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
rc = -EINVAL;
if (sipx->sipx_family != AF_IPX)
break;
f.ipx_network = sipx->sipx_network;
memcpy(f.ipx_device, ifr.ifr_name,
sizeof(f.ipx_device));
memcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN);
f.ipx_dlink_type = sipx->sipx_type;
f.ipx_special = sipx->sipx_special;
if (sipx->sipx_action == IPX_DLTITF)
rc = ipxitf_delete(&f);
else
rc = ipxitf_create(&f);
break;
}
case SIOCGIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface *ipxif;
struct net_device *dev;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
dev = __dev_get_by_name(&init_net, ifr.ifr_name);
rc = -ENODEV;
if (!dev)
break;
ipxif = ipxitf_find_using_phys(dev,
ipx_map_frame_type(sipx->sipx_type));
rc = -EADDRNOTAVAIL;
if (!ipxif)
break;
sipx->sipx_family = AF_IPX;
sipx->sipx_network = ipxif->if_netnum;
memcpy(sipx->sipx_node, ipxif->if_node,
sizeof(sipx->sipx_node));
rc = 0;
if (copy_to_user(arg, &ifr, sizeof(ifr)))
rc = -EFAULT;
ipxitf_put(ipxif);
break;
}
case SIOCAIPXITFCRT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_auto_create_interfaces = val;
break;
case SIOCAIPXPRISLT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_set_auto_select(val);
break;
}
return rc;
}
| 168,272 |
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 SocketStream::HandleCertificateError(int result) {
DCHECK(IsCertificateError(result));
SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get());
DCHECK(ssl_socket);
if (!context_.get())
return result;
if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) {
const HttpNetworkSession::Params* session_params =
context_->GetNetworkSessionParams();
if (session_params && session_params->ignore_certificate_errors)
return OK;
}
if (!delegate_)
return result;
SSLInfo ssl_info;
ssl_socket->GetSSLInfo(&ssl_info);
TransportSecurityState::DomainState domain_state;
const bool fatal = context_->transport_security_state() &&
context_->transport_security_state()->GetDomainState(url_.host(),
SSLConfigService::IsSNIAvailable(context_->ssl_config_service()),
&domain_state) &&
domain_state.ShouldSSLErrorsBeFatal();
delegate_->OnSSLCertificateError(this, ssl_info, fatal);
return ERR_IO_PENDING;
}
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 | int SocketStream::HandleCertificateError(int result) {
DCHECK(IsCertificateError(result));
SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get());
DCHECK(ssl_socket);
if (!context_)
return result;
if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) {
const HttpNetworkSession::Params* session_params =
context_->GetNetworkSessionParams();
if (session_params && session_params->ignore_certificate_errors)
return OK;
}
if (!delegate_)
return result;
SSLInfo ssl_info;
ssl_socket->GetSSLInfo(&ssl_info);
TransportSecurityState::DomainState domain_state;
const bool fatal = context_->transport_security_state() &&
context_->transport_security_state()->GetDomainState(url_.host(),
SSLConfigService::IsSNIAvailable(context_->ssl_config_service()),
&domain_state) &&
domain_state.ShouldSSLErrorsBeFatal();
delegate_->OnSSLCertificateError(this, ssl_info, fatal);
return ERR_IO_PENDING;
}
| 171,255 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: asn1_get_bit_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *bit_len)
{
int len_len, len_byte;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
len_byte = asn1_get_length_der (der, der_len, &len_len) - 1;
if (len_byte < 0)
return ASN1_DER_ERROR;
*ret_len = len_byte + len_len + 1;
*bit_len = len_byte * 8 - der[len_len];
if (str_size >= len_byte)
memcpy (str, der + len_len + 1, len_byte);
}
Commit Message:
CWE ID: CWE-189 | asn1_get_bit_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *bit_len)
{
int len_len = 0, len_byte;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
len_byte = asn1_get_length_der (der, der_len, &len_len) - 1;
if (len_byte < 0)
return ASN1_DER_ERROR;
*ret_len = len_byte + len_len + 1;
*bit_len = len_byte * 8 - der[len_len];
if (*bit_len <= 0)
return ASN1_DER_ERROR;
if (str_size >= len_byte)
memcpy (str, der + len_len + 1, len_byte);
}
| 165,177 |
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 write_version(
FILE *fp,
const char *fname,
const char *dirname,
xref_t *xref)
{
long start;
char *c, *new_fname, data;
FILE *new_fp;
start = ftell(fp);
/* Create file */
if ((c = strstr(fname, ".pdf")))
*c = '\0';
new_fname = malloc(strlen(fname) + strlen(dirname) + 16);
snprintf(new_fname, strlen(fname) + strlen(dirname) + 16,
"%s/%s-version-%d.pdf", dirname, fname, xref->version);
if (!(new_fp = fopen(new_fname, "w")))
{
ERR("Could not create file '%s'\n", new_fname);
fseek(fp, start, SEEK_SET);
free(new_fname);
return;
}
/* Copy original PDF */
fseek(fp, 0, SEEK_SET);
while (fread(&data, 1, 1, fp))
fwrite(&data, 1, 1, new_fp);
/* Emit an older startxref, refering to an older version. */
fprintf(new_fp, "\r\nstartxref\r\n%ld\r\n%%%%EOF", xref->start);
/* Clean */
fclose(new_fp);
free(new_fname);
fseek(fp, start, SEEK_SET);
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787 | static void write_version(
FILE *fp,
const char *fname,
const char *dirname,
xref_t *xref)
{
long start;
char *c, *new_fname, data;
FILE *new_fp;
start = ftell(fp);
/* Create file */
if ((c = strstr(fname, ".pdf")))
*c = '\0';
new_fname = safe_calloc(strlen(fname) + strlen(dirname) + 16);
snprintf(new_fname, strlen(fname) + strlen(dirname) + 16,
"%s/%s-version-%d.pdf", dirname, fname, xref->version);
if (!(new_fp = fopen(new_fname, "w")))
{
ERR("Could not create file '%s'\n", new_fname);
fseek(fp, start, SEEK_SET);
free(new_fname);
return;
}
/* Copy original PDF */
fseek(fp, 0, SEEK_SET);
while (fread(&data, 1, 1, fp))
fwrite(&data, 1, 1, new_fp);
/* Emit an older startxref, refering to an older version. */
fprintf(new_fp, "\r\nstartxref\r\n%ld\r\n%%%%EOF", xref->start);
/* Clean */
fclose(new_fp);
free(new_fname);
fseek(fp, start, SEEK_SET);
}
| 169,565 |
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_cmap8_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_Byte* is32;
FT_UInt32 length;
FT_UInt32 num_groups;
if ( table + 16 + 8192 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 )
FT_INVALID_TOO_SHORT;
is32 = table + 12;
p = is32 + 8192; /* skip `is32' array */
num_groups = TT_NEXT_ULONG( p );
if ( p + num_groups * 12 > valid->limit )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
FT_UInt32 n, start, end, start_id, count, last = 0;
for ( n = 0; n < num_groups; n++ )
{
FT_UInt hi, lo;
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;
count = (FT_UInt32)( end - start + 1 );
{
hi = (FT_UInt)( start >> 16 );
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 )
FT_INVALID_DATA;
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 )
FT_INVALID_DATA;
}
}
else
{
/* start_hi == 0; check that is32[i] is 0 for each i in */
/* the range [start..end] */
/* end_hi cannot be != 0! */
if ( end & ~0xFFFFU )
FT_INVALID_DATA;
for ( ; count > 0; count--, start++ )
{
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 )
FT_INVALID_DATA;
}
}
}
last = end;
}
Commit Message:
CWE ID: CWE-125 | tt_cmap8_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_Byte* is32;
FT_UInt32 length;
FT_UInt32 num_groups;
if ( table + 16 + 8192 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 )
FT_INVALID_TOO_SHORT;
is32 = table + 12;
p = is32 + 8192; /* skip `is32' array */
num_groups = TT_NEXT_ULONG( p );
/* p + num_groups * 12 > valid->limit ? */
if ( num_groups > (FT_UInt32)( valid->limit - p ) / 12 )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
FT_UInt32 n, start, end, start_id, count, last = 0;
for ( n = 0; n < num_groups; n++ )
{
FT_UInt hi, lo;
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 )
{
FT_UInt32 d = end - start;
/* start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ? */
if ( d > TT_VALID_GLYPH_COUNT( valid ) ||
start_id >= TT_VALID_GLYPH_COUNT( valid ) - d )
FT_INVALID_GLYPH_ID;
count = (FT_UInt32)( end - start + 1 );
{
hi = (FT_UInt)( start >> 16 );
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 )
FT_INVALID_DATA;
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 )
FT_INVALID_DATA;
}
}
else
{
/* start_hi == 0; check that is32[i] is 0 for each i in */
/* the range [start..end] */
/* end_hi cannot be != 0! */
if ( end & ~0xFFFFU )
FT_INVALID_DATA;
for ( ; count > 0; count--, start++ )
{
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 )
FT_INVALID_DATA;
}
}
}
last = end;
}
| 164,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
int new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
uint32_t new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
| 165,496 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ClientControlledShellSurface::OnBoundsChangeEvent(
ash::WindowStateType current_state,
ash::WindowStateType requested_state,
int64_t display_id,
const gfx::Rect& window_bounds,
int bounds_change) {
if (!geometry().IsEmpty() && !window_bounds.IsEmpty() &&
(!widget_->IsMinimized() ||
requested_state != ash::WindowStateType::kMinimized) &&
bounds_changed_callback_) {
ash::NonClientFrameViewAsh* frame_view = GetFrameView();
const bool becoming_snapped =
requested_state == ash::WindowStateType::kLeftSnapped ||
requested_state == ash::WindowStateType::kRightSnapped;
const bool is_tablet_mode =
WMHelper::GetInstance()->IsTabletModeWindowManagerEnabled();
gfx::Rect client_bounds =
becoming_snapped && is_tablet_mode
? window_bounds
: frame_view->GetClientBoundsForWindowBounds(window_bounds);
gfx::Size current_size = frame_view->GetBoundsForClientView().size();
bool is_resize = client_bounds.size() != current_size &&
!widget_->IsMaximized() && !widget_->IsFullscreen();
bounds_changed_callback_.Run(current_state, requested_state, display_id,
client_bounds, is_resize, bounds_change);
auto* window_state = GetWindowState();
if (server_reparent_window_ &&
window_state->GetDisplay().id() != display_id) {
ScopedSetBoundsLocally scoped_set_bounds(this);
int container_id = window_state->window()->parent()->id();
aura::Window* new_parent =
ash::Shell::GetRootWindowControllerWithDisplayId(display_id)
->GetContainer(container_id);
new_parent->AddChild(window_state->window());
}
}
}
Commit Message: Ignore updatePipBounds before initial bounds is set
When PIP enter/exit transition happens, window state change and
initial bounds change are committed in the same commit. However,
as state change is applied first in OnPreWidgetCommit and the
bounds is update later, if updatePipBounds is called between the
gap, it ends up returning a wrong bounds based on the previous
bounds.
Currently, there are two callstacks that end up triggering
updatePipBounds between the gap: (i) The state change causes
OnWindowAddedToLayout and updatePipBounds is called in OnWMEvent,
(ii) updatePipBounds is called in UpdatePipState to prevent it
from being placed under some system ui.
As it doesn't make sense to call updatePipBounds before the first
bounds is not set, this CL adds a boolean to defer updatePipBounds.
position.
Bug: b130782006
Test: Got VLC into PIP and confirmed it was placed at the correct
Change-Id: I5b9f3644bfb2533fd3f905bc09d49708a5d08a90
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1578719
Commit-Queue: Kazuki Takise <[email protected]>
Auto-Submit: Kazuki Takise <[email protected]>
Reviewed-by: Mitsuru Oshima <[email protected]>
Cr-Commit-Position: refs/heads/master@{#668724}
CWE ID: CWE-787 | void ClientControlledShellSurface::OnBoundsChangeEvent(
ash::WindowStateType current_state,
ash::WindowStateType requested_state,
int64_t display_id,
const gfx::Rect& window_bounds,
int bounds_change) {
if (ignore_bounds_change_request_)
return;
if (!geometry().IsEmpty() && !window_bounds.IsEmpty() &&
(!widget_->IsMinimized() ||
requested_state != ash::WindowStateType::kMinimized) &&
bounds_changed_callback_) {
ash::NonClientFrameViewAsh* frame_view = GetFrameView();
const bool becoming_snapped =
requested_state == ash::WindowStateType::kLeftSnapped ||
requested_state == ash::WindowStateType::kRightSnapped;
const bool is_tablet_mode =
WMHelper::GetInstance()->IsTabletModeWindowManagerEnabled();
gfx::Rect client_bounds =
becoming_snapped && is_tablet_mode
? window_bounds
: frame_view->GetClientBoundsForWindowBounds(window_bounds);
gfx::Size current_size = frame_view->GetBoundsForClientView().size();
bool is_resize = client_bounds.size() != current_size &&
!widget_->IsMaximized() && !widget_->IsFullscreen();
bounds_changed_callback_.Run(current_state, requested_state, display_id,
client_bounds, is_resize, bounds_change);
auto* window_state = GetWindowState();
if (server_reparent_window_ &&
window_state->GetDisplay().id() != display_id) {
ScopedSetBoundsLocally scoped_set_bounds(this);
int container_id = window_state->window()->parent()->id();
aura::Window* new_parent =
ash::Shell::GetRootWindowControllerWithDisplayId(display_id)
->GetContainer(container_id);
new_parent->AddChild(window_state->window());
}
}
}
| 172,408 |
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 Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
double
scale;
Image
*clone_image;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickSignature;
clone_image->storage_class=image->storage_class;
clone_image->channels=image->channels;
clone_image->colorspace=image->colorspace;
clone_image->matte=image->matte;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelPacket *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelPacket *) NULL)
{
clone_image=DestroyImage(clone_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
InitializeExceptionInfo(&clone_image->exception);
InheritException(&clone_image->exception,&image->exception);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MaxTextExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent);
(void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
clone_image->clip_mask=NewImageList();
clone_image->mask=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AllocateSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
if ((columns == image->columns) && (rows == image->rows))
{
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->cache=ClonePixelCache(image->cache);
if (SetImageExtent(clone_image,columns,rows) == MagickFalse)
{
InheritException(exception,&clone_image->exception);
clone_image=DestroyImage(clone_image);
}
return(clone_image);
}
Commit Message: Fixed incorrect call to DestroyImage reported in #491.
CWE ID: CWE-617 | MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
double
scale;
Image
*clone_image;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickSignature;
clone_image->storage_class=image->storage_class;
clone_image->channels=image->channels;
clone_image->colorspace=image->colorspace;
clone_image->matte=image->matte;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelPacket *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelPacket *) NULL)
{
image=(Image *) RelinquishMagickMemory(image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
InitializeExceptionInfo(&clone_image->exception);
InheritException(&clone_image->exception,&image->exception);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MaxTextExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent);
(void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
clone_image->clip_mask=NewImageList();
clone_image->mask=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AllocateSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
if ((columns == image->columns) && (rows == image->rows))
{
if (image->clip_mask != (Image *) NULL)
clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue,
exception);
if (image->mask != (Image *) NULL)
clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->cache=ClonePixelCache(image->cache);
if (SetImageExtent(clone_image,columns,rows) == MagickFalse)
{
InheritException(exception,&clone_image->exception);
clone_image=DestroyImage(clone_image);
}
return(clone_image);
}
| 168,096 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadLABELImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
*property;
const char
*label;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
TypeMetric
metrics;
size_t
height,
width;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
(void) ResetImagePage(image,"0x0+0+0");
property=InterpretImageProperties(image_info,image,image_info->filename);
(void) SetImageProperty(image,"label",property);
property=DestroyString(property);
label=GetImageProperty(image,"label");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->text=ConstantString(label);
metrics.width=0;
metrics.ascent=0.0;
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if ((image->columns == 0) && (image->rows == 0))
{
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
}
else
if ((strlen(label) > 0) &&
(((image->columns == 0) || (image->rows == 0)) ||
(fabs(image_info->pointsize) < MagickEpsilon)))
{
double
high,
low;
/*
Auto fit text into bounding box.
*/
for ( ; ; draw_info->pointsize*=2.0)
{
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width >= image->columns) && (height >= image->rows))
break;
}
else
if (((image->columns != 0) && (width >= image->columns)) ||
((image->rows != 0) && (height >= image->rows)))
break;
}
high=draw_info->pointsize;
for (low=1.0; (high-low) > 0.5; )
{
draw_info->pointsize=(low+high)/2.0;
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width < image->columns) && (height < image->rows))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
else
if (((image->columns != 0) && (width < image->columns)) ||
((image->rows != 0) && (height < image->rows)))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
draw_info->pointsize=(low+high)/2.0-0.5;
}
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image->columns == 0)
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
if (image->columns == 0)
image->columns=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
if (image->rows == 0)
image->rows=(size_t) floor(metrics.ascent-metrics.descent+
draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Draw label.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
draw_info->direction == RightToLeftDirection ? image->columns-
metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ?
metrics.ascent : 0.0);
draw_info->geometry=AcquireString(geometry);
status=AnnotateImage(image,draw_info);
if (image_info->pointsize == 0.0)
{
char
pointsize[MaxTextExtent];
(void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g",
draw_info->pointsize);
(void) SetImageProperty(image,"label:pointsize",pointsize);
}
draw_info=DestroyDrawInfo(draw_info);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
return(GetFirstImageInList(image));
}
Commit Message: Fix a small memory leak
CWE ID: CWE-399 | static Image *ReadLABELImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
*property;
const char
*label;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
TypeMetric
metrics;
size_t
height,
width;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
(void) ResetImagePage(image,"0x0+0+0");
property=InterpretImageProperties(image_info,image,image_info->filename);
(void) SetImageProperty(image,"label",property);
property=DestroyString(property);
label=GetImageProperty(image,"label");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->text=ConstantString(label);
metrics.width=0;
metrics.ascent=0.0;
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if ((image->columns == 0) && (image->rows == 0))
{
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
}
else
if ((strlen(label) > 0) &&
(((image->columns == 0) || (image->rows == 0)) ||
(fabs(image_info->pointsize) < MagickEpsilon)))
{
double
high,
low;
/*
Auto fit text into bounding box.
*/
for ( ; ; draw_info->pointsize*=2.0)
{
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width >= image->columns) && (height >= image->rows))
break;
}
else
if (((image->columns != 0) && (width >= image->columns)) ||
((image->rows != 0) && (height >= image->rows)))
break;
}
high=draw_info->pointsize;
for (low=1.0; (high-low) > 0.5; )
{
draw_info->pointsize=(low+high)/2.0;
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width < image->columns) && (height < image->rows))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
else
if (((image->columns != 0) && (width < image->columns)) ||
((image->rows != 0) && (height < image->rows)))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
draw_info->pointsize=(low+high)/2.0-0.5;
}
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image->columns == 0)
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
if (image->columns == 0)
image->columns=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
if (image->rows == 0)
image->rows=(size_t) floor(metrics.ascent-metrics.descent+
draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Draw label.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
draw_info->direction == RightToLeftDirection ? image->columns-
metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ?
metrics.ascent : 0.0);
(void) CloneString(&draw_info->geometry,geometry);
status=AnnotateImage(image,draw_info);
if (image_info->pointsize == 0.0)
{
char
pointsize[MaxTextExtent];
(void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g",
draw_info->pointsize);
(void) SetImageProperty(image,"label:pointsize",pointsize);
}
draw_info=DestroyDrawInfo(draw_info);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
return(GetFirstImageInList(image));
}
| 168,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_zalloc(voidpf png_ptr, uInt items, uInt size)
{
png_voidp ptr;
png_structp p=(png_structp)png_ptr;
png_uint_32 save_flags=p->flags;
png_uint_32 num_bytes;
if (png_ptr == NULL)
return (NULL);
if (items > PNG_UINT_32_MAX/size)
{
png_warning (p, "Potential overflow in png_zalloc()");
return (NULL);
}
num_bytes = (png_uint_32)items * size;
p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
p->flags=save_flags;
#if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
if (ptr == NULL)
return ((voidpf)ptr);
if (num_bytes > (png_uint_32)0x8000L)
{
png_memset(ptr, 0, (png_size_t)0x8000L);
png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
(png_size_t)(num_bytes - (png_uint_32)0x8000L));
}
else
{
png_memset(ptr, 0, (png_size_t)num_bytes);
}
#endif
return ((voidpf)ptr);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_zalloc(voidpf png_ptr, uInt items, uInt size)
{
png_voidp ptr;
png_structp p;
png_uint_32 save_flags;
png_uint_32 num_bytes;
if (png_ptr == NULL)
return (NULL);
p=(png_structp)png_ptr;
save_flags=p->flags;
if (items > PNG_UINT_32_MAX/size)
{
png_warning (p, "Potential overflow in png_zalloc()");
return (NULL);
}
num_bytes = (png_uint_32)items * size;
p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
p->flags=save_flags;
#if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
if (ptr == NULL)
return ((voidpf)ptr);
if (num_bytes > (png_uint_32)0x8000L)
{
png_memset(ptr, 0, (png_size_t)0x8000L);
png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
(png_size_t)(num_bytes - (png_uint_32)0x8000L));
}
else
{
png_memset(ptr, 0, (png_size_t)num_bytes);
}
#endif
return ((voidpf)ptr);
}
| 172,164 |
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 venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200 | int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (venc_handle->is_secure_session()) {
DEBUG_PRINT_ERROR("logging secure output buffers is not allowed!");
return -1;
}
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
| 173,507 |
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 opl3_load_patch(int dev, int format, const char __user *addr,
int offs, int count, int pmgr_flag)
{
struct sbi_instrument ins;
if (count <sizeof(ins))
{
printk(KERN_WARNING "FM Error: Patch record too short\n");
return -EINVAL;
}
/*
* What the fuck is going on here? We leave junk in the beginning
* of ins and then check the field pretty close to that beginning?
*/
if(copy_from_user(&((char *) &ins)[offs], addr + offs, sizeof(ins) - offs))
return -EFAULT;
if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR)
{
printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel);
return -EINVAL;
}
ins.key = format;
return store_instr(ins.channel, &ins);
}
Commit Message: sound/oss: remove offset from load_patch callbacks
Was: [PATCH] sound/oss/midi_synth: prevent underflow, use of
uninitialized value, and signedness issue
The offset passed to midi_synth_load_patch() can be essentially
arbitrary. If it's greater than the header length, this will result in
a copy_from_user(dst, src, negative_val). While this will just return
-EFAULT on x86, on other architectures this may cause memory corruption.
Additionally, the length field of the sysex_info structure may not be
initialized prior to its use. Finally, a signed comparison may result
in an unintentionally large loop.
On suggestion by Takashi Iwai, version two removes the offset argument
from the load_patch callbacks entirely, which also resolves similar
issues in opl3. Compile tested only.
v3 adjusts comments and hopefully gets copy offsets right.
Signed-off-by: Dan Rosenberg <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-189 | static int opl3_load_patch(int dev, int format, const char __user *addr,
int count, int pmgr_flag)
{
struct sbi_instrument ins;
if (count <sizeof(ins))
{
printk(KERN_WARNING "FM Error: Patch record too short\n");
return -EINVAL;
}
if (copy_from_user(&ins, addr, sizeof(ins)))
return -EFAULT;
if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR)
{
printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel);
return -EINVAL;
}
ins.key = format;
return store_instr(ins.channel, &ins);
}
| 165,893 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.