instruction
stringclasses 1
value | input
stringlengths 93
3.53k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,
uint32_t prefix, int length)
{
if (!bitstream_read_bit(bc)) { // Leaf
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
}
hc->values[hc->current] = bitstream_read(bc, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else { //Node
int r;
length++;
r = smacker_decode_tree(bc, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);
}
}
Commit Message: smacker: add sanity check for length in smacker_decode_tree()
Signed-off-by: Michael Niedermayer <[email protected]>
Bug-Id: 1098
Cc: [email protected]
Signed-off-by: Sean McGovern <[email protected]>
CWE ID: CWE-119
|
static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,
uint32_t prefix, int length)
{
if (length > SMKTREE_DECODE_MAX_RECURSION) {
av_log(NULL, AV_LOG_ERROR, "Maximum tree recursion level exceeded.\n");
return AVERROR_INVALIDDATA;
}
if (!bitstream_read_bit(bc)) { // Leaf
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
}
hc->values[hc->current] = bitstream_read(bc, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else { //Node
int r;
length++;
r = smacker_decode_tree(bc, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);
}
}
| 167,671
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long Cluster::GetLast(const BlockEntry*& pLast) const
{
for (;;)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pLast = NULL;
return status;
}
if (status > 0) //no new block
break;
}
if (m_entries_count <= 0)
{
pLast = NULL;
return 0;
}
assert(m_entries);
const long idx = m_entries_count - 1;
pLast = m_entries[idx];
assert(pLast);
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 Cluster::GetLast(const BlockEntry*& pLast) const
if (m_entries_count <= 0) {
pLast = NULL;
return 0;
}
assert(m_entries);
const long idx = m_entries_count - 1;
pLast = m_entries[idx];
assert(pLast);
return 0;
}
| 174,338
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool NaClProcessHost::ReplyToRenderer(
const IPC::ChannelHandle& channel_handle) {
std::vector<nacl::FileDescriptor> handles_for_renderer;
for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
#if defined(OS_WIN)
HANDLE handle_in_renderer;
if (!DuplicateHandle(base::GetCurrentProcessHandle(),
reinterpret_cast<HANDLE>(
internal_->sockets_for_renderer[i]),
chrome_render_message_filter_->peer_handle(),
&handle_in_renderer,
0, // Unused given DUPLICATE_SAME_ACCESS.
FALSE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
DLOG(ERROR) << "DuplicateHandle() failed";
return false;
}
handles_for_renderer.push_back(
reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));
#else
nacl::FileDescriptor imc_handle;
imc_handle.fd = internal_->sockets_for_renderer[i];
imc_handle.auto_close = true;
handles_for_renderer.push_back(imc_handle);
#endif
}
#if defined(OS_WIN)
if (RunningOnWOW64()) {
if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
DLOG(ERROR) << "Failed to add NaCl process PID";
return false;
}
}
#endif
ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(
reply_msg_, handles_for_renderer, channel_handle);
chrome_render_message_filter_->Send(reply_msg_);
chrome_render_message_filter_ = NULL;
reply_msg_ = NULL;
internal_->sockets_for_renderer.clear();
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 NaClProcessHost::ReplyToRenderer(
bool NaClProcessHost::ReplyToRenderer() {
std::vector<nacl::FileDescriptor> handles_for_renderer;
for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {
#if defined(OS_WIN)
HANDLE handle_in_renderer;
if (!DuplicateHandle(base::GetCurrentProcessHandle(),
reinterpret_cast<HANDLE>(
internal_->sockets_for_renderer[i]),
chrome_render_message_filter_->peer_handle(),
&handle_in_renderer,
0, // Unused given DUPLICATE_SAME_ACCESS.
FALSE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
DLOG(ERROR) << "DuplicateHandle() failed";
return false;
}
handles_for_renderer.push_back(
reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));
#else
nacl::FileDescriptor imc_handle;
imc_handle.fd = internal_->sockets_for_renderer[i];
imc_handle.auto_close = true;
handles_for_renderer.push_back(imc_handle);
#endif
}
#if defined(OS_WIN)
if (RunningOnWOW64()) {
if (!content::BrokerAddTargetPeer(process_->GetData().handle)) {
DLOG(ERROR) << "Failed to add NaCl process PID";
return false;
}
}
#endif
ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(
reply_msg_, handles_for_renderer);
chrome_render_message_filter_->Send(reply_msg_);
chrome_render_message_filter_ = NULL;
reply_msg_ = NULL;
internal_->sockets_for_renderer.clear();
return true;
}
| 170,727
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: load_fake(png_charp param, png_bytepp profile)
{
char *endptr = NULL;
unsigned long long int size = strtoull(param, &endptr, 0/*base*/);
/* The 'fake' format is <number>*[string] */
if (endptr != NULL && *endptr == '*')
{
size_t len = strlen(++endptr);
size_t result = (size_t)size;
if (len == 0) len = 1; /* capture the terminating '\0' */
/* Now repeat that string to fill 'size' bytes. */
if (result == size && (*profile = malloc(result)) != NULL)
{
png_bytep out = *profile;
if (len == 1)
memset(out, *endptr, result);
else
{
while (size >= len)
{
memcpy(out, endptr, len);
out += len;
size -= len;
}
memcpy(out, endptr, size);
}
return result;
}
else
{
fprintf(stderr, "%s: size exceeds system limits\n", param);
exit(1);
}
}
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
load_fake(png_charp param, png_bytepp profile)
{
char *endptr = NULL;
uint64_t size = strtoull(param, &endptr, 0/*base*/);
/* The 'fake' format is <number>*[string] */
if (endptr != NULL && *endptr == '*')
{
size_t len = strlen(++endptr);
size_t result = (size_t)size;
if (len == 0) len = 1; /* capture the terminating '\0' */
/* Now repeat that string to fill 'size' bytes. */
if (result == size && (*profile = malloc(result)) != NULL)
{
png_bytep out = *profile;
if (len == 1)
memset(out, *endptr, result);
else
{
while (size >= len)
{
memcpy(out, endptr, len);
out += len;
size -= len;
}
memcpy(out, endptr, size);
}
return result;
}
else
{
fprintf(stderr, "%s: size exceeds system limits\n", param);
exit(1);
}
}
return 0;
}
| 173,583
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::OnPair(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Paired";
if (!pairing_delegate_used_)
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_NONE,
UMA_PAIRING_METHOD_COUNT);
UnregisterAgent();
SetTrusted();
ConnectInternal(true, callback, error_callback);
}
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::OnPair(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Paired";
pairing_context_.reset();
SetTrusted();
ConnectInternal(true, callback, error_callback);
}
| 171,227
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cf2_initGlobalRegionBuffer( CFF_Decoder* decoder,
CF2_UInt idx,
CF2_Buffer buf )
{
FT_ASSERT( decoder && decoder->globals );
FT_ZERO( buf );
idx += decoder->globals_bias;
if ( idx >= decoder->num_globals )
return TRUE; /* error */
buf->start =
buf->ptr = decoder->globals[idx];
buf->end = decoder->globals[idx + 1];
}
Commit Message:
CWE ID: CWE-20
|
cf2_initGlobalRegionBuffer( CFF_Decoder* decoder,
CF2_UInt idx,
CF2_Buffer buf )
{
FT_ASSERT( decoder );
FT_ZERO( buf );
idx += decoder->globals_bias;
if ( idx >= decoder->num_globals )
return TRUE; /* error */
FT_ASSERT( decoder->globals );
buf->start =
buf->ptr = decoder->globals[idx];
buf->end = decoder->globals[idx + 1];
}
| 165,221
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline int process_numeric_entity(const char **buf, unsigned *code_point)
{
long code_l;
int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */
char *endptr;
if (hexadecimal && (**buf != '\0'))
(*buf)++;
/* strtol allows whitespace and other stuff in the beginning
* we're not interested */
if ((hexadecimal && !isxdigit(**buf)) ||
(!hexadecimal && !isdigit(**buf))) {
return FAILURE;
}
code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10);
/* we're guaranteed there were valid digits, so *endptr > buf */
*buf = endptr;
if (**buf != ';')
return FAILURE;
/* many more are invalid, but that depends on whether it's HTML
* (and which version) or XML. */
if (code_l > 0x10FFFFL)
return FAILURE;
if (code_point != NULL)
*code_point = (unsigned)code_l;
return SUCCESS;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
|
static inline int process_numeric_entity(const char **buf, unsigned *code_point)
{
long code_l;
int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */
char *endptr;
if (hexadecimal && (**buf != '\0'))
(*buf)++;
/* strtol allows whitespace and other stuff in the beginning
* we're not interested */
if ((hexadecimal && !isxdigit(**buf)) ||
(!hexadecimal && !isdigit(**buf))) {
return FAILURE;
}
code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10);
/* we're guaranteed there were valid digits, so *endptr > buf */
*buf = endptr;
if (**buf != ';')
return FAILURE;
/* many more are invalid, but that depends on whether it's HTML
* (and which version) or XML. */
if (code_l > 0x10FFFFL)
return FAILURE;
if (code_point != NULL)
*code_point = (unsigned)code_l;
return SUCCESS;
}
| 167,177
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
Commit Message: [MJ2] Avoid index out of bounds access to pi->include[]
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-20
|
static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
| 169,770
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];
obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);;
obj_bucket->destructor_called = 1;
}
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction
CWE ID: CWE-119
|
ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];
obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);
obj_bucket->destructor_called = 1;
}
| 166,938
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AppControllerImpl::BindRequest(mojom::AppControllerRequest request) {
bindings_.AddBinding(this, std::move(request));
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416
|
void AppControllerImpl::BindRequest(mojom::AppControllerRequest request) {
void AppControllerService::BindRequest(mojom::AppControllerRequest request) {
bindings_.AddBinding(this, std::move(request));
}
| 172,080
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SetManualFallbacks(bool enabled) {
std::vector<std::string> features = {
password_manager::features::kEnableManualFallbacksFilling.name,
password_manager::features::kEnableManualFallbacksFillingStandalone
.name,
password_manager::features::kEnableManualFallbacksGeneration.name};
if (enabled) {
scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","),
std::string());
} else {
scoped_feature_list_.InitFromCommandLine(std::string(),
base::JoinString(features, ","));
}
}
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <[email protected]>
Commit-Queue: NIKHIL SAHNI <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534923}
CWE ID: CWE-264
|
void SetManualFallbacks(bool enabled) {
std::vector<std::string> features = {
password_manager::features::kManualFallbacksFilling.name,
password_manager::features::kEnableManualFallbacksFillingStandalone
.name,
password_manager::features::kEnableManualFallbacksGeneration.name};
if (enabled) {
scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","),
std::string());
} else {
scoped_feature_list_.InitFromCommandLine(std::string(),
base::JoinString(features, ","));
}
}
| 171,749
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SpdyWriteQueue::Clear() {
CHECK(!removing_writes_);
removing_writes_ = true;
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
for (std::deque<PendingWrite>::iterator it = queue_[i].begin();
it != queue_[i].end(); ++it) {
delete it->frame_producer;
}
queue_[i].clear();
}
removing_writes_ = false;
}
Commit Message: These can post callbacks which re-enter into SpdyWriteQueue.
BUG=369539
Review URL: https://codereview.chromium.org/265933007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void SpdyWriteQueue::Clear() {
CHECK(!removing_writes_);
removing_writes_ = true;
std::vector<SpdyBufferProducer*> erased_buffer_producers;
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
for (std::deque<PendingWrite>::iterator it = queue_[i].begin();
it != queue_[i].end(); ++it) {
erased_buffer_producers.push_back(it->frame_producer);
}
queue_[i].clear();
}
removing_writes_ = false;
STLDeleteElements(&erased_buffer_producers); // Invokes callbacks.
}
| 171,673
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int generate_key(DH *dh)
{
int ok = 0;
int generate_new_key = 0;
unsigned l;
BN_CTX *ctx;
BN_MONT_CTX *mont = NULL;
BIGNUM *pub_key = NULL, *priv_key = NULL;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
generate_new_key = 1;
} else
Commit Message:
CWE ID: CWE-320
|
static int generate_key(DH *dh)
{
int ok = 0;
int generate_new_key = 0;
unsigned l;
BN_CTX *ctx = NULL;
BN_MONT_CTX *mont = NULL;
BIGNUM *pub_key = NULL, *priv_key = NULL;
if (BN_num_bits(dh->p) > OPENSSL_DH_MAX_MODULUS_BITS) {
DHerr(DH_F_GENERATE_KEY, DH_R_MODULUS_TOO_LARGE);
return 0;
}
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
generate_new_key = 1;
} else
| 165,332
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virDomainGetTime(virDomainPtr dom,
long long *seconds,
unsigned int *nseconds,
unsigned int flags)
{
VIR_DOMAIN_DEBUG(dom, "seconds=%p, nseconds=%p, flags=%x",
seconds, nseconds, flags);
virResetLastError();
virCheckDomainReturn(dom, -1);
if (dom->conn->driver->domainGetTime) {
int ret = dom->conn->driver->domainGetTime(dom, seconds,
nseconds, flags);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(dom->conn);
return -1;
}
Commit Message: virDomainGetTime: Deny on RO connections
We have a policy that if API may end up talking to a guest agent
it should require RW connection. We don't obey the rule in
virDomainGetTime().
Signed-off-by: Michal Privoznik <[email protected]>
CWE ID: CWE-254
|
virDomainGetTime(virDomainPtr dom,
long long *seconds,
unsigned int *nseconds,
unsigned int flags)
{
VIR_DOMAIN_DEBUG(dom, "seconds=%p, nseconds=%p, flags=%x",
seconds, nseconds, flags);
virResetLastError();
virCheckDomainReturn(dom, -1);
virCheckReadOnlyGoto(dom->conn->flags, error);
if (dom->conn->driver->domainGetTime) {
int ret = dom->conn->driver->domainGetTime(dom, seconds,
nseconds, flags);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(dom->conn);
return -1;
}
| 169,863
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context)
{
uint8_t tmp = 0;
asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context));
asn1_read_uint8(data, &tmp);
if (tmp == 0xFF) {
*v = true;
} else {
*v = false;
}
asn1_end_tag(data);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context)
{
uint8_t tmp = 0;
if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context))) return false;
*v = false;
if (!asn1_read_uint8(data, &tmp)) return false;
if (tmp == 0xFF) {
*v = true;
}
return asn1_end_tag(data);
}
| 164,584
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void nfs4_open_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (data->rpc_status != 0 || !data->rpc_done)
goto out_free;
/* In case we need an open_confirm, no cleanup! */
if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(&data->path, state, data->o_arg.open_flags);
out_free:
nfs4_opendata_put(data);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
|
static void nfs4_open_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (data->rpc_status != 0 || !data->rpc_done)
goto out_free;
/* In case we need an open_confirm, no cleanup! */
if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(&data->path, state, data->o_arg.fmode);
out_free:
nfs4_opendata_put(data);
}
| 165,698
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ClipboardMessageFilter::OnReadImageReply(
SkBitmap bitmap, IPC::Message* reply_msg) {
base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle();
uint32 image_size = 0;
std::string reply_data;
if (!bitmap.isNull()) {
std::vector<unsigned char> png_data;
SkAutoLockPixels lock(bitmap);
if (gfx::PNGCodec::EncodeWithCompressionLevel(
static_cast<const unsigned char*>(bitmap.getPixels()),
gfx::PNGCodec::FORMAT_BGRA,
gfx::Size(bitmap.width(), bitmap.height()),
bitmap.rowBytes(),
false,
std::vector<gfx::PNGCodec::Comment>(),
Z_BEST_SPEED,
&png_data)) {
base::SharedMemory buffer;
if (buffer.CreateAndMapAnonymous(png_data.size())) {
memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size());
if (buffer.GiveToProcess(peer_handle(), &image_handle)) {
image_size = png_data.size();
}
}
}
}
ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle,
image_size);
Send(reply_msg);
}
Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE)
CIDs 16230, 16439, 16610, 16635
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/7215029
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void ClipboardMessageFilter::OnReadImageReply(
const SkBitmap& bitmap, IPC::Message* reply_msg) {
base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle();
uint32 image_size = 0;
std::string reply_data;
if (!bitmap.isNull()) {
std::vector<unsigned char> png_data;
SkAutoLockPixels lock(bitmap);
if (gfx::PNGCodec::EncodeWithCompressionLevel(
static_cast<const unsigned char*>(bitmap.getPixels()),
gfx::PNGCodec::FORMAT_BGRA,
gfx::Size(bitmap.width(), bitmap.height()),
bitmap.rowBytes(),
false,
std::vector<gfx::PNGCodec::Comment>(),
Z_BEST_SPEED,
&png_data)) {
base::SharedMemory buffer;
if (buffer.CreateAndMapAnonymous(png_data.size())) {
memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size());
if (buffer.GiveToProcess(peer_handle(), &image_handle)) {
image_size = png_data.size();
}
}
}
}
ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle,
image_size);
Send(reply_msg);
}
| 170,311
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
type = get4(); get4(); get4();
wide = get4();
high = get4();
if (type == 2) {
fread (meta_data, 1, meta_length, ifp);
for (i=0; i < meta_length; i++) {
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64) 301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
} else if (type == 4) {
free (meta_data);
meta_data = (char *) malloc (meta_length = wide*high*3/2);
merror (meta_data, "foveon_load_camf()");
foveon_huff (huff);
get4();
getbits(-1);
for (j=row=0; row < high; row++) {
for (col=0; col < wide; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if (col & 1) {
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
} else
fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
}
Commit Message: Fixed possible foveon buffer overrun (Secunia SA750000)
CWE ID: CWE-119
|
void CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[1024], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
type = get4(); get4(); get4();
wide = get4();
high = get4();
#ifdef LIBRAW_LIBRARY_BUILD
if(wide>32767 || high > 32767 || wide*high > 20000000)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
if (type == 2) {
fread (meta_data, 1, meta_length, ifp);
for (i=0; i < meta_length; i++) {
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64) 301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
} else if (type == 4) {
free (meta_data);
meta_data = (char *) malloc (meta_length = wide*high*3/2);
merror (meta_data, "foveon_load_camf()");
foveon_huff (huff);
get4();
getbits(-1);
for (j=row=0; row < high; row++) {
for (col=0; col < wide; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if (col & 1) {
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
} else
fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
}
| 168,314
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int UDPSocketWin::DoBind(const IPEndPoint& address) {
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len))
return ERR_ADDRESS_INVALID;
int rv = bind(socket_, storage.addr, storage.addr_len);
if (rv == 0)
return OK;
int last_error = WSAGetLastError();
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromWinOS", last_error);
if (last_error == WSAEACCES || last_error == WSAEINVAL)
return ERR_ADDRESS_IN_USE;
return MapSystemError(last_error);
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
|
int UDPSocketWin::DoBind(const IPEndPoint& address) {
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len))
return ERR_ADDRESS_INVALID;
int rv = bind(socket_, storage.addr, storage.addr_len);
if (rv == 0)
return OK;
int last_error = WSAGetLastError();
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromWinOS", last_error);
// * WSAEACCES: If a port is already bound to a socket, WSAEACCES may be
// returned instead of WSAEADDRINUSE, depending on whether the socket
// option SO_REUSEADDR or SO_EXCLUSIVEADDRUSE is set and whether the
// conflicting socket is owned by a different user account. See the MSDN
// page "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" for the gory details.
if (last_error == WSAEACCES || last_error == WSAEADDRNOTAVAIL)
return ERR_ADDRESS_IN_USE;
return MapSystemError(last_error);
}
| 171,317
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
Commit Message: ipsec: Fix aborted xfrm policy dump crash
An independent security researcher, Mohamed Ghannam, has reported
this vulnerability to Beyond Security's SecuriTeam Secure Disclosure
program.
The xfrm_dump_policy_done function expects xfrm_dump_policy to
have been called at least once or it will crash. This can be
triggered if a dump fails because the target socket's receive
buffer is full.
This patch fixes it by using the cb->start mechanism to ensure that
the initialisation is always done regardless of the buffer situation.
Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list")
Signed-off-by: Herbert Xu <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
CWE ID: CWE-416
|
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
struct xfrm_dump_info info;
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
| 167,662
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: raptor_libxml_getEntity(void* user_data, const xmlChar *name) {
raptor_sax2* sax2 = (raptor_sax2*)user_data;
return libxml2_getEntity(sax2->xc, name);
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
|
raptor_libxml_getEntity(void* user_data, const xmlChar *name) {
raptor_libxml_getEntity(void* user_data, const xmlChar *name)
{
raptor_sax2* sax2 = (raptor_sax2*)user_data;
xmlParserCtxtPtr xc = sax2->xc;
xmlEntityPtr ret = NULL;
if(!xc)
return NULL;
if(!xc->inSubset) {
/* looks for hardcoded set of entity names - lt, gt etc. */
ret = xmlGetPredefinedEntity(name);
if(ret) {
RAPTOR_DEBUG2("Entity '%s' found in predefined set\n", name);
return ret;
}
}
/* This section uses xmlGetDocEntity which looks for entities in
* memory only, never from a file or URI
*/
if(xc->myDoc && (xc->myDoc->standalone == 1)) {
RAPTOR_DEBUG2("Entity '%s' document is standalone\n", name);
/* Document is standalone: no entities are required to interpret doc */
if(xc->inSubset == 2) {
xc->myDoc->standalone = 0;
ret = xmlGetDocEntity(xc->myDoc, name);
xc->myDoc->standalone = 1;
} else {
ret = xmlGetDocEntity(xc->myDoc, name);
if(!ret) {
xc->myDoc->standalone = 0;
ret = xmlGetDocEntity(xc->myDoc, name);
xc->myDoc->standalone = 1;
}
}
} else {
ret = xmlGetDocEntity(xc->myDoc, name);
}
if(ret && !ret->children &&
(ret->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
/* Entity is an external general parsed entity. It may be in a
* catalog file, user file or user URI
*/
int val = 0;
xmlNodePtr children;
int load_entity = 0;
load_entity = RAPTOR_OPTIONS_GET_NUMERIC(sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES);
if(load_entity)
load_entity = raptor_sax2_check_load_uri_string(sax2, ret->URI);
if(!load_entity) {
RAPTOR_DEBUG2("Not getting entity URI %s by policy\n", ret->URI);
children = xmlNewText((const xmlChar*)"");
} else {
/* Disable SAX2 handlers so that the SAX2 events do not all get
* sent to callbacks during dealing with the entity parsing.
*/
sax2->enabled = 0;
val = xmlParseCtxtExternalEntity(xc, ret->URI, ret->ExternalID, &children);
sax2->enabled = 1;
}
if(!val) {
xmlAddChildList((xmlNodePtr)ret, children);
} else {
xc->validate = 0;
return NULL;
}
ret->owner = 1;
/* Mark this entity as having been checked - never do this again */
if(!ret->checked)
ret->checked = 1;
}
return ret;
}
| 165,658
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int base64decode_block(unsigned char *target, const char *data, size_t data_size)
{
int w1,w2,w3,w4;
int i;
size_t n;
if (!data || (data_size <= 0)) {
return 0;
}
n = 0;
i = 0;
while (n < data_size-3) {
w1 = base64_table[(int)data[n]];
w2 = base64_table[(int)data[n+1]];
w3 = base64_table[(int)data[n+2]];
w4 = base64_table[(int)data[n+3]];
if (w2 >= 0) {
target[i++] = (char)((w1*4 + (w2 >> 4)) & 255);
}
if (w3 >= 0) {
target[i++] = (char)((w2*16 + (w3 >> 2)) & 255);
}
if (w4 >= 0) {
target[i++] = (char)((w3*64 + w4) & 255);
}
n+=4;
}
return i;
}
Commit Message: base64: Rework base64decode to handle split encoded data correctly
CWE ID: CWE-125
|
static int base64decode_block(unsigned char *target, const char *data, size_t data_size)
| 168,417
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SWFInput_readSBits(SWFInput input, int number)
{
int num = SWFInput_readBits(input, number);
if ( num & (1<<(number-1)) )
return num - (1<<number);
else
return num;
}
Commit Message: Fix left shift of a negative value in SWFInput_readSBits. Check for number before before left-shifting by (number-1).
CWE ID: CWE-190
|
SWFInput_readSBits(SWFInput input, int number)
{
int num = SWFInput_readBits(input, number);
if(number && num & (1<<(number-1)))
return num - (1<<number);
else
return num;
}
| 169,648
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_FUNCTION(imagesetstyle)
{
zval *IM, *styles;
gdImagePtr im;
int * stylearr;
int index;
HashPosition pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
/* copy the style values in the stylearr */
stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0);
zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos);
for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) {
zval ** item;
if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) {
break;
}
convert_to_long_ex(item);
stylearr[index++] = Z_LVAL_PP(item);
}
gdImageSetStyle(im, stylearr, index);
efree(stylearr);
RETURN_TRUE;
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189
|
PHP_FUNCTION(imagesetstyle)
{
zval *IM, *styles;
gdImagePtr im;
int * stylearr;
int index;
HashPosition pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
/* copy the style values in the stylearr */
stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0);
zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos);
for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) {
zval ** item;
if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) {
break;
}
if (Z_TYPE_PP(item) != IS_LONG) {
zval lval;
lval = **item;
zval_copy_ctor(&lval);
convert_to_long(&lval);
stylearr[index++] = Z_LVAL(lval);
} else {
stylearr[index++] = Z_LVAL_PP(item);
}
}
gdImageSetStyle(im, stylearr, index);
efree(stylearr);
RETURN_TRUE;
}
| 166,425
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: TestCompletionCallback()
: callback_(base::Bind(&TestCompletionCallback::SetResult,
base::Unretained(this))) {}
Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback
Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback
migration, as they are copied and passed to others.
This CL updates them to pass new callbacks for each use to avoid the
copy of callbacks.
Bug: 714018
Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0
Reviewed-on: https://chromium-review.googlesource.com/527549
Reviewed-by: Ken Rockot <[email protected]>
Commit-Queue: Taiju Tsuiki <[email protected]>
Cr-Commit-Position: refs/heads/master@{#478549}
CWE ID:
|
TestCompletionCallback()
| 171,975
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHPAPI PHP_FUNCTION(fread)
{
zval *arg1;
long len;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) {
RETURN_FALSE;
}
PHP_STREAM_TO_ZVAL(stream, &arg1);
if (len <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(len + 1);
Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
Commit Message: Fix bug #72114 - int/size_t confusion in fread
CWE ID: CWE-190
|
PHPAPI PHP_FUNCTION(fread)
{
zval *arg1;
long len;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) {
RETURN_FALSE;
}
PHP_STREAM_TO_ZVAL(stream, &arg1);
if (len <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
if (len > INT_MAX) {
/* string length is int in 5.x so we can not read more than int */
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX);
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(len + 1);
Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
| 167,167
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
{
write_seqlock(&state->seqlock);
nfs_set_open_stateid_locked(state, stateid, open_flags);
write_sequnlock(&state->seqlock);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
|
static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
{
write_seqlock(&state->seqlock);
nfs_set_open_stateid_locked(state, stateid, fmode);
write_sequnlock(&state->seqlock);
}
| 165,705
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual InputMethodDescriptors* GetActiveInputMethods() {
chromeos::InputMethodDescriptors* result =
new chromeos::InputMethodDescriptors;
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
if (result->empty()) {
LOG(WARNING) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual InputMethodDescriptors* GetActiveInputMethods() {
virtual input_method::InputMethodDescriptors* GetActiveInputMethods() {
input_method::InputMethodDescriptors* result =
new input_method::InputMethodDescriptors;
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const input_method::InputMethodDescriptor* descriptor =
input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
if (result->empty()) {
LOG(WARNING) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
| 170,486
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Cluster::Cluster() :
m_pSegment(NULL),
m_element_start(0),
m_index(0),
m_pos(0),
m_element_size(0),
m_timecode(0),
m_entries(NULL),
m_entries_size(0),
m_entries_count(0) //means "no entries"
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Cluster::Cluster() :
| 174,248
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void EnterpriseEnrollmentScreen::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
if (is_showing_) {
switch (state) {
case policy::CloudPolicySubsystem::UNENROLLED:
return;
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
actor_->ShowFatalEnrollmentError();
break;
case policy::CloudPolicySubsystem::UNMANAGED:
actor_->ShowAccountError();
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
actor_->ShowNetworkEnrollmentError();
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
WriteInstallAttributesData();
return;
case policy::CloudPolicySubsystem::SUCCESS:
registrar_.reset();
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentOK,
policy::kMetricEnrollmentSize);
actor_->ShowConfirmationScreen();
return;
}
if (state == policy::CloudPolicySubsystem::UNMANAGED) {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentNotSupported,
policy::kMetricEnrollmentSize);
} else {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentPolicyFailed,
policy::kMetricEnrollmentSize);
}
LOG(WARNING) << "Policy subsystem error during enrollment: " << state
<< " details: " << error_details;
}
registrar_.reset();
g_browser_process->browser_policy_connector()->DeviceStopAutoRetry();
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void EnterpriseEnrollmentScreen::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
if (is_showing_) {
switch (state) {
case policy::CloudPolicySubsystem::UNENROLLED:
return;
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
actor_->ShowFatalEnrollmentError();
break;
case policy::CloudPolicySubsystem::UNMANAGED:
actor_->ShowAccountError();
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
actor_->ShowNetworkEnrollmentError();
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
WriteInstallAttributesData();
return;
case policy::CloudPolicySubsystem::SUCCESS:
registrar_.reset();
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentOK,
policy::kMetricEnrollmentSize);
actor_->ShowConfirmationScreen();
return;
}
if (state == policy::CloudPolicySubsystem::UNMANAGED) {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentNotSupported,
policy::kMetricEnrollmentSize);
} else {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentPolicyFailed,
policy::kMetricEnrollmentSize);
}
LOG(WARNING) << "Policy subsystem error during enrollment: " << state
<< " details: " << error_details;
}
registrar_.reset();
g_browser_process->browser_policy_connector()->ResetDevicePolicy();
}
| 170,277
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cJSON *cJSON_CreateArray( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_Array;
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
|
cJSON *cJSON_CreateArray( void )
| 167,269
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
SessionService* session_service =
SessionServiceFactory::GetForProfile(profile_);
if (session_service)
session_service->TabClosing(old_contents->web_contents());
TabInsertedAt(new_contents->web_contents(), index, (index == active_index()));
int entry_count =
new_contents->web_contents()->GetController().GetEntryCount();
if (entry_count > 0) {
new_contents->web_contents()->GetController().NotifyEntryChanged(
new_contents->web_contents()->GetController().GetEntryAtIndex(
entry_count - 1),
entry_count - 1);
}
if (session_service) {
session_service->TabRestored(new_contents,
tab_strip_model_->IsTabPinned(index));
}
content::DevToolsManager::GetInstance()->ContentsReplaced(
old_contents->web_contents(), new_contents->web_contents());
}
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::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
TabDetachedAtImpl(old_contents->web_contents(), index, DETACH_TYPE_REPLACE);
SessionService* session_service =
SessionServiceFactory::GetForProfile(profile_);
if (session_service)
session_service->TabClosing(old_contents->web_contents());
TabInsertedAt(new_contents->web_contents(), index, (index == active_index()));
int entry_count =
new_contents->web_contents()->GetController().GetEntryCount();
if (entry_count > 0) {
new_contents->web_contents()->GetController().NotifyEntryChanged(
new_contents->web_contents()->GetController().GetEntryAtIndex(
entry_count - 1),
entry_count - 1);
}
if (session_service) {
session_service->TabRestored(new_contents,
tab_strip_model_->IsTabPinned(index));
}
content::DevToolsManager::GetInstance()->ContentsReplaced(
old_contents->web_contents(), new_contents->web_contents());
}
| 171,509
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AppShortcutManager::OnceOffCreateShortcuts() {
bool was_enabled = prefs_->GetBoolean(prefs::kAppShortcutsHaveBeenCreated);
#if defined(OS_MACOSX)
bool is_now_enabled = apps::IsAppShimsEnabled();
#else
bool is_now_enabled = true;
#endif // defined(OS_MACOSX)
if (was_enabled != is_now_enabled)
prefs_->SetBoolean(prefs::kAppShortcutsHaveBeenCreated, is_now_enabled);
if (was_enabled || !is_now_enabled)
return;
extensions::ExtensionSystem* extension_system;
ExtensionServiceInterface* extension_service;
if (!(extension_system = extensions::ExtensionSystem::Get(profile_)) ||
!(extension_service = extension_system->extension_service()))
return;
const extensions::ExtensionSet* apps = extension_service->extensions();
for (extensions::ExtensionSet::const_iterator it = apps->begin();
it != apps->end(); ++it) {
if (ShouldCreateShortcutFor(profile_, it->get()))
CreateShortcutsInApplicationsMenu(profile_, it->get());
}
}
Commit Message: Remove --disable-app-shims.
App shims have been enabled by default for 3 milestones
(since r242711).
BUG=350161
Review URL: https://codereview.chromium.org/298953002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void AppShortcutManager::OnceOffCreateShortcuts() {
if (prefs_->GetBoolean(prefs::kAppShortcutsHaveBeenCreated))
return;
prefs_->SetBoolean(prefs::kAppShortcutsHaveBeenCreated, true);
extensions::ExtensionSystem* extension_system;
ExtensionServiceInterface* extension_service;
if (!(extension_system = extensions::ExtensionSystem::Get(profile_)) ||
!(extension_service = extension_system->extension_service()))
return;
const extensions::ExtensionSet* apps = extension_service->extensions();
for (extensions::ExtensionSet::const_iterator it = apps->begin();
it != apps->end(); ++it) {
if (ShouldCreateShortcutFor(profile_, it->get()))
CreateShortcutsInApplicationsMenu(profile_, it->get());
}
}
| 171,146
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ahci_uninit(AHCIState *s)
{
g_free(s->dev);
}
Commit Message:
CWE ID: CWE-772
|
void ahci_uninit(AHCIState *s)
{
int i, j;
for (i = 0; i < s->ports; i++) {
AHCIDevice *ad = &s->dev[i];
for (j = 0; j < 2; j++) {
IDEState *s = &ad->port.ifs[j];
ide_exit(s);
}
}
g_free(s->dev);
}
| 164,797
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: gray_render_span( int y,
int count,
const FT_Span* spans,
PWorker worker )
{
unsigned char* p;
FT_Bitmap* map = &worker->target;
/* first of all, compute the scanline offset */
p = (unsigned char*)map->buffer - y * map->pitch;
if ( map->pitch >= 0 )
p += ( map->rows - 1 ) * map->pitch;
for ( ; count > 0; count--, spans++ )
{
unsigned char coverage = spans->coverage;
if ( coverage )
{
/* For small-spans it is faster to do it by ourselves than
* calling `memset'. This is mainly due to the cost of the
* function call.
*/
if ( spans->len >= 8 )
FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len );
else
{
unsigned char* q = p + spans->x;
switch ( spans->len )
{
case 7: *q++ = (unsigned char)coverage;
case 6: *q++ = (unsigned char)coverage;
case 5: *q++ = (unsigned char)coverage;
case 4: *q++ = (unsigned char)coverage;
case 3: *q++ = (unsigned char)coverage;
case 2: *q++ = (unsigned char)coverage;
case 1: *q = (unsigned char)coverage;
default:
;
}
}
}
}
}
Commit Message:
CWE ID: CWE-189
|
gray_render_span( int y,
int count,
const FT_Span* spans,
PWorker worker )
{
unsigned char* p;
FT_Bitmap* map = &worker->target;
/* first of all, compute the scanline offset */
p = (unsigned char*)map->buffer - y * map->pitch;
if ( map->pitch >= 0 )
p += (unsigned)( ( map->rows - 1 ) * map->pitch );
for ( ; count > 0; count--, spans++ )
{
unsigned char coverage = spans->coverage;
if ( coverage )
{
/* For small-spans it is faster to do it by ourselves than
* calling `memset'. This is mainly due to the cost of the
* function call.
*/
if ( spans->len >= 8 )
FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len );
else
{
unsigned char* q = p + spans->x;
switch ( spans->len )
{
case 7: *q++ = (unsigned char)coverage;
case 6: *q++ = (unsigned char)coverage;
case 5: *q++ = (unsigned char)coverage;
case 4: *q++ = (unsigned char)coverage;
case 3: *q++ = (unsigned char)coverage;
case 2: *q++ = (unsigned char)coverage;
case 1: *q = (unsigned char)coverage;
default:
;
}
}
}
}
}
| 165,004
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cJSON *cJSON_Parse( const char *value )
{
cJSON *c;
ep = 0;
if ( ! ( c = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! parse_value( c, skip( value ) ) ) {
cJSON_Delete( c );
return 0;
}
return c;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
|
cJSON *cJSON_Parse( const char *value )
cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated)
{
const char *end=0,**ep=return_parse_end?return_parse_end:&global_ep;
cJSON *c=cJSON_New_Item();
*ep=0;
if (!c) return 0; /* memory fail */
end=parse_value(c,skip(value),ep);
if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);*ep=end;return 0;}}
if (return_parse_end) *return_parse_end=end;
return c;
}
| 167,292
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void HTMLMediaElement::NoneSupported(const String& message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='" << message
<< "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
|
void HTMLMediaElement::NoneSupported(const String& message) {
void HTMLMediaElement::NoneSupported(const String& input_message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='"
<< input_message << "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
String empty_string;
const String& message = MediaShouldBeOpaque() ? empty_string : input_message;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
| 173,163
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Accelerator GetAccelerator(KeyboardCode code, int mask) {
return Accelerator(code, mask & (1 << 0), mask & (1 << 1), mask & (1 << 2));
}
Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans.
BUG=128242
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10399085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
Accelerator GetAccelerator(KeyboardCode code, int mask) {
return Accelerator(code, mask);
}
| 170,907
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(
process_->GetBrowserContext());
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
interceptor->GetResponseBody(interception_id, std::move(callback));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void NetworkHandler::GetResponseBodyForInterception(
const String& interception_id,
std::unique_ptr<GetResponseBodyForInterceptionCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(browser_context_);
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
interceptor->GetResponseBody(interception_id, std::move(callback));
}
| 172,758
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: on_handler_vanished(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
char *reason;
reason = g_strdup_printf("Cannot find handler bus name: "
"org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", FALSE, reason));
g_free(reason);
}
tcmur_unregister_handler(handler);
dbus_unexport_handler(handler);
}
Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.
CWE ID: CWE-476
|
on_handler_vanished(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
char *reason;
reason = g_strdup_printf("Cannot find handler bus name: "
"org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", FALSE, reason));
g_free(reason);
}
tcmur_unregister_dbus_handler(handler);
dbus_unexport_handler(handler);
}
| 167,632
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long ContentEncoding::ParseContentEncAESSettingsEntry(
long long start,
long long size,
IMkvReader* pReader,
ContentEncAESSettings* aes) {
assert(pReader);
assert(aes);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x7E8) {
aes->cipher_mode = UnserializeUInt(pReader, pos, size);
if (aes->cipher_mode != 1)
return E_FILE_FORMAT_INVALID;
}
pos += size; //consume payload
assert(pos <= stop);
}
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 ContentEncoding::ParseContentEncAESSettingsEntry(
long long start, long long size, IMkvReader* pReader,
ContentEncAESSettings* aes) {
assert(pReader);
assert(aes);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E8) {
aes->cipher_mode = UnserializeUInt(pReader, pos, size);
if (aes->cipher_mode != 1)
return E_FILE_FORMAT_INVALID;
}
pos += size; // consume payload
assert(pos <= stop);
}
return 0;
}
| 174,418
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ManifestChangeNotifier::DidChangeManifest() {
if (weak_factory_.HasWeakPtrs())
return;
if (!render_frame()->GetWebFrame()->IsLoading()) {
render_frame()
->GetTaskRunner(blink::TaskType::kUnspecedLoading)
->PostTask(FROM_HERE,
base::BindOnce(&ManifestChangeNotifier::ReportManifestChange,
weak_factory_.GetWeakPtr()));
return;
}
ReportManifestChange();
}
Commit Message: Fail the web app manifest fetch if the document is sandboxed.
This ensures that sandboxed pages are regarded as non-PWAs, and that
other features in the browser process which trust the web manifest do
not receive the manifest at all if the document itself cannot access the
manifest.
BUG=771709
Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4
Reviewed-on: https://chromium-review.googlesource.com/866529
Commit-Queue: Dominick Ng <[email protected]>
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531121}
CWE ID:
|
void ManifestChangeNotifier::DidChangeManifest() {
// Manifests are not considered when the current page has a unique origin.
if (!ManifestManager::CanFetchManifest(render_frame()))
return;
if (weak_factory_.HasWeakPtrs())
return;
if (!render_frame()->GetWebFrame()->IsLoading()) {
render_frame()
->GetTaskRunner(blink::TaskType::kUnspecedLoading)
->PostTask(FROM_HERE,
base::BindOnce(&ManifestChangeNotifier::ReportManifestChange,
weak_factory_.GetWeakPtr()));
return;
}
ReportManifestChange();
}
| 172,920
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void unregisterBlobURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().unregisterBlobURL(blobRegistryContext->url);
}
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:
|
static void unregisterBlobURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
if (WebBlobRegistry* registry = blobRegistry())
registry->unregisterBlobURL(blobRegistryContext->url);
}
| 170,691
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Segment::~Segment()
{
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** i = m_clusters;
Cluster** j = m_clusters + count;
while (i != j)
{
Cluster* const p = *i++;
assert(p);
delete p;
}
delete[] m_clusters;
delete m_pTracks;
delete m_pInfo;
delete m_pCues;
delete m_pChapters;
delete m_pSeekHead;
}
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
|
Segment::~Segment()
assert((total < 0) || (available <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
assert((segment_stop < 0) || (total < 0) || (segment_stop <= total));
assert((segment_stop < 0) || (m_pos <= segment_stop));
for (;;) {
if ((total >= 0) && (m_pos >= total))
break;
if ((segment_stop >= 0) && (m_pos >= segment_stop))
break;
long long pos = m_pos;
const long long element_start = pos;
| 174,470
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data)
{ SF_PRIVATE *psf ;
/* Make sure we have a valid set ot virtual pointers. */
if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf->virtual_io = SF_TRUE ;
psf->vio = *sfvirtual ;
psf->vio_user_data = user_data ;
psf->file.mode = mode ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open_virtual */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
|
sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data)
{ SF_PRIVATE *psf ;
/* Make sure we have a valid set ot virtual pointers. */
if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((psf = psf_allocate ()) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf->virtual_io = SF_TRUE ;
psf->vio = *sfvirtual ;
psf->vio_user_data = user_data ;
psf->file.mode = mode ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open_virtual */
| 170,069
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
{
return GetTime(pChapters, m_start_timecode);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
| 174,355
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return chromeos::GetKeyboardOverlayId(input_method_id);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return input_method::GetKeyboardOverlayId(input_method_id);
}
| 170,489
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RunCallbacksWithDisabled(LogoCallbacks callbacks) {
if (callbacks.on_cached_encoded_logo_available) {
std::move(callbacks.on_cached_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_cached_decoded_logo_available) {
std::move(callbacks.on_cached_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_encoded_logo_available) {
std::move(callbacks.on_fresh_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_decoded_logo_available) {
std::move(callbacks.on_fresh_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
|
void RunCallbacksWithDisabled(LogoCallbacks callbacks) {
| 171,958
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: create_surface_from_thumbnail_data (guchar *data,
gint width,
gint height,
gint rowstride)
{
guchar *cairo_pixels;
cairo_surface_t *surface;
static cairo_user_data_key_t key;
int j;
cairo_pixels = (guchar *)g_malloc (4 * width * height);
surface = cairo_image_surface_create_for_data ((unsigned char *)cairo_pixels,
CAIRO_FORMAT_RGB24,
width, height, 4 * width);
cairo_surface_set_user_data (surface, &key,
cairo_pixels, (cairo_destroy_func_t)g_free);
for (j = height; j; j--) {
guchar *p = data;
guchar *q = cairo_pixels;
guchar *end = p + 3 * width;
while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
q[0] = p[2];
q[1] = p[1];
q[2] = p[0];
#else
q[1] = p[0];
q[2] = p[1];
q[3] = p[2];
#endif
p += 3;
q += 4;
}
data += rowstride;
cairo_pixels += 4 * width;
}
return surface;
}
Commit Message:
CWE ID: CWE-189
|
create_surface_from_thumbnail_data (guchar *data,
gint width,
gint height,
gint rowstride)
{
guchar *cairo_pixels;
gint cairo_stride;
cairo_surface_t *surface;
int j;
surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
if (cairo_surface_status (surface))
return NULL;
cairo_pixels = cairo_image_surface_get_data (surface);
cairo_stride = cairo_image_surface_get_stride (surface);
for (j = height; j; j--) {
guchar *p = data;
guchar *q = cairo_pixels;
guchar *end = p + 3 * width;
while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
q[0] = p[2];
q[1] = p[1];
q[2] = p[0];
#else
q[1] = p[0];
q[2] = p[1];
q[3] = p[2];
#endif
p += 3;
q += 4;
}
data += rowstride;
cairo_pixels += cairo_stride;
}
return surface;
}
| 164,601
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool SimplifiedBackwardsTextIterator::handleTextNode()
{
m_lastTextNode = m_node;
int startOffset;
int offsetInNode;
RenderText* renderer = handleFirstLetter(startOffset, offsetInNode);
if (!renderer)
return true;
String text = renderer->text();
if (!renderer->firstTextBox() && text.length() > 0)
return true;
m_positionEndOffset = m_offset;
m_offset = startOffset + offsetInNode;
m_positionNode = m_node;
m_positionStartOffset = m_offset;
ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(m_positionStartOffset <= m_positionEndOffset);
m_textLength = m_positionEndOffset - m_positionStartOffset;
m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
ASSERT(m_textCharacters >= text.characters());
ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
m_lastCharacter = text[m_positionEndOffset - 1];
return !m_shouldHandleFirstLetter;
}
Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure.
BUG=156930,177197
[email protected]
Review URL: https://codereview.chromium.org/15057010
git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
bool SimplifiedBackwardsTextIterator::handleTextNode()
{
m_lastTextNode = m_node;
int startOffset;
int offsetInNode;
RenderText* renderer = handleFirstLetter(startOffset, offsetInNode);
if (!renderer)
return true;
String text = renderer->text();
if (!renderer->firstTextBox() && text.length() > 0)
return true;
m_positionEndOffset = m_offset;
m_offset = startOffset + offsetInNode;
m_positionNode = m_node;
m_positionStartOffset = m_offset;
ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(m_positionStartOffset <= m_positionEndOffset);
m_textLength = m_positionEndOffset - m_positionStartOffset;
m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
ASSERT(m_textCharacters >= text.characters());
RELEASE_ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
m_lastCharacter = text[m_positionEndOffset - 1];
return !m_shouldHandleFirstLetter;
}
| 171,311
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() {
return GetBooleanParam(
switches::kEnableContextualSearchNowOnTapBarIntegration,
&is_now_on_tap_bar_integration_enabled_cached_,
&is_now_on_tap_bar_integration_enabled_);
}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID:
|
bool ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() {
bool ContextualSearchFieldTrial::IsContextualCardsBarIntegrationEnabled() {
return GetBooleanParam(
switches::kEnableContextualSearchContextualCardsBarIntegration,
&is_contextual_cards_bar_integration_enabled_cached_,
&is_contextual_cards_bar_integration_enabled_);
}
| 171,644
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AppControllerImpl::LaunchApp(const std::string& app_id) {
app_service_proxy_->Launch(app_id, ui::EventFlags::EF_NONE,
apps::mojom::LaunchSource::kFromAppListGrid,
display::kDefaultDisplayId);
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416
|
void AppControllerImpl::LaunchApp(const std::string& app_id) {
void AppControllerService::LaunchApp(const std::string& app_id) {
app_service_proxy_->Launch(app_id, ui::EventFlags::EF_NONE,
apps::mojom::LaunchSource::kFromAppListGrid,
display::kDefaultDisplayId);
}
| 172,084
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void AcceleratedStaticBitmapImage::Transfer() {
CheckThread();
EnsureMailbox(kVerifiedSyncToken, GL_NEAREST);
detach_thread_at_next_check_ = true;
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
void AcceleratedStaticBitmapImage::Transfer() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
EnsureMailbox(kVerifiedSyncToken, GL_NEAREST);
DETACH_FROM_THREAD(thread_checker_);
}
| 172,598
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool AppCacheBackendImpl::MarkAsForeignEntry(
int host_id,
const GURL& document_url,
int64 cache_document_was_loaded_from) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->MarkAsForeignEntry(document_url, cache_document_was_loaded_from);
return true;
}
Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer.
BUG=551044
Review URL: https://codereview.chromium.org/1418783005
Cr-Commit-Position: refs/heads/master@{#358815}
CWE ID:
|
bool AppCacheBackendImpl::MarkAsForeignEntry(
int host_id,
const GURL& document_url,
int64 cache_document_was_loaded_from) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
return host->MarkAsForeignEntry(document_url, cache_document_was_loaded_from);
}
| 171,735
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Core(const OAuthProviderInfo& info,
net::URLRequestContextGetter* request_context_getter)
: provider_info_(info),
request_context_getter_(request_context_getter),
delegate_(NULL) {
}
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
Core(const OAuthProviderInfo& info,
net::URLRequestContextGetter* request_context_getter)
: provider_info_(info),
request_context_getter_(request_context_getter),
delegate_(NULL),
url_fetcher_type_(URL_FETCHER_NONE) {
}
| 170,805
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long long Cluster::GetLastTime() const
{
const BlockEntry* pEntry;
const long status = GetLast(pEntry);
if (status < 0) //error
return status;
if (pEntry == NULL) //empty cluster
return GetTime();
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
return pBlock->GetTime(this);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Cluster::GetLastTime() const
| 174,341
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserPpapiHostImpl::AddInstance(
PP_Instance instance,
const PepperRendererInstanceData& renderer_instance_data) {
DCHECK(instance_map_.find(instance) == instance_map_.end());
instance_map_[instance] =
base::MakeUnique<InstanceData>(renderer_instance_data);
}
Commit Message: Validate in-process plugin instance messages.
Bug: 733548, 733549
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba
Reviewed-on: https://chromium-review.googlesource.com/538908
Commit-Queue: Bill Budge <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480696}
CWE ID: CWE-20
|
void BrowserPpapiHostImpl::AddInstance(
PP_Instance instance,
const PepperRendererInstanceData& renderer_instance_data) {
// NOTE: 'instance' may be coming from a compromised renderer process. We
// take care here to make sure an attacker can't overwrite data for an
// existing plugin instance.
// See http://crbug.com/733548.
if (instance_map_.find(instance) == instance_map_.end()) {
instance_map_[instance] =
base::MakeUnique<InstanceData>(renderer_instance_data);
} else {
NOTREACHED();
}
}
| 172,309
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: VideoTrack::VideoTrack(
Segment* pSegment,
long long element_start,
long long element_size) :
Track(pSegment, element_start, element_size)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
VideoTrack::VideoTrack(
| 174,453
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) {
DCHECK(CalledOnValidThread());
DCHECK(!is_connected());
DCHECK(!remote_address_.get());
int addr_family = address.GetSockAddrFamily();
int rv = CreateSocket(addr_family);
if (rv < 0)
return rv;
if (bind_type_ == DatagramSocket::RANDOM_BIND) {
size_t addr_size =
addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize;
IPAddressNumber addr_any(addr_size);
rv = RandomBind(addr_any);
}
if (rv < 0) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv);
Close();
return rv;
}
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len)) {
Close();
return ERR_ADDRESS_INVALID;
}
rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len));
if (rv < 0) {
int result = MapSystemError(errno);
Close();
return result;
}
remote_address_.reset(new IPEndPoint(address));
return rv;
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
|
int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) {
DCHECK(CalledOnValidThread());
DCHECK(!is_connected());
DCHECK(!remote_address_.get());
int addr_family = address.GetSockAddrFamily();
int rv = CreateSocket(addr_family);
if (rv < 0)
return rv;
if (bind_type_ == DatagramSocket::RANDOM_BIND) {
size_t addr_size =
addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize;
IPAddressNumber addr_any(addr_size);
rv = RandomBind(addr_any);
}
if (rv < 0) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", -rv);
Close();
return rv;
}
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len)) {
Close();
return ERR_ADDRESS_INVALID;
}
rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len));
if (rv < 0) {
int result = MapSystemError(errno);
Close();
return result;
}
remote_address_.reset(new IPEndPoint(address));
return rv;
}
| 171,316
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool OmniboxViewViews::ShouldShowPlaceholderText() const {
return Textfield::ShouldShowPlaceholderText() &&
!model()->is_caret_visible() && !model()->is_keyword_selected();
}
Commit Message: omnibox: experiment with restoring placeholder when caret shows
Shows the "Search Google or type a URL" omnibox placeholder even when
the caret (text edit cursor) is showing / when focused. views::Textfield
works this way, as does <input placeholder="">. Omnibox and the NTP's
"fakebox" are exceptions in this regard and this experiment makes this
more consistent.
[email protected]
BUG=955585
Change-Id: I23c299c0973f2feb43f7a2be3bd3425a80b06c2d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1582315
Commit-Queue: Dan Beam <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654279}
CWE ID: CWE-200
|
bool OmniboxViewViews::ShouldShowPlaceholderText() const {
bool show_with_caret = base::FeatureList::IsEnabled(
omnibox::kUIExperimentShowPlaceholderWhenCaretShowing);
return Textfield::ShouldShowPlaceholderText() &&
(show_with_caret || !model()->is_caret_visible()) &&
!model()->is_keyword_selected();
}
| 172,543
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ExtensionTtsSpeakCompletedFunction::RunImpl() {
int request_id;
std::string error_message;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &request_id));
if (args_->GetSize() >= 2)
EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &error_message));
ExtensionTtsController::GetInstance()->OnSpeechFinished(
request_id, error_message);
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
bool ExtensionTtsSpeakCompletedFunction::RunImpl() {
bool ExtensionTtsGetVoicesFunction::RunImpl() {
result_.reset(ExtensionTtsController::GetInstance()->GetVoices(profile()));
return true;
}
| 170,385
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) {
if (mSyncSampleOffset >= 0 || data_size < 8) {
return ERROR_MALFORMED;
}
mSyncSampleOffset = data_offset;
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;
}
mNumSyncSamples = U32_AT(&header[4]);
if (mNumSyncSamples < 2) {
ALOGV("Table of sync samples is empty or has only a single entry!");
}
mSyncSamples = new uint32_t[mNumSyncSamples];
size_t size = mNumSyncSamples * sizeof(uint32_t);
if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size)
!= (ssize_t)size) {
return ERROR_IO;
}
for (size_t i = 0; i < mNumSyncSamples; ++i) {
mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1;
}
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::setSyncSampleParams(off64_t data_offset, size_t data_size) {
if (mSyncSampleOffset >= 0 || data_size < 8) {
return ERROR_MALFORMED;
}
mSyncSampleOffset = data_offset;
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;
}
mNumSyncSamples = U32_AT(&header[4]);
if (mNumSyncSamples < 2) {
ALOGV("Table of sync samples is empty or has only a single entry!");
}
uint64_t allocSize = mNumSyncSamples * sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mSyncSamples = new uint32_t[mNumSyncSamples];
size_t size = mNumSyncSamples * sizeof(uint32_t);
if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size)
!= (ssize_t)size) {
return ERROR_IO;
}
for (size_t i = 0; i < mNumSyncSamples; ++i) {
mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1;
}
return OK;
}
| 173,376
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserEventRouter::DispatchTabUpdatedEvent(
WebContents* contents, DictionaryValue* changed_properties) {
DCHECK(changed_properties);
DCHECK(contents);
scoped_ptr<ListValue> args_base(new ListValue());
args_base->AppendInteger(ExtensionTabUtil::GetTabId(contents));
args_base->Append(changed_properties);
Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
scoped_ptr<Event> event(new Event(events::kOnTabUpdated, args_base.Pass()));
event->restrict_to_profile = profile;
event->user_gesture = EventRouter::USER_GESTURE_NOT_ENABLED;
event->will_dispatch_callback =
base::Bind(&WillDispatchTabUpdatedEvent, contents);
ExtensionSystem::Get(profile)->event_router()->BroadcastEvent(event.Pass());
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
void BrowserEventRouter::DispatchTabUpdatedEvent(
WebContents* contents, scoped_ptr<DictionaryValue> changed_properties) {
DCHECK(changed_properties);
DCHECK(contents);
scoped_ptr<ListValue> args_base(new ListValue());
args_base->AppendInteger(ExtensionTabUtil::GetTabId(contents));
// Second arg: An object containing the changes to the tab state. Filled in
// by WillDispatchTabUpdatedEvent as a copy of changed_properties, if the
// extension has the tabs permission.
Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
scoped_ptr<Event> event(new Event(events::kOnTabUpdated, args_base.Pass()));
event->restrict_to_profile = profile;
event->user_gesture = EventRouter::USER_GESTURE_NOT_ENABLED;
event->will_dispatch_callback =
base::Bind(&WillDispatchTabUpdatedEvent,
contents, changed_properties.get());
ExtensionSystem::Get(profile)->event_router()->BroadcastEvent(event.Pass());
}
| 171,449
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t CameraClient::dump(int fd, const Vector<String16>& args) {
const size_t SIZE = 256;
char buffer[SIZE];
size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
len = (len > SIZE - 1) ? SIZE - 1 : len;
write(fd, buffer, len);
return mHardware->dump(fd, args);
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264
|
status_t CameraClient::dump(int fd, const Vector<String16>& args) {
return BasicClient::dump(fd, args);
}
status_t CameraClient::dumpClient(int fd, const Vector<String16>& args) {
const size_t SIZE = 256;
char buffer[SIZE];
size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
len = (len > SIZE - 1) ? SIZE - 1 : len;
write(fd, buffer, len);
return mHardware->dump(fd, args);
}
| 173,938
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static bool ndp_msg_check_valid(struct ndp_msg *msg)
{
size_t len = ndp_msg_payload_len(msg);
enum ndp_msg_type msg_type = ndp_msg_type(msg);
if (len < ndp_msg_type_info(msg_type)->raw_struct_size)
return false;
return true;
}
Commit Message: libndb: reject redirect and router advertisements from non-link-local
RFC4861 suggests that these messages should only originate from
link-local addresses in 6.1.2 (RA) and 8.1. (redirect):
Mitigates CVE-2016-3698.
Signed-off-by: Lubomir Rintel <[email protected]>
Signed-off-by: Jiri Pirko <[email protected]>
CWE ID: CWE-284
|
static bool ndp_msg_check_valid(struct ndp_msg *msg)
{
size_t len = ndp_msg_payload_len(msg);
enum ndp_msg_type msg_type = ndp_msg_type(msg);
if (len < ndp_msg_type_info(msg_type)->raw_struct_size)
return false;
if (ndp_msg_type_info(msg_type)->addrto_validate)
return ndp_msg_type_info(msg_type)->addrto_validate(&msg->addrto);
else
return true;
}
| 169,971
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static MagickBooleanType CheckMemoryOverflow(const size_t count,
const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
errno=ENOMEM;
return(MagickTrue);
}
return(MagickFalse);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119
|
static MagickBooleanType CheckMemoryOverflow(const size_t count,
| 168,539
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: irc_ctcp_dcc_filename_without_quotes (const char *filename)
{
int length;
length = strlen (filename);
if (length > 0)
{
if ((filename[0] == '\"') && (filename[length - 1] == '\"'))
return weechat_strndup (filename + 1, length - 2);
}
return strdup (filename);
}
Commit Message: irc: fix parsing of DCC filename
CWE ID: CWE-119
|
irc_ctcp_dcc_filename_without_quotes (const char *filename)
{
int length;
length = strlen (filename);
if (length > 1)
{
if ((filename[0] == '\"') && (filename[length - 1] == '\"'))
return weechat_strndup (filename + 1, length - 2);
}
return strdup (filename);
}
| 168,206
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
|
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL || sec_attr_len) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
| 169,079
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Track::Info::Info():
uid(0),
defaultDuration(0),
codecDelay(0),
seekPreRoll(0),
nameAsUTF8(NULL),
language(NULL),
codecId(NULL),
codecNameAsUTF8(NULL),
codecPrivate(NULL),
codecPrivateSize(0),
lacing(false)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Track::Info::Info():
| 174,385
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) {
major = 1;
minor = 0;
build = 0;
revision = 28;
}
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
|
void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) {
IMkvReader::~IMkvReader() {}
template<typename Type> Type* SafeArrayAlloc(unsigned long long num_elements,
unsigned long long element_size) {
if (num_elements == 0 || element_size == 0)
return NULL;
const size_t kMaxAllocSize = 0x80000000; // 2GiB
const unsigned long long num_bytes = num_elements * element_size;
if (element_size > (kMaxAllocSize / num_elements))
return NULL;
return new (std::nothrow) Type[num_bytes];
}
void GetVersion(int& major, int& minor, int& build, int& revision) {
major = 1;
minor = 0;
build = 0;
revision = 30;
}
| 173,825
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )
{
cJSON_AddItemToArray( array, create_reference( item ) );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
|
void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )
| 167,265
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264
|
status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
return BasicClient::dump(fd, args);
}
status_t ProCamera2Client::dumpClient(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
| 173,940
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
MyObject *mobject;
mobject = MY_OBJECT (object);
switch (prop_id)
{
case PROP_THIS_IS_A_STRING:
g_free (mobject->this_is_a_string);
mobject->this_is_a_string = g_value_dup_string (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
Commit Message:
CWE ID: CWE-264
|
my_object_set_property (GObject *object,
| 165,120
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y]);
}
}
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20
|
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y&255]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y&255]);
}
}
}
| 169,614
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: _TIFFmalloc(tsize_t s)
{
return (malloc((size_t) s));
}
Commit Message: * libtiff/tif_{unix,vms,win32}.c (_TIFFmalloc): ANSI C does not
require malloc() to return NULL pointer if requested allocation
size is zero. Assure that _TIFFmalloc does.
CWE ID: CWE-369
|
_TIFFmalloc(tsize_t s)
{
if (s == 0)
return ((void *) NULL);
return (malloc((size_t) s));
}
| 169,460
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: l2tp_proxy_auth_type_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
ND_PRINT((ndo, "%s", tok2str(l2tp_authentype2str,
"AuthType-#%u", EXTRACT_16BITS(ptr))));
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
l2tp_proxy_auth_type_print(netdissect_options *ndo, const u_char *dat)
l2tp_proxy_auth_type_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
if (length < 2) {
ND_PRINT((ndo, "AVP too short"));
return;
}
ND_PRINT((ndo, "%s", tok2str(l2tp_authentype2str,
"AuthType-#%u", EXTRACT_16BITS(ptr))));
}
| 167,900
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: FileReaderLoader::~FileReaderLoader()
{
terminate();
if (!m_urlForReading.isEmpty())
ThreadableBlobRegistry::unregisterBlobURL(m_urlForReading);
}
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:
|
FileReaderLoader::~FileReaderLoader()
{
terminate();
if (!m_urlForReading.isEmpty())
BlobRegistry::unregisterBlobURL(m_urlForReading);
}
| 170,693
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void buf_to_pages(const void *buf, size_t buflen,
struct page **pages, unsigned int *pgbase)
{
const void *p = buf;
*pgbase = offset_in_page(buf);
p -= *pgbase;
while (p < buf + buflen) {
*(pages++) = virt_to_page(p);
p += PAGE_CACHE_SIZE;
}
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: [email protected]
Signed-off-by: Andy Adamson <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189
|
static void buf_to_pages(const void *buf, size_t buflen,
| 165,717
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool PrintWebViewHelper::InitPrintSettingsAndPrepareFrame(
WebKit::WebFrame* frame, WebKit::WebNode* node,
scoped_ptr<PrepareFrameAndViewForPrint>* prepare) {
if (!InitPrintSettings(frame, node, false))
return false;
DCHECK(!prepare->get());
prepare->reset(new PrepareFrameAndViewForPrint(print_pages_params_->params,
frame, node));
UpdatePrintableSizeInPrintParameters(frame, node, prepare->get(),
&print_pages_params_->params);
Send(new PrintHostMsg_DidGetDocumentCookie(
routing_id(), print_pages_params_->params.document_cookie));
return true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool PrintWebViewHelper::InitPrintSettingsAndPrepareFrame(
WebKit::WebFrame* frame, WebKit::WebNode* node,
scoped_ptr<PrepareFrameAndViewForPrint>* prepare) {
if (!InitPrintSettings(frame))
return false;
DCHECK(!prepare->get());
prepare->reset(new PrepareFrameAndViewForPrint(print_pages_params_->params,
frame, node));
UpdatePrintableSizeInPrintParameters(frame, node, prepare->get(),
&print_pages_params_->params);
Send(new PrintHostMsg_DidGetDocumentCookie(
routing_id(), print_pages_params_->params.document_cookie));
return true;
}
| 170,260
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next)
{
File* file = V8File::toNative(value.As<v8::Object>());
if (!file)
return 0;
if (file->hasBeenClosed())
return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next);
int blobIndex = -1;
m_blobDataHandles.add(file->uuid(), file->blobDataHandle());
if (appendFileInfo(file, &blobIndex)) {
ASSERT(blobIndex >= 0);
m_writer.writeFileIndex(blobIndex);
} else {
m_writer.writeFile(*file);
}
return 0;
}
Commit Message: Replace further questionable HashMap::add usages in bindings
BUG=390928
[email protected]
Review URL: https://codereview.chromium.org/411273002
git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next)
{
File* file = V8File::toNative(value.As<v8::Object>());
if (!file)
return 0;
if (file->hasBeenClosed())
return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next);
int blobIndex = -1;
m_blobDataHandles.set(file->uuid(), file->blobDataHandle());
if (appendFileInfo(file, &blobIndex)) {
ASSERT(blobIndex >= 0);
m_writer.writeFileIndex(blobIndex);
} else {
m_writer.writeFile(*file);
}
return 0;
}
| 171,651
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void fdct8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct8x8_c(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void fdct8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
const int kSignBiasMaxDiff255 = 1500;
const int kSignBiasMaxDiff15 = 10000;
typedef void (*FdctFunc)(const int16_t *in, tran_low_t *out, int stride);
typedef void (*IdctFunc)(const tran_low_t *in, uint8_t *out, int stride);
typedef void (*FhtFunc)(const int16_t *in, tran_low_t *out, int stride,
int tx_type);
typedef void (*IhtFunc)(const tran_low_t *in, uint8_t *out, int stride,
int tx_type);
typedef std::tr1::tuple<FdctFunc, IdctFunc, int, vpx_bit_depth_t> Dct8x8Param;
typedef std::tr1::tuple<FhtFunc, IhtFunc, int, vpx_bit_depth_t> Ht8x8Param;
typedef std::tr1::tuple<IdctFunc, IdctFunc, int, vpx_bit_depth_t> Idct8x8Param;
void reference_8x8_dct_1d(const double in[8], double out[8], int stride) {
const double kInvSqrt2 = 0.707106781186547524400844362104;
for (int k = 0; k < 8; k++) {
out[k] = 0.0;
for (int n = 0; n < 8; n++)
out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 16.0);
if (k == 0)
out[k] = out[k] * kInvSqrt2;
}
}
| 174,564
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool Get(const std::string& addr, int* out_value) {
base::AutoLock lock(lock_);
PrintPreviewRequestIdMap::const_iterator it = map_.find(addr);
if (it == map_.end())
return false;
*out_value = it->second;
return true;
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
bool Get(const std::string& addr, int* out_value) {
// Gets the value for |preview_id|.
// Returns true and sets |out_value| on success.
bool Get(int32 preview_id, int* out_value) {
base::AutoLock lock(lock_);
PrintPreviewRequestIdMap::const_iterator it = map_.find(preview_id);
if (it == map_.end())
return false;
*out_value = it->second;
return true;
}
| 170,831
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int pptp_bind(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len)
{
struct sock *sk = sock->sk;
struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr;
struct pppox_sock *po = pppox_sk(sk);
struct pptp_opt *opt = &po->proto.pptp;
int error = 0;
lock_sock(sk);
opt->src_addr = sp->sa_addr.pptp;
if (add_chan(po))
error = -EBUSY;
release_sock(sk);
return error;
}
Commit Message: pptp: verify sockaddr_len in pptp_bind() and pptp_connect()
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
|
static int pptp_bind(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len)
{
struct sock *sk = sock->sk;
struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr;
struct pppox_sock *po = pppox_sk(sk);
struct pptp_opt *opt = &po->proto.pptp;
int error = 0;
if (sockaddr_len < sizeof(struct sockaddr_pppox))
return -EINVAL;
lock_sock(sk);
opt->src_addr = sp->sa_addr.pptp;
if (add_chan(po))
error = -EBUSY;
release_sock(sk);
return error;
}
| 166,560
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SoftMPEG2::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20
|
void SoftMPEG2::setDecodeArgs(
bool SoftMPEG2::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
uint8_t *pBuf;
if (outHeader) {
if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) {
android_errorWriteLog(0x534e4554, "27569635");
return false;
}
pBuf = outHeader->pBuffer;
} else {
// mFlushOutBuffer always has the right size.
pBuf = mFlushOutBuffer;
}
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return true;
}
| 174,184
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
{
struct super_block *sb;
int err;
int rc;
if (!ext4_handle_valid(handle)) {
ext4_put_nojournal(handle);
return 0;
}
if (!handle->h_transaction) {
err = jbd2_journal_stop(handle);
return handle->h_err ? handle->h_err : err;
}
sb = handle->h_transaction->t_journal->j_private;
err = handle->h_err;
rc = jbd2_journal_stop(handle);
if (!err)
err = rc;
if (err)
__ext4_std_error(sb, where, line, err);
return err;
}
Commit Message: ext4: fix potential use after free in __ext4_journal_stop
There is a use-after-free possibility in __ext4_journal_stop() in the
case that we free the handle in the first jbd2_journal_stop() because
we're referencing handle->h_err afterwards. This was introduced in
9705acd63b125dee8b15c705216d7186daea4625 and it is wrong. Fix it by
storing the handle->h_err value beforehand and avoid referencing
potentially freed handle.
Fixes: 9705acd63b125dee8b15c705216d7186daea4625
Signed-off-by: Lukas Czerner <[email protected]>
Reviewed-by: Andreas Dilger <[email protected]>
Cc: [email protected]
CWE ID: CWE-416
|
int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
{
struct super_block *sb;
int err;
int rc;
if (!ext4_handle_valid(handle)) {
ext4_put_nojournal(handle);
return 0;
}
err = handle->h_err;
if (!handle->h_transaction) {
rc = jbd2_journal_stop(handle);
return err ? err : rc;
}
sb = handle->h_transaction->t_journal->j_private;
rc = jbd2_journal_stop(handle);
if (!err)
err = rc;
if (err)
__ext4_std_error(sb, where, line, err);
return err;
}
| 167,465
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: destroy_one_secret (gpointer data)
{
char *secret = (char *) data;
/* Don't leave the secret lying around in memory */
g_message ("%s: destroying %s", __func__, secret);
memset (secret, 0, strlen (secret));
g_free (secret);
}
Commit Message:
CWE ID: CWE-200
|
destroy_one_secret (gpointer data)
{
char *secret = (char *) data;
/* Don't leave the secret lying around in memory */
memset (secret, 0, strlen (secret));
g_free (secret);
}
| 164,689
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long long SegmentInfo::GetDuration() const
{
if (m_duration < 0)
return -1;
assert(m_timecodeScale >= 1);
const double dd = double(m_duration) * double(m_timecodeScale);
const long long d = static_cast<long long>(dd);
return d;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long SegmentInfo::GetDuration() const
| 174,307
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir,
const FilePath& text) {
FilePath old_cur_directory;
if (!base_dir.empty()) {
file_util::GetCurrentDirectory(&old_cur_directory);
file_util::SetCurrentDirectory(base_dir);
}
FilePath::StringType trimmed;
PrepareStringForFileOps(text, &trimmed);
bool is_file = true;
FilePath full_path;
if (!ValidPathForFile(trimmed, &full_path)) {
#if defined(OS_WIN)
std::wstring unescaped = UTF8ToWide(UnescapeURLComponent(
WideToUTF8(trimmed),
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS));
#elif defined(OS_POSIX)
std::string unescaped = UnescapeURLComponent(
trimmed,
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
#endif
if (!ValidPathForFile(unescaped, &full_path))
is_file = false;
}
if (!base_dir.empty())
file_util::SetCurrentDirectory(old_cur_directory);
if (is_file) {
GURL file_url = net::FilePathToFileURL(full_path);
if (file_url.is_valid())
return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL,
NULL, NULL)));
}
#if defined(OS_WIN)
std::string text_utf8 = WideToUTF8(text.value());
#elif defined(OS_POSIX)
std::string text_utf8 = text.value();
#endif
return FixupURL(text_utf8, std::string());
}
Commit Message: Be a little more careful whether something is an URL or a file path.
BUG=72492
Review URL: http://codereview.chromium.org/7572046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95731 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir,
const FilePath& text) {
FilePath old_cur_directory;
if (!base_dir.empty()) {
file_util::GetCurrentDirectory(&old_cur_directory);
file_util::SetCurrentDirectory(base_dir);
}
FilePath::StringType trimmed;
PrepareStringForFileOps(text, &trimmed);
bool is_file = true;
// Avoid recognizing definite non-file URLs as file paths.
GURL gurl(trimmed);
if (gurl.is_valid() && gurl.IsStandard())
is_file = false;
FilePath full_path;
if (is_file && !ValidPathForFile(trimmed, &full_path)) {
#if defined(OS_WIN)
std::wstring unescaped = UTF8ToWide(UnescapeURLComponent(
WideToUTF8(trimmed),
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS));
#elif defined(OS_POSIX)
std::string unescaped = UnescapeURLComponent(
trimmed,
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
#endif
if (!ValidPathForFile(unescaped, &full_path))
is_file = false;
}
if (!base_dir.empty())
file_util::SetCurrentDirectory(old_cur_directory);
if (is_file) {
GURL file_url = net::FilePathToFileURL(full_path);
if (file_url.is_valid())
return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL,
NULL, NULL)));
}
#if defined(OS_WIN)
std::string text_utf8 = WideToUTF8(text.value());
#elif defined(OS_POSIX)
std::string text_utf8 = text.value();
#endif
return FixupURL(text_utf8, std::string());
}
| 170,364
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: IndexedDBDispatcher::~IndexedDBDispatcher() {
g_idb_dispatcher_tls.Pointer()->Set(NULL);
}
Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created.
This could happen if there are IDB objects that survive the call to
didStopWorkerRunLoop.
BUG=121734
TEST=
Review URL: http://codereview.chromium.org/9999035
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
IndexedDBDispatcher::~IndexedDBDispatcher() {
g_idb_dispatcher_tls.Pointer()->Set(HAS_BEEN_DELETED);
}
| 171,040
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void toggle_fpga_eeprom_bus(bool cpu_own)
{
qrio_gpio_direction_output(GPIO_A, PROM_SEL_L, !cpu_own);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
|
static void toggle_fpga_eeprom_bus(bool cpu_own)
{
qrio_gpio_direction_output(QRIO_GPIO_A, PROM_SEL_L, !cpu_own);
}
| 169,634
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CrosLibrary::TestApi::SetSyslogsLibrary(
SyslogsLibrary* library, bool own) {
library_->syslogs_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
void CrosLibrary::TestApi::SetSyslogsLibrary(
| 170,646
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ParamTraits<GURL>::Write(Message* m, const GURL& p) {
DCHECK(p.possibly_invalid_spec().length() <= content::kMaxURLChars);
m->WriteString(p.possibly_invalid_spec());
}
Commit Message: Beware of print-read inconsistency when serializing GURLs.
BUG=165622
Review URL: https://chromiumcodereview.appspot.com/11576038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173583 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
void ParamTraits<GURL>::Write(Message* m, const GURL& p) {
DCHECK(p.possibly_invalid_spec().length() <= content::kMaxURLChars);
// Beware of print-parse inconsistency which would change an invalid
// URL into a valid one. Ideally, the message would contain this flag
// so that the read side could make the check, but performing it here
// avoids changing the on-the-wire representation of such a fundamental
// type as GURL. See https://crbug.com/166486 for additional work in
// this area.
if (!p.is_valid()) {
GURL reconstructed_url(p.possibly_invalid_spec());
if (reconstructed_url.is_valid()) {
DLOG(WARNING) << "GURL string " << p.possibly_invalid_spec()
<< " (marked invalid) but parsed as valid.";
m->WriteString(std::string());
return;
}
}
m->WriteString(p.possibly_invalid_spec());
}
| 171,503
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CloudPolicyController::StopAutoRetry() {
scheduler_->CancelDelayedWork();
backend_.reset();
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void CloudPolicyController::StopAutoRetry() {
void CloudPolicyController::Reset() {
SetState(STATE_TOKEN_UNAVAILABLE);
}
| 170,282
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::CancelPairing() {
if (!RunPairingCallbacks(CANCELLED)) {
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
UnregisterAgent();
}
}
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::CancelPairing() {
if (!pairing_context_.get() || !pairing_context_->CancelPairing()) {
VLOG(1) << object_path_.value() << ": No pairing context or callback. "
<< "Sending explicit cancel";
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
CancelPairing(
object_path_,
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnCancelPairingError,
weak_ptr_factory_.GetWeakPtr()));
// delegate is going to be freed before things complete, so clear out the
// context holding it.
pairing_context_.reset();
}
}
| 171,219
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void LocalFileSystem::fileSystemAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
PassRefPtr<CallbackWrapper> callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void LocalFileSystem::fileSystemAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
CallbackWrapper* callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
| 171,426
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool BitReaderCore::ReadBitsInternal(int num_bits, uint64_t* out) {
DCHECK_GE(num_bits, 0);
if (num_bits == 0) {
*out = 0;
return true;
}
if (num_bits > nbits_ && !Refill(num_bits)) {
nbits_ = 0;
reg_ = 0;
return false;
}
bits_read_ += num_bits;
if (num_bits == kRegWidthInBits) {
*out = reg_;
reg_ = 0;
nbits_ = 0;
return true;
}
*out = reg_ >> (kRegWidthInBits - num_bits);
reg_ <<= num_bits;
nbits_ -= num_bits;
return true;
}
Commit Message: Cleanup media BitReader ReadBits() calls
Initialize temporary values, check return values.
Small tweaks to solution proposed by [email protected].
Bug: 929962
Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735
Reviewed-on: https://chromium-review.googlesource.com/c/1481085
Commit-Queue: Chrome Cunningham <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#634889}
CWE ID: CWE-200
|
bool BitReaderCore::ReadBitsInternal(int num_bits, uint64_t* out) {
DCHECK_GE(num_bits, 0);
if (num_bits == 0) {
*out = 0;
return true;
}
if (num_bits > nbits_ && !Refill(num_bits)) {
nbits_ = 0;
reg_ = 0;
*out = 0;
return false;
}
bits_read_ += num_bits;
if (num_bits == kRegWidthInBits) {
*out = reg_;
reg_ = 0;
nbits_ = 0;
return true;
}
*out = reg_ >> (kRegWidthInBits - num_bits);
reg_ <<= num_bits;
nbits_ -= num_bits;
return true;
}
| 173,017
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void UserSelectionScreen::FillUserMojoStruct(
const user_manager::User* user,
bool is_owner,
bool is_signin_to_add,
proximity_auth::mojom::AuthType auth_type,
const std::vector<std::string>* public_session_recommended_locales,
ash::mojom::LoginUserInfo* user_info) {
user_info->basic_user_info = ash::mojom::UserInfo::New();
user_info->basic_user_info->type = user->GetType();
user_info->basic_user_info->account_id = user->GetAccountId();
user_info->basic_user_info->display_name =
base::UTF16ToUTF8(user->GetDisplayName());
user_info->basic_user_info->display_email = user->display_email();
user_info->basic_user_info->avatar = BuildMojoUserAvatarForUser(user);
user_info->auth_type = auth_type;
user_info->is_signed_in = user->is_logged_in();
user_info->is_device_owner = is_owner;
user_info->can_remove = CanRemoveUser(user);
user_info->allow_fingerprint_unlock = AllowFingerprintForUser(user);
if (!is_signin_to_add) {
user_info->is_multiprofile_allowed = true;
} else {
GetMultiProfilePolicy(user, &user_info->is_multiprofile_allowed,
&user_info->multiprofile_policy);
}
if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) {
user_info->public_account_info = ash::mojom::PublicAccountInfo::New();
std::string domain;
if (GetEnterpriseDomain(&domain))
user_info->public_account_info->enterprise_domain = domain;
std::string selected_locale;
bool has_multiple_locales;
std::unique_ptr<base::ListValue> available_locales =
GetPublicSessionLocales(public_session_recommended_locales,
&selected_locale, &has_multiple_locales);
DCHECK(available_locales);
user_info->public_account_info->available_locales =
lock_screen_utils::FromListValueToLocaleItem(
std::move(available_locales));
user_info->public_account_info->default_locale = selected_locale;
user_info->public_account_info->show_advanced_view = has_multiple_locales;
}
}
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:
|
void UserSelectionScreen::FillUserMojoStruct(
| 172,201
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ )
{
int rc = 0;
gnutls_session *session = gnutls_malloc(sizeof(gnutls_session));
gnutls_init(session, type);
# ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
/* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */
gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL);
/* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */
# else
gnutls_set_default_priority(*session);
gnutls_kx_set_priority(*session, tls_kx_order);
# endif
gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock));
switch (type) {
case GNUTLS_SERVER:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_s);
break;
case GNUTLS_CLIENT:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_c);
break;
}
do {
rc = gnutls_handshake(*session);
} while (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN);
if (rc < 0) {
crm_err("Handshake failed: %s", gnutls_strerror(rc));
gnutls_deinit(*session);
gnutls_free(session);
return NULL;
}
return session;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ )
void *
crm_create_anon_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */, void *credentials)
{
gnutls_session *session = gnutls_malloc(sizeof(gnutls_session));
gnutls_init(session, type);
# ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
/* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */
gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL);
/* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */
# else
gnutls_set_default_priority(*session);
gnutls_kx_set_priority(*session, anon_tls_kx_order);
# endif
gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock));
switch (type) {
case GNUTLS_SERVER:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_server_credentials_t) credentials);
break;
case GNUTLS_CLIENT:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_client_credentials_t) credentials);
break;
}
return session;
}
| 166,162
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RenderMessageFilter::GetPluginsCallback(
IPC::Message* reply_msg,
const std::vector<webkit::WebPluginInfo>& all_plugins) {
PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter();
std::vector<webkit::WebPluginInfo> plugins;
int child_process_id = -1;
int routing_id = MSG_ROUTING_NONE;
for (size_t i = 0; i < all_plugins.size(); ++i) {
webkit::WebPluginInfo plugin(all_plugins[i]);
if (!filter || filter->IsPluginEnabled(child_process_id,
routing_id,
resource_context_,
GURL(),
GURL(),
&plugin)) {
plugins.push_back(plugin);
}
}
ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
Send(reply_msg);
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287
|
void RenderMessageFilter::GetPluginsCallback(
IPC::Message* reply_msg,
const std::vector<webkit::WebPluginInfo>& all_plugins) {
PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter();
std::vector<webkit::WebPluginInfo> plugins;
int child_process_id = -1;
int routing_id = MSG_ROUTING_NONE;
for (size_t i = 0; i < all_plugins.size(); ++i) {
webkit::WebPluginInfo plugin(all_plugins[i]);
if (!filter || filter->IsPluginAvailable(child_process_id,
routing_id,
resource_context_,
GURL(),
GURL(),
&plugin)) {
plugins.push_back(plugin);
}
}
ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
Send(reply_msg);
}
| 171,476
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent,
int start, int count) {
removed_count_++;
}
Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods.
BUG=None
TEST=None
[email protected]
Review URL: http://codereview.chromium.org/7046093
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent,
virtual void TreeNodesRemoved(TreeModel* model,
TreeModelNode* parent,
int start,
int count) OVERRIDE {
removed_count_++;
}
| 170,471
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.