instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: s_aes_process(stream_state * ss, stream_cursor_read * pr,
stream_cursor_write * pw, bool last)
{
stream_aes_state *const state = (stream_aes_state *) ss;
const unsigned char *limit;
const long in_size = pr->limit - pr->ptr;
const long out_size = pw->limit - pw->ptr;
unsigned char temp[16];
int status = 0;
/* figure out if we're going to run out of space */
if (in_size > out_size) {
limit = pr->ptr + out_size;
status = 1; /* need more output space */
} else {
limit = pr->limit;
status = last ? EOFC : 0; /* need more input */
}
/* set up state and context */
if (state->ctx == NULL) {
/* allocate the aes context. this is a public struct but it
contains internal pointers, so we need to store it separately
in immovable memory like any opaque structure. */
state->ctx = (aes_context *)gs_alloc_bytes_immovable(state->memory,
sizeof(aes_context), "aes context structure");
if (state->ctx == NULL) {
gs_throw(gs_error_VMerror, "could not allocate aes context");
return ERRC;
}
if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) {
gs_throw1(gs_error_rangecheck, "invalid aes key length (%d bytes)",
state->keylength);
}
aes_setkey_dec(state->ctx, state->key, state->keylength * 8);
}
if (!state->initialized) {
/* read the initialization vector from the first 16 bytes */
if (in_size < 16) return 0; /* get more data */
memcpy(state->iv, pr->ptr + 1, 16);
state->initialized = 1;
pr->ptr += 16;
}
/* decrypt available blocks */
while (pr->ptr + 16 <= limit) {
aes_crypt_cbc(state->ctx, AES_DECRYPT, 16, state->iv,
pr->ptr + 1, temp);
pr->ptr += 16;
if (last && pr->ptr == pr->limit) {
/* we're on the last block; unpad if necessary */
int pad;
if (state->use_padding) {
/* we are using RFC 1423-style padding, so the last byte of the
plaintext gives the number of bytes to discard */
pad = temp[15];
if (pad < 1 || pad > 16) {
/* Bug 692343 - don't error here, just warn. Take padding to be
* zero. This may give us a stream that's too long - preferable
* to the alternatives. */
gs_warn1("invalid aes padding byte (0x%02x)",
(unsigned char)pad);
pad = 0;
}
} else {
/* not using padding */
pad = 0;
}
memcpy(pw->ptr + 1, temp, 16 - pad);
pw->ptr += 16 - pad;
return EOFC;
}
memcpy(pw->ptr + 1, temp, 16);
pw->ptr += 16;
}
/* if we got to the end of the file without triggering the padding
check, the input must not have been a multiple of 16 bytes long.
complain. */
if (status == EOFC) {
gs_throw(gs_error_rangecheck, "aes stream isn't a multiple of 16 bytes");
return 0;
}
return status;
}
Commit Message:
CWE ID: CWE-119
|
s_aes_process(stream_state * ss, stream_cursor_read * pr,
stream_cursor_write * pw, bool last)
{
stream_aes_state *const state = (stream_aes_state *) ss;
const unsigned char *limit;
const long in_size = pr->limit - pr->ptr;
const long out_size = pw->limit - pw->ptr;
unsigned char temp[16];
int status = 0;
/* figure out if we're going to run out of space */
if (in_size > out_size) {
limit = pr->ptr + out_size;
status = 1; /* need more output space */
} else {
limit = pr->limit;
status = last ? EOFC : 0; /* need more input */
}
/* set up state and context */
if (state->ctx == NULL) {
/* allocate the aes context. this is a public struct but it
contains internal pointers, so we need to store it separately
in immovable memory like any opaque structure. */
state->ctx = (aes_context *)gs_alloc_bytes_immovable(state->memory,
sizeof(aes_context), "aes context structure");
if (state->ctx == NULL) {
gs_throw(gs_error_VMerror, "could not allocate aes context");
return ERRC;
}
memset(state->ctx, 0x00, sizeof(aes_context));
if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) {
gs_throw1(gs_error_rangecheck, "invalid aes key length (%d bytes)",
state->keylength);
}
aes_setkey_dec(state->ctx, state->key, state->keylength * 8);
}
if (!state->initialized) {
/* read the initialization vector from the first 16 bytes */
if (in_size < 16) return 0; /* get more data */
memcpy(state->iv, pr->ptr + 1, 16);
state->initialized = 1;
pr->ptr += 16;
}
/* decrypt available blocks */
while (pr->ptr + 16 <= limit) {
aes_crypt_cbc(state->ctx, AES_DECRYPT, 16, state->iv,
pr->ptr + 1, temp);
pr->ptr += 16;
if (last && pr->ptr == pr->limit) {
/* we're on the last block; unpad if necessary */
int pad;
if (state->use_padding) {
/* we are using RFC 1423-style padding, so the last byte of the
plaintext gives the number of bytes to discard */
pad = temp[15];
if (pad < 1 || pad > 16) {
/* Bug 692343 - don't error here, just warn. Take padding to be
* zero. This may give us a stream that's too long - preferable
* to the alternatives. */
gs_warn1("invalid aes padding byte (0x%02x)",
(unsigned char)pad);
pad = 0;
}
} else {
/* not using padding */
pad = 0;
}
memcpy(pw->ptr + 1, temp, 16 - pad);
pw->ptr += 16 - pad;
return EOFC;
}
memcpy(pw->ptr + 1, temp, 16);
pw->ptr += 16;
}
/* if we got to the end of the file without triggering the padding
check, the input must not have been a multiple of 16 bytes long.
complain. */
if (status == EOFC) {
gs_throw(gs_error_rangecheck, "aes stream isn't a multiple of 16 bytes");
return 0;
}
return status;
}
| 164,703
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct svc_serv *nfs_callback_create_svc(int minorversion)
{
struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion];
struct svc_serv *serv;
struct svc_serv_ops *sv_ops;
/*
* Check whether we're already up and running.
*/
if (cb_info->serv) {
/*
* Note: increase service usage, because later in case of error
* svc_destroy() will be called.
*/
svc_get(cb_info->serv);
return cb_info->serv;
}
switch (minorversion) {
case 0:
sv_ops = nfs4_cb_sv_ops[0];
break;
default:
sv_ops = nfs4_cb_sv_ops[1];
}
if (sv_ops == NULL)
return ERR_PTR(-ENOTSUPP);
/*
* Sanity check: if there's no task,
* we should be the first user ...
*/
if (cb_info->users)
printk(KERN_WARNING "nfs_callback_create_svc: no kthread, %d users??\n",
cb_info->users);
serv = svc_create(&nfs4_callback_program, NFS4_CALLBACK_BUFSIZE, sv_ops);
if (!serv) {
printk(KERN_ERR "nfs_callback_create_svc: create service failed\n");
return ERR_PTR(-ENOMEM);
}
cb_info->serv = serv;
/* As there is only one thread we need to over-ride the
* default maximum of 80 connections
*/
serv->sv_maxconn = 1024;
dprintk("nfs_callback_create_svc: service created\n");
return serv;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
static struct svc_serv *nfs_callback_create_svc(int minorversion)
{
struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion];
struct svc_serv *serv;
struct svc_serv_ops *sv_ops;
/*
* Check whether we're already up and running.
*/
if (cb_info->serv) {
/*
* Note: increase service usage, because later in case of error
* svc_destroy() will be called.
*/
svc_get(cb_info->serv);
return cb_info->serv;
}
switch (minorversion) {
case 0:
sv_ops = nfs4_cb_sv_ops[0];
break;
default:
sv_ops = nfs4_cb_sv_ops[1];
}
if (sv_ops == NULL)
return ERR_PTR(-ENOTSUPP);
/*
* Sanity check: if there's no task,
* we should be the first user ...
*/
if (cb_info->users)
printk(KERN_WARNING "nfs_callback_create_svc: no kthread, %d users??\n",
cb_info->users);
serv = svc_create_pooled(&nfs4_callback_program, NFS4_CALLBACK_BUFSIZE, sv_ops);
if (!serv) {
printk(KERN_ERR "nfs_callback_create_svc: create service failed\n");
return ERR_PTR(-ENOMEM);
}
cb_info->serv = serv;
/* As there is only one thread we need to over-ride the
* default maximum of 80 connections
*/
serv->sv_maxconn = 1024;
dprintk("nfs_callback_create_svc: service created\n");
return serv;
}
| 168,139
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void StartSync(const StartSyncArgs& args,
OneClickSigninSyncStarter::StartSyncMode start_mode) {
if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
return;
}
OneClickSigninSyncStarter::ConfirmationRequired confirmation =
args.confirmation_required;
if (start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST &&
confirmation == OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN) {
confirmation = OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
}
new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index,
args.email, args.password, start_mode,
args.force_same_tab_navigation,
confirmation);
int action = one_click_signin::HISTOGRAM_MAX;
switch (args.auto_accept) {
case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
break;
case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
action =
start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS;
break;
case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
default:
NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
break;
}
if (action != one_click_signin::HISTOGRAM_MAX)
LogOneClickHistogramValue(action);
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void StartSync(const StartSyncArgs& args,
OneClickSigninSyncStarter::StartSyncMode start_mode) {
if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
return;
}
new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index,
args.email, args.password, start_mode,
args.force_same_tab_navigation,
args.confirmation_required,
args.source);
int action = one_click_signin::HISTOGRAM_MAX;
switch (args.auto_accept) {
case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
break;
case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
action =
start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS;
break;
case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
default:
NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
break;
}
if (action != one_click_signin::HISTOGRAM_MAX)
LogOneClickHistogramValue(action);
}
| 171,244
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior,
UpdateFromElementBehavior update_behavior,
const KURL& url,
ReferrerPolicy referrer_policy,
UpdateType update_type) {
pending_task_.reset();
std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter;
load_delay_counter.swap(delay_until_do_update_from_element_);
Document& document = element_->GetDocument();
if (!document.IsActive())
return;
AtomicString image_source_url = element_->ImageSourceURL();
ImageResourceContent* new_image_content = nullptr;
if (!url.IsNull() && !url.IsEmpty()) {
ResourceLoaderOptions resource_loader_options;
resource_loader_options.initiator_info.name = GetElement()->localName();
ResourceRequest resource_request(url);
if (update_behavior == kUpdateForcedReload) {
resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache);
resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform);
}
if (referrer_policy != kReferrerPolicyDefault) {
resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer(
referrer_policy, url, document.OutgoingReferrer()));
}
if (IsHTMLPictureElement(GetElement()->parentNode()) ||
!GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull())
resource_request.SetRequestContext(
WebURLRequest::kRequestContextImageSet);
bool page_is_being_dismissed =
document.PageDismissalEventBeingDispatched() != Document::kNoDismissal;
if (page_is_being_dismissed) {
resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control,
"max-age=0");
resource_request.SetKeepalive(true);
resource_request.SetRequestContext(WebURLRequest::kRequestContextPing);
}
FetchParameters params(resource_request, resource_loader_options);
ConfigureRequest(params, bypass_behavior, *element_,
document.GetClientHintsPreferences());
if (update_behavior != kUpdateForcedReload && document.GetFrame())
document.GetFrame()->MaybeAllowImagePlaceholder(params);
new_image_content = ImageResourceContent::Fetch(params, document.Fetcher());
if (page_is_being_dismissed)
new_image_content = nullptr;
ClearFailedLoadURL();
} else {
if (!image_source_url.IsNull()) {
DispatchErrorEvent();
}
NoImageResourceToLoad();
}
ImageResourceContent* old_image_content = image_content_.Get();
if (old_image_content != new_image_content)
RejectPendingDecodes(update_type);
if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() &&
element_->GetLayoutObject()->IsImage() &&
new_image_content == old_image_content) {
ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged();
} else {
if (pending_load_event_.IsActive())
pending_load_event_.Cancel();
if (pending_error_event_.IsActive() && new_image_content)
pending_error_event_.Cancel();
UpdateImageState(new_image_content);
UpdateLayoutObject();
if (new_image_content) {
new_image_content->AddObserver(this);
}
if (old_image_content) {
old_image_content->RemoveObserver(this);
}
}
if (LayoutImageResource* image_resource = GetLayoutImageResource())
image_resource->ResetAnimation();
}
Commit Message: Use correct Request Context when EMBED or OBJECT requests an image
When an OBJECT or EMBED element requests an image, it does so using
an ImageLoader. To ensure that Content-Security-Policy restrictions
are applied correctly in this scenario, we must adjust the request's
context to indicate the originating element.
Bug: 811691
Change-Id: I0fd8010970a12e68e845a54310695acc0b3f7625
Reviewed-on: https://chromium-review.googlesource.com/924589
Commit-Queue: Eric Lawrence <elawrence@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#537846}
CWE ID: CWE-20
|
void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior,
UpdateFromElementBehavior update_behavior,
const KURL& url,
ReferrerPolicy referrer_policy,
UpdateType update_type) {
pending_task_.reset();
std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter;
load_delay_counter.swap(delay_until_do_update_from_element_);
Document& document = element_->GetDocument();
if (!document.IsActive())
return;
AtomicString image_source_url = element_->ImageSourceURL();
ImageResourceContent* new_image_content = nullptr;
if (!url.IsNull() && !url.IsEmpty()) {
ResourceLoaderOptions resource_loader_options;
resource_loader_options.initiator_info.name = GetElement()->localName();
ResourceRequest resource_request(url);
if (update_behavior == kUpdateForcedReload) {
resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache);
resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform);
}
if (referrer_policy != kReferrerPolicyDefault) {
resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer(
referrer_policy, url, document.OutgoingReferrer()));
}
// Correct the RequestContext if necessary.
if (IsHTMLPictureElement(GetElement()->parentNode()) ||
!GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) {
resource_request.SetRequestContext(
WebURLRequest::kRequestContextImageSet);
} else if (IsHTMLObjectElement(GetElement())) {
resource_request.SetRequestContext(WebURLRequest::kRequestContextObject);
} else if (IsHTMLEmbedElement(GetElement())) {
resource_request.SetRequestContext(WebURLRequest::kRequestContextEmbed);
}
bool page_is_being_dismissed =
document.PageDismissalEventBeingDispatched() != Document::kNoDismissal;
if (page_is_being_dismissed) {
resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control,
"max-age=0");
resource_request.SetKeepalive(true);
resource_request.SetRequestContext(WebURLRequest::kRequestContextPing);
}
FetchParameters params(resource_request, resource_loader_options);
ConfigureRequest(params, bypass_behavior, *element_,
document.GetClientHintsPreferences());
if (update_behavior != kUpdateForcedReload && document.GetFrame())
document.GetFrame()->MaybeAllowImagePlaceholder(params);
new_image_content = ImageResourceContent::Fetch(params, document.Fetcher());
if (page_is_being_dismissed)
new_image_content = nullptr;
ClearFailedLoadURL();
} else {
if (!image_source_url.IsNull()) {
DispatchErrorEvent();
}
NoImageResourceToLoad();
}
ImageResourceContent* old_image_content = image_content_.Get();
if (old_image_content != new_image_content)
RejectPendingDecodes(update_type);
if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() &&
element_->GetLayoutObject()->IsImage() &&
new_image_content == old_image_content) {
ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged();
} else {
if (pending_load_event_.IsActive())
pending_load_event_.Cancel();
if (pending_error_event_.IsActive() && new_image_content)
pending_error_event_.Cancel();
UpdateImageState(new_image_content);
UpdateLayoutObject();
if (new_image_content) {
new_image_content->AddObserver(this);
}
if (old_image_content) {
old_image_content->RemoveObserver(this);
}
}
if (LayoutImageResource* image_resource = GetLayoutImageResource())
image_resource->ResetAnimation();
}
| 172,792
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_emit_signal2 (MyObject *obj, GError **error)
{
GHashTable *table;
table = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (table, "baz", "cow");
g_hash_table_insert (table, "bar", "foo");
g_signal_emit (obj, signals[SIG2], 0, table);
g_hash_table_destroy (table);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_emit_signal2 (MyObject *obj, GError **error)
| 165,095
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
| 170,979
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Part::slotOpenExtractedEntry(KJob *job)
{
if (!job->error()) {
OpenJob *openJob = qobject_cast<OpenJob*>(job);
Q_ASSERT(openJob);
m_tmpExtractDirList << openJob->tempDir();
const QString fullName = openJob->validatedFilePath();
bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly();
if (!isWritable) {
QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
}
if (isWritable) {
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified);
m_fileWatcher->addPath(fullName);
}
if (qobject_cast<OpenWithJob*>(job)) {
const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)};
KRun::displayOpenWithDialog(urls, widget());
} else {
KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile),
QMimeDatabase().mimeTypeForFile(fullName).name(),
widget());
}
} else if (job->error() != KJob::KilledJobError) {
KMessageBox::error(widget(), job->errorString());
}
setReadyGui();
}
Commit Message:
CWE ID: CWE-78
|
void Part::slotOpenExtractedEntry(KJob *job)
{
if (!job->error()) {
OpenJob *openJob = qobject_cast<OpenJob*>(job);
Q_ASSERT(openJob);
m_tmpExtractDirList << openJob->tempDir();
const QString fullName = openJob->validatedFilePath();
bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly();
if (!isWritable) {
QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
}
if (isWritable) {
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified);
m_fileWatcher->addPath(fullName);
}
if (qobject_cast<OpenWithJob*>(job)) {
const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)};
KRun::displayOpenWithDialog(urls, widget());
} else {
KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile),
QMimeDatabase().mimeTypeForFile(fullName).name(),
widget(), false, false);
}
} else if (job->error() != KJob::KilledJobError) {
KMessageBox::error(widget(), job->errorString());
}
setReadyGui();
}
| 164,992
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool WebContentsImpl::ShowingInterstitialPage() const {
return GetRenderManager()->interstitial_page() != NULL;
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20
|
bool WebContentsImpl::ShowingInterstitialPage() const {
return interstitial_page_ != nullptr;
}
| 172,334
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls -
rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls -
rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
Commit Message: Fixed an integer overflow problem in the JPC codec that later resulted
in the use of uninitialized data.
CWE ID: CWE-190
|
static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
| 168,471
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LauncherView::Init() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
model_->AddObserver(this);
const LauncherItems& items(model_->items());
for (LauncherItems::const_iterator i = items.begin(); i != items.end(); ++i) {
views::View* child = CreateViewForItem(*i);
child->SetPaintToLayer(true);
view_model_->Add(child, static_cast<int>(i - items.begin()));
AddChildView(child);
}
UpdateFirstButtonPadding();
overflow_button_ = new views::ImageButton(this);
overflow_button_->set_accessibility_focusable(true);
overflow_button_->SetImage(
views::CustomButton::BS_NORMAL,
rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW).ToImageSkia());
overflow_button_->SetImage(
views::CustomButton::BS_HOT,
rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_HOT).ToImageSkia());
overflow_button_->SetImage(
views::CustomButton::BS_PUSHED,
rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_PUSHED).ToImageSkia());
overflow_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_AURA_LAUNCHER_OVERFLOW_NAME));
overflow_button_->set_context_menu_controller(this);
ConfigureChildView(overflow_button_);
AddChildView(overflow_button_);
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void LauncherView::Init() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
model_->AddObserver(this);
const LauncherItems& items(model_->items());
for (LauncherItems::const_iterator i = items.begin(); i != items.end(); ++i) {
views::View* child = CreateViewForItem(*i);
child->SetPaintToLayer(true);
view_model_->Add(child, static_cast<int>(i - items.begin()));
AddChildView(child);
}
UpdateFirstButtonPadding();
overflow_button_ = new views::ImageButton(this);
overflow_button_->set_accessibility_focusable(true);
overflow_button_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
overflow_button_->SetImage(
views::CustomButton::BS_NORMAL,
rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW).ToImageSkia());
overflow_button_->SetImage(
views::CustomButton::BS_HOT,
rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_HOT).ToImageSkia());
overflow_button_->SetImage(
views::CustomButton::BS_PUSHED,
rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_PUSHED).ToImageSkia());
overflow_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_AURA_LAUNCHER_OVERFLOW_NAME));
overflow_button_->set_context_menu_controller(this);
ConfigureChildView(overflow_button_);
AddChildView(overflow_button_);
}
| 170,890
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void build_ntlmssp_negotiate_blob(unsigned char *pbuffer,
struct cifs_ses *ses)
{
NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer;
__u32 flags;
memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
sec_blob->MessageType = NtLmNegotiate;
/* BB is NTLMV2 session security format easier to use here? */
flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET |
NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC;
if (ses->server->sign) {
flags |= NTLMSSP_NEGOTIATE_SIGN;
if (!ses->server->session_estab ||
ses->ntlmssp->sesskey_per_smbsess)
flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
}
sec_blob->NegotiateFlags = cpu_to_le32(flags);
sec_blob->WorkstationName.BufferOffset = 0;
sec_blob->WorkstationName.Length = 0;
sec_blob->WorkstationName.MaximumLength = 0;
/* Domain name is sent on the Challenge not Negotiate NTLMSSP request */
sec_blob->DomainName.BufferOffset = 0;
sec_blob->DomainName.Length = 0;
sec_blob->DomainName.MaximumLength = 0;
}
Commit Message: CIFS: Enable encryption during session setup phase
In order to allow encryption on SMB connection we need to exchange
a session key and generate encryption and decryption keys.
Signed-off-by: Pavel Shilovsky <pshilov@microsoft.com>
CWE ID: CWE-476
|
void build_ntlmssp_negotiate_blob(unsigned char *pbuffer,
struct cifs_ses *ses)
{
NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer;
__u32 flags;
memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
sec_blob->MessageType = NtLmNegotiate;
/* BB is NTLMV2 session security format easier to use here? */
flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET |
NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
NTLMSSP_NEGOTIATE_SEAL;
if (ses->server->sign)
flags |= NTLMSSP_NEGOTIATE_SIGN;
if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
sec_blob->NegotiateFlags = cpu_to_le32(flags);
sec_blob->WorkstationName.BufferOffset = 0;
sec_blob->WorkstationName.Length = 0;
sec_blob->WorkstationName.MaximumLength = 0;
/* Domain name is sent on the Challenge not Negotiate NTLMSSP request */
sec_blob->DomainName.BufferOffset = 0;
sec_blob->DomainName.Length = 0;
sec_blob->DomainName.MaximumLength = 0;
}
| 169,360
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: get_cdtext_generic (void *p_user_data)
{
generic_img_private_t *p_env = p_user_data;
uint8_t *p_cdtext_data = NULL;
size_t len;
if (!p_env) return NULL;
if (p_env->b_cdtext_error) return NULL;
if (NULL == p_env->cdtext) {
p_cdtext_data = read_cdtext_generic (p_env);
if (NULL != p_cdtext_data) {
len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2;
p_env->cdtext = cdtext_init();
if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) {
p_env->b_cdtext_error = true;
cdtext_destroy (p_env->cdtext);
free(p_env->cdtext);
p_env->cdtext = NULL;
}
}
free(p_cdtext_data);
}
}
Commit Message:
CWE ID: CWE-415
|
get_cdtext_generic (void *p_user_data)
{
generic_img_private_t *p_env = p_user_data;
uint8_t *p_cdtext_data = NULL;
size_t len;
if (!p_env) return NULL;
if (p_env->b_cdtext_error) return NULL;
if (NULL == p_env->cdtext) {
p_cdtext_data = read_cdtext_generic (p_env);
if (NULL != p_cdtext_data) {
len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2;
p_env->cdtext = cdtext_init();
if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) {
p_env->b_cdtext_error = true;
free(p_env->cdtext);
p_env->cdtext = NULL;
}
}
free(p_cdtext_data);
}
}
| 165,370
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int string_check(char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf failed:\nwe '%s'\nsystem: '%s'\n",
buf, buf2);
return 1;
}
return 0;
}
Commit Message: printf: fix floating point buffer overflow issues
... and add a bunch of floating point printf tests
CWE ID: CWE-119
|
static int string_check(char *buf, const char *buf2)
static int _string_check(int linenumber, char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf line %d failed:\nwe '%s'\nsystem: '%s'\n",
linenumber, buf, buf2);
return 1;
}
return 0;
}
| 169,437
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams(
int version,
size_t start,
size_t end,
const std::string& selection,
const std::string& content,
const std::string& base_page_url,
const std::string& encoding,
int now_on_tap_version)
: version(version),
start(start),
end(end),
selection(selection),
content(content),
base_page_url(base_page_url),
encoding(encoding),
now_on_tap_version(now_on_tap_version) {}
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:
|
TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams(
int version,
size_t start,
size_t end,
const std::string& selection,
const std::string& content,
const std::string& base_page_url,
const std::string& encoding,
int contextual_cards_version)
: version(version),
start(start),
end(end),
selection(selection),
content(content),
base_page_url(base_page_url),
encoding(encoding),
| 171,647
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void set_banner(struct openconnect_info *vpninfo)
{
char *banner, *q;
const char *p;
if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) {
unsetenv("CISCO_BANNER");
return;
}
p = vpninfo->banner;
q = banner;
while (*p) {
if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
isxdigit((int)(unsigned char)p[2])) {
*(q++) = unhex(p + 1);
p += 3;
} else
*(q++) = *(p++);
}
*q = 0;
setenv("CISCO_BANNER", banner, 1);
free(banner);
}
Commit Message:
CWE ID: CWE-119
|
static void set_banner(struct openconnect_info *vpninfo)
{
char *banner, *q;
const char *p;
if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)+1))) {
unsetenv("CISCO_BANNER");
return;
}
p = vpninfo->banner;
q = banner;
while (*p) {
if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
isxdigit((int)(unsigned char)p[2])) {
*(q++) = unhex(p + 1);
p += 3;
} else
*(q++) = *(p++);
}
*q = 0;
setenv("CISCO_BANNER", banner, 1);
free(banner);
}
| 164,960
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BluetoothOptionsHandler::GenerateFakePairing(
const std::string& name,
const std::string& address,
const std::string& icon,
const std::string& pairing) {
DictionaryValue device;
device.SetString("name", name);
device.SetString("address", address);
device.SetString("icon", icon);
device.SetBoolean("paired", false);
device.SetBoolean("connected", false);
DictionaryValue op;
op.SetString("pairing", pairing);
if (pairing.compare("bluetoothEnterPasskey") != 0)
op.SetInteger("passkey", 12345);
if (pairing.compare("bluetoothRemotePasskey") == 0)
op.SetInteger("entered", 2);
web_ui_->CallJavascriptFunction(
"options.SystemOptions.connectBluetoothDevice", device, op);
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void BluetoothOptionsHandler::GenerateFakePairing(
bool connected,
const std::string& pairing) {
DictionaryValue properties;
properties.SetString(bluetooth_device::kNameProperty, name);
properties.SetString(bluetooth_device::kAddressProperty, address);
properties.SetString(bluetooth_device::kIconProperty, icon);
properties.SetBoolean(bluetooth_device::kPairedProperty, paired);
properties.SetBoolean(bluetooth_device::kConnectedProperty, connected);
properties.SetInteger(bluetooth_device::kClassProperty, 0);
chromeos::BluetoothDevice* device =
chromeos::BluetoothDevice::Create(properties);
DeviceFound("FakeAdapter", device);
if (pairing.compare("bluetoothRemotePasskey") == 0) {
DisplayPasskey(device, 12345, 2);
} else if (pairing.compare("bluetoothConfirmPasskey") == 0) {
RequestConfirmation(device, 12345);
} else if (pairing.compare("bluetoothEnterPasskey") == 0) {
RequestPasskey(device);
}
delete device;
}
| 170,970
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int __glXDispSwap_CreateContext(__GLXclientState *cl, GLbyte *pc)
{
xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
__GLX_DECLARE_SWAP_VARIABLES;
__GLX_SWAP_SHORT(&req->length);
__GLX_SWAP_INT(&req->context);
__GLX_SWAP_INT(&req->visual);
return __glXDisp_CreateContext(cl, pc);
}
Commit Message:
CWE ID: CWE-20
|
int __glXDispSwap_CreateContext(__GLXclientState *cl, GLbyte *pc)
{
ClientPtr client = cl->client;
xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
__GLX_DECLARE_SWAP_VARIABLES;
REQUEST_SIZE_MATCH(xGLXCreateContextReq);
__GLX_SWAP_SHORT(&req->length);
__GLX_SWAP_INT(&req->context);
__GLX_SWAP_INT(&req->visual);
return __glXDisp_CreateContext(cl, pc);
}
| 165,269
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: dwarf_elf_object_access_load_section(void* obj_in,
Dwarf_Half section_index,
Dwarf_Small** section_data,
int* error)
{
dwarf_elf_object_access_internals_t*obj =
(dwarf_elf_object_access_internals_t*)obj_in;
if (section_index == 0) {
return DW_DLV_NO_ENTRY;
}
{
Elf_Scn *scn = 0;
Elf_Data *data = 0;
scn = elf_getscn(obj->elf, section_index);
if (scn == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
/* When using libelf as a producer, section data may be stored
in multiple buffers. In libdwarf however, we only use libelf
as a consumer (there is a dwarf producer API, but it doesn't
use libelf). Because of this, this single call to elf_getdata
will retrieve the entire section in a single contiguous
buffer. */
data = elf_getdata(scn, NULL);
if (data == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
*section_data = data->d_buf;
}
return DW_DLV_OK;
}
Commit Message: A DWARF related section marked SHT_NOBITS (elf section type)
is an error in the elf object. Now detected.
dwarf_elf_access.c
CWE ID: CWE-476
|
dwarf_elf_object_access_load_section(void* obj_in,
Dwarf_Half section_index,
Dwarf_Small** section_data,
int* error)
{
dwarf_elf_object_access_internals_t*obj =
(dwarf_elf_object_access_internals_t*)obj_in;
if (section_index == 0) {
return DW_DLV_NO_ENTRY;
}
{
Elf_Scn *scn = 0;
Elf_Data *data = 0;
scn = elf_getscn(obj->elf, section_index);
if (scn == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
/* When using libelf as a producer, section data may be stored
in multiple buffers. In libdwarf however, we only use libelf
as a consumer (there is a dwarf producer API, but it doesn't
use libelf). Because of this, this single call to elf_getdata
will retrieve the entire section in a single contiguous
buffer. */
data = elf_getdata(scn, NULL);
if (data == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
if (!data->d_buf) {
/* If NULL it means 'the section has no data'
according to libelf documentation.
No DWARF-related section should ever have
'no data'. Happens if a section type is
SHT_NOBITS and no section libdwarf
wants to look at should be SHT_NOBITS. */
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
*section_data = data->d_buf;
}
return DW_DLV_OK;
}
| 168,866
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
void *memory;
if (dma_alloc_from_coherent(dev, size, handle, &memory))
return memory;
return __dma_alloc(dev, size, handle, gfp, prot, false,
__builtin_return_address(0));
}
Commit Message: ARM: dma-mapping: don't allow DMA mappings to be marked executable
DMA mapping permissions were being derived from pgprot_kernel directly
without using PAGE_KERNEL. This causes them to be marked with executable
permission, which is not what we want. Fix this.
Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk>
CWE ID: CWE-264
|
void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, PAGE_KERNEL);
void *memory;
if (dma_alloc_from_coherent(dev, size, handle, &memory))
return memory;
return __dma_alloc(dev, size, handle, gfp, prot, false,
__builtin_return_address(0));
}
| 167,578
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
const char* name;
size_t namelen;
if (node->graft_path) {
name = node->graft_path;
namelen = node->graft_pathlen;
} else if (node->actual_name) {
name = node->actual_name;
namelen = node->namelen;
} else {
name = node->name;
namelen = node->namelen;
}
if (bufsize < namelen + 1) {
return -1;
}
ssize_t pathlen = 0;
if (node->parent && node->graft_path == NULL) {
pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 2);
if (pathlen < 0) {
return -1;
}
buf[pathlen++] = '/';
}
memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
return pathlen + namelen;
}
Commit Message: Fix overflow in path building
An incorrect size was causing an unsigned value
to wrap, causing it to write past the end of
the buffer.
Bug: 28085658
Change-Id: Ie9625c729cca024d514ba2880ff97209d435a165
CWE ID: CWE-264
|
static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
const char* name;
size_t namelen;
if (node->graft_path) {
name = node->graft_path;
namelen = node->graft_pathlen;
} else if (node->actual_name) {
name = node->actual_name;
namelen = node->namelen;
} else {
name = node->name;
namelen = node->namelen;
}
if (bufsize < namelen + 1) {
return -1;
}
ssize_t pathlen = 0;
if (node->parent && node->graft_path == NULL) {
pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 1);
if (pathlen < 0) {
return -1;
}
buf[pathlen++] = '/';
}
memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
return pathlen + namelen;
}
| 173,774
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
xml_parser *parser = (xml_parser *)rsrc->ptr;
if (parser->parser) {
XML_ParserFree(parser->parser);
}
if (parser->ltags) {
int inx;
for (inx = 0; ((inx < parser->level) && (inx < XML_MAXLEVEL)); inx++)
efree(parser->ltags[ inx ]);
efree(parser->ltags);
}
if (parser->startElementHandler) {
zval_ptr_dtor(&parser->startElementHandler);
}
if (parser->endElementHandler) {
zval_ptr_dtor(&parser->endElementHandler);
}
if (parser->characterDataHandler) {
zval_ptr_dtor(&parser->characterDataHandler);
}
if (parser->processingInstructionHandler) {
zval_ptr_dtor(&parser->processingInstructionHandler);
}
if (parser->defaultHandler) {
zval_ptr_dtor(&parser->defaultHandler);
}
if (parser->unparsedEntityDeclHandler) {
zval_ptr_dtor(&parser->unparsedEntityDeclHandler);
}
if (parser->notationDeclHandler) {
zval_ptr_dtor(&parser->notationDeclHandler);
}
if (parser->externalEntityRefHandler) {
zval_ptr_dtor(&parser->externalEntityRefHandler);
}
if (parser->unknownEncodingHandler) {
zval_ptr_dtor(&parser->unknownEncodingHandler);
}
if (parser->startNamespaceDeclHandler) {
zval_ptr_dtor(&parser->startNamespaceDeclHandler);
}
if (parser->endNamespaceDeclHandler) {
zval_ptr_dtor(&parser->endNamespaceDeclHandler);
}
if (parser->baseURI) {
efree(parser->baseURI);
}
if (parser->object) {
zval_ptr_dtor(&parser->object);
}
efree(parser);
}
Commit Message:
CWE ID: CWE-119
|
static void xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
xml_parser *parser = (xml_parser *)rsrc->ptr;
if (parser->parser) {
XML_ParserFree(parser->parser);
}
if (parser->ltags) {
int inx;
for (inx = 0; ((inx < parser->level) && (inx < XML_MAXLEVEL)); inx++)
efree(parser->ltags[ inx ]);
efree(parser->ltags);
}
if (parser->startElementHandler) {
zval_ptr_dtor(&parser->startElementHandler);
}
if (parser->endElementHandler) {
zval_ptr_dtor(&parser->endElementHandler);
}
if (parser->characterDataHandler) {
zval_ptr_dtor(&parser->characterDataHandler);
}
if (parser->processingInstructionHandler) {
zval_ptr_dtor(&parser->processingInstructionHandler);
}
if (parser->defaultHandler) {
zval_ptr_dtor(&parser->defaultHandler);
}
if (parser->unparsedEntityDeclHandler) {
zval_ptr_dtor(&parser->unparsedEntityDeclHandler);
}
if (parser->notationDeclHandler) {
zval_ptr_dtor(&parser->notationDeclHandler);
}
if (parser->externalEntityRefHandler) {
zval_ptr_dtor(&parser->externalEntityRefHandler);
}
if (parser->unknownEncodingHandler) {
zval_ptr_dtor(&parser->unknownEncodingHandler);
}
if (parser->startNamespaceDeclHandler) {
zval_ptr_dtor(&parser->startNamespaceDeclHandler);
}
if (parser->endNamespaceDeclHandler) {
zval_ptr_dtor(&parser->endNamespaceDeclHandler);
}
if (parser->baseURI) {
efree(parser->baseURI);
}
if (parser->object) {
zval_ptr_dtor(&parser->object);
}
efree(parser);
}
| 165,047
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void suffix_object( cJSON *prev, cJSON *item )
{
prev->next = item;
item->prev = prev;
}
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 <bmah@es.net>
CWE ID: CWE-119
|
static void suffix_object( cJSON *prev, cJSON *item )
| 167,313
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState)
{
if (options.hasVibrate() && options.silent()) {
exceptionState.throwTypeError("Silent notifications must not specify vibration patterns.");
return WebNotificationData();
}
WebNotificationData webData;
webData.title = title;
webData.direction = toDirectionEnumValue(options.dir());
webData.lang = options.lang();
webData.body = options.body();
webData.tag = options.tag();
KURL iconUrl;
iconUrl = executionContext->completeURL(options.icon());
if (!iconUrl.isValid())
iconUrl = KURL();
}
webData.icon = iconUrl;
webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate());
webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS();
webData.silent = options.silent();
webData.requireInteraction = options.requireInteraction();
if (options.hasData()) {
RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState);
if (exceptionState.hadException())
return WebNotificationData();
Vector<char> serializedData;
serializedScriptValue->toWireBytes(serializedData);
webData.data = serializedData;
}
Vector<WebNotificationAction> actions;
const size_t maxActions = Notification::maxActions();
for (const NotificationAction& action : options.actions()) {
if (actions.size() >= maxActions)
break;
WebNotificationAction webAction;
webAction.action = action.action();
webAction.title = action.title();
actions.append(webAction);
}
webData.actions = actions;
return webData;
}
Commit Message: Notification actions may have an icon url.
This is behind a runtime flag for two reasons:
* The implementation is incomplete.
* We're still evaluating the API design.
Intent to Implement and Ship: Notification Action Icons
https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ
BUG=581336
Review URL: https://codereview.chromium.org/1644573002
Cr-Commit-Position: refs/heads/master@{#374649}
CWE ID:
|
WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState)
{
if (options.hasVibrate() && options.silent()) {
exceptionState.throwTypeError("Silent notifications must not specify vibration patterns.");
return WebNotificationData();
}
WebNotificationData webData;
webData.title = title;
webData.direction = toDirectionEnumValue(options.dir());
webData.lang = options.lang();
webData.body = options.body();
webData.tag = options.tag();
KURL iconUrl;
iconUrl = executionContext->completeURL(options.icon());
if (!iconUrl.isValid())
iconUrl = KURL();
}
webData.icon = iconUrl;
webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate());
webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS();
webData.silent = options.silent();
webData.requireInteraction = options.requireInteraction();
if (options.hasData()) {
RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState);
if (exceptionState.hadException())
return WebNotificationData();
Vector<char> serializedData;
serializedScriptValue->toWireBytes(serializedData);
webData.data = serializedData;
}
Vector<WebNotificationAction> actions;
const size_t maxActions = Notification::maxActions();
for (const NotificationAction& action : options.actions()) {
if (actions.size() >= maxActions)
break;
WebNotificationAction webAction;
webAction.action = action.action();
webAction.title = action.title();
KURL iconUrl;
if (action.hasIcon() && !action.icon().isEmpty()) {
iconUrl = executionContext->completeURL(action.icon());
if (!iconUrl.isValid())
iconUrl = KURL();
}
webAction.icon = iconUrl;
actions.append(webAction);
}
webData.actions = actions;
return webData;
}
| 171,634
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
|
static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,547
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_,
long long size_) {
const long long stop = start_ + size_;
long long pos = start_;
m_track = -1;
m_pos = -1;
m_block = 1; // default
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x77) // CueTrack ID
m_track = UnserializeUInt(pReader, pos, size);
else if (id == 0x71) // CueClusterPos ID
m_pos = UnserializeUInt(pReader, pos, size);
else if (id == 0x1378) // CueBlockNumber
m_block = UnserializeUInt(pReader, pos, size);
pos += size; // consume payload
assert(pos <= stop);
}
assert(m_pos >= 0);
assert(m_track > 0);
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_,
bool CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_,
long long size_) {
const long long stop = start_ + size_;
long long pos = start_;
m_track = -1;
m_pos = -1;
m_block = 1; // default
while (pos < stop) {
long len;
const long long id = ReadID(pReader, pos, len);
if ((id < 0) || ((pos + len) > stop)) {
return false;
}
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
if ((size < 0) || ((pos + len) > stop)) {
return false;
}
pos += len; // consume Size field
if ((pos + size) > stop) {
return false;
}
if (id == 0x77) // CueTrack ID
m_track = UnserializeUInt(pReader, pos, size);
else if (id == 0x71) // CueClusterPos ID
m_pos = UnserializeUInt(pReader, pos, size);
else if (id == 0x1378) // CueBlockNumber
m_block = UnserializeUInt(pReader, pos, size);
pos += size; // consume payload
}
if ((m_pos < 0) || (m_track <= 0)) {
return false;
}
return true;
}
| 173,837
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: jbig2_sd_release(Jbig2Ctx *ctx, Jbig2SymbolDict *dict)
{
int i;
if (dict == NULL)
return;
for (i = 0; i < dict->n_symbols; i++)
if (dict->glyphs[i])
jbig2_image_release(ctx, dict->glyphs[i]);
jbig2_free(ctx->allocator, dict->glyphs);
jbig2_free(ctx->allocator, dict);
}
Commit Message:
CWE ID: CWE-119
|
jbig2_sd_release(Jbig2Ctx *ctx, Jbig2SymbolDict *dict)
{
uint32_t i;
if (dict == NULL)
return;
for (i = 0; i < dict->n_symbols; i++)
if (dict->glyphs[i])
jbig2_image_release(ctx, dict->glyphs[i]);
jbig2_free(ctx->allocator, dict->glyphs);
jbig2_free(ctx->allocator, dict);
}
| 165,503
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: set_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
}
Commit Message: Fix compile warning introduced in commit c6247a9
Commit c6247a9 - "Add command line and configuration option to set umask"
introduced a compile warning, although the code would have worked OK.
Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>
CWE ID: CWE-200
|
set_umask(const char *optarg)
{
long umask_long;
mode_t umask_val;
char *endptr;
umask_long = strtoll(optarg, &endptr, 0);
if (*endptr || umask_long < 0 || umask_long & ~0777L) {
fprintf(stderr, "Invalid --umask option %s", optarg);
return 0;
}
umask_val = umask_long & 0777;
umask(umask_val);
umask_cmdline = true;
return umask_val;
}
| 170,158
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) {
UNUSED(p_org_set);
BTIF_TRACE_DEBUG("entering %s",__FUNCTION__);
for (const list_node_t *node = list_begin(soc_queue);
node != list_end(soc_queue); node = list_next(node)) {
btif_hl_soc_cb_t *p_scb = list_node(node);
if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) {
if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) {
BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ");
btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx,
p_scb->mcl_idx, p_scb->mdl_idx);
assert(p_dcb != NULL);
if (p_dcb->p_tx_pkt) {
BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been"
" sent tx_size=%d", p_dcb->tx_size);
btif_hl_free_buf((void **) &p_dcb->p_tx_pkt);
}
p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu);
if (p_dcb) {
int r = (int)recv(p_scb->socket_id[1], p_dcb->p_tx_pkt,
p_dcb->mtu, MSG_DONTWAIT);
if (r > 0) {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r);
p_dcb->tx_size = r;
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size );
BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size);
} else {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r);
BTA_HlDchClose(p_dcb->mdl_handle);
}
}
}
}
}
if (list_is_empty(soc_queue))
BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty");
BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) {
UNUSED(p_org_set);
BTIF_TRACE_DEBUG("entering %s",__FUNCTION__);
for (const list_node_t *node = list_begin(soc_queue);
node != list_end(soc_queue); node = list_next(node)) {
btif_hl_soc_cb_t *p_scb = list_node(node);
if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) {
if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) {
BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ");
btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx,
p_scb->mcl_idx, p_scb->mdl_idx);
assert(p_dcb != NULL);
if (p_dcb->p_tx_pkt) {
BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been"
" sent tx_size=%d", p_dcb->tx_size);
btif_hl_free_buf((void **) &p_dcb->p_tx_pkt);
}
p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu);
if (p_dcb) {
int r = (int)TEMP_FAILURE_RETRY(recv(p_scb->socket_id[1], p_dcb->p_tx_pkt,
p_dcb->mtu, MSG_DONTWAIT));
if (r > 0) {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r);
p_dcb->tx_size = r;
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size );
BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size);
} else {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r);
BTA_HlDchClose(p_dcb->mdl_handle);
}
}
}
}
}
if (list_is_empty(soc_queue))
BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty");
BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
}
| 173,441
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
{
const uni_to_enc *l = table,
*h = &table[num-1],
*m;
unsigned short code_key;
/* we have no mappings outside the BMP */
if (code_key_a > 0xFFFFU)
return 0;
code_key = (unsigned short) code_key_a;
while (l <= h) {
m = l + (h - l) / 2;
if (code_key < m->un_code_point)
h = m - 1;
else if (code_key > m->un_code_point)
l = m + 1;
else
return m->cs_code;
}
return 0;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
|
static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
{
const uni_to_enc *l = table,
*h = &table[num-1],
*m;
unsigned short code_key;
/* we have no mappings outside the BMP */
if (code_key_a > 0xFFFFU)
return 0;
code_key = (unsigned short) code_key_a;
while (l <= h) {
m = l + (h - l) / 2;
if (code_key < m->un_code_point)
h = m - 1;
else if (code_key > m->un_code_point)
l = m + 1;
else
return m->cs_code;
}
return 0;
}
| 167,180
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void TabStrip::ChangeTabGroup(int model_index,
base::Optional<int> old_group,
base::Optional<int> new_group) {
if (new_group.has_value() && !group_headers_[new_group.value()]) {
const TabGroupData* group_data =
controller_->GetDataForGroup(new_group.value());
auto header = std::make_unique<TabGroupHeader>(group_data->title());
header->set_owned_by_client();
AddChildView(header.get());
group_headers_[new_group.value()] = std::move(header);
}
if (old_group.has_value() &&
controller_->ListTabsInGroup(old_group.value()).size() == 0) {
group_headers_.erase(old_group.value());
}
UpdateIdealBounds();
AnimateToIdealBounds();
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <bsep@chromium.org>
Reviewed-by: Taylor Bergquist <tbergquist@chromium.org>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
|
void TabStrip::ChangeTabGroup(int model_index,
base::Optional<int> old_group,
base::Optional<int> new_group) {
tab_at(model_index)->SetGroup(new_group);
if (new_group.has_value() && !group_headers_[new_group.value()]) {
auto header = std::make_unique<TabGroupHeader>(this, new_group.value());
header->set_owned_by_client();
AddChildView(header.get());
group_headers_[new_group.value()] = std::move(header);
}
if (old_group.has_value() &&
controller_->ListTabsInGroup(old_group.value()).size() == 0) {
group_headers_.erase(old_group.value());
}
UpdateIdealBounds();
AnimateToIdealBounds();
}
| 172,520
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BrowserEventRouter::ExtensionActionExecuted(
Profile* profile,
const ExtensionAction& extension_action,
WebContents* web_contents) {
const char* event_name = NULL;
switch (extension_action.action_type()) {
case Extension::ActionInfo::TYPE_BROWSER:
event_name = "browserAction.onClicked";
break;
case Extension::ActionInfo::TYPE_PAGE:
event_name = "pageAction.onClicked";
break;
case Extension::ActionInfo::TYPE_SCRIPT_BADGE:
event_name = "scriptBadge.onClicked";
break;
case Extension::ActionInfo::TYPE_SYSTEM_INDICATOR:
break;
}
if (event_name) {
scoped_ptr<ListValue> args(new ListValue());
DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue(
web_contents,
ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS);
args->Append(tab_value);
DispatchEventToExtension(profile,
extension_action.extension_id(),
event_name,
args.Pass(),
EventRouter::USER_GESTURE_ENABLED);
}
}
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::ExtensionActionExecuted(
Profile* profile,
const ExtensionAction& extension_action,
WebContents* web_contents) {
const char* event_name = NULL;
switch (extension_action.action_type()) {
case Extension::ActionInfo::TYPE_BROWSER:
event_name = "browserAction.onClicked";
break;
case Extension::ActionInfo::TYPE_PAGE:
event_name = "pageAction.onClicked";
break;
case Extension::ActionInfo::TYPE_SCRIPT_BADGE:
event_name = "scriptBadge.onClicked";
break;
case Extension::ActionInfo::TYPE_SYSTEM_INDICATOR:
break;
}
if (event_name) {
scoped_ptr<ListValue> args(new ListValue());
DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue(
web_contents);
args->Append(tab_value);
DispatchEventToExtension(profile,
extension_action.extension_id(),
event_name,
args.Pass(),
EventRouter::USER_GESTURE_ENABLED);
}
}
| 171,450
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GraphicsContext::clipPath(const Path&, WindRule)
{
notImplemented();
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
void GraphicsContext::clipPath(const Path&, WindRule)
void GraphicsContext::clipPath(const Path& path, WindRule clipRule)
{
if (paintingDisabled())
return;
if (path.isEmpty())
return;
wxGraphicsContext* gc = m_data->context->GetGraphicsContext();
#if __WXMAC__
CGContextRef context = (CGContextRef)gc->GetNativeContext();
CGPathRef nativePath = (CGPathRef)path.platformPath()->GetNativePath();
CGContextBeginPath(context);
CGContextAddPath(context, nativePath);
if (clipRule == RULE_EVENODD)
CGContextEOClip(context);
else
CGContextClip(context);
#elif __WXMSW__
Gdiplus::Graphics* g = (Gdiplus::Graphics*)gc->GetNativeContext();
Gdiplus::GraphicsPath* nativePath = (Gdiplus::GraphicsPath*)path.platformPath()->GetNativePath();
if (clipRule == RULE_EVENODD)
nativePath->SetFillMode(Gdiplus::FillModeAlternate);
else
nativePath->SetFillMode(Gdiplus::FillModeWinding);
g->SetClip(nativePath);
#endif
}
| 170,424
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 i;
WORD32 max_dpb_size;
WORD32 mv_bank_size_allocated;
WORD32 pic_mv_bank_size;
sps_t *ps_sps;
UWORD8 *pu1_buf;
mv_buf_t *ps_mv_buf;
/* Initialize MV Bank buffer manager */
ps_sps = ps_codec->s_parse.ps_sps;
/* Compute the number of MV Bank buffers needed */
max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1];
/* Allocate one extra MV Bank to handle current frame
* In case of asynchronous parsing and processing, number of buffers should increase here
* based on when parsing and processing threads are synchronized
*/
max_dpb_size++;
pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base;
ps_mv_buf = (mv_buf_t *)pu1_buf;
pu1_buf += max_dpb_size * sizeof(mv_buf_t);
ps_codec->ps_mv_buf = ps_mv_buf;
mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t);
/* Compute MV bank size per picture */
pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples));
for(i = 0; i < max_dpb_size; i++)
{
WORD32 buf_ret;
WORD32 num_pu;
WORD32 num_ctb;
WORD32 pic_size;
pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples);
num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE);
num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE);
mv_bank_size_allocated -= pic_mv_bank_size;
if(mv_bank_size_allocated < 0)
{
ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK;
return IHEVCD_INSUFFICIENT_MEM_MVBANK;
}
ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf;
pu1_buf += (num_ctb + 1) * sizeof(WORD32);
ps_mv_buf->pu1_pic_pu_map = pu1_buf;
pu1_buf += num_pu;
ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf;
pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16));
ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf;
pu1_buf += num_pu * sizeof(pu_t);
buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i);
if(0 != buf_ret)
{
ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR;
return IHEVCD_BUF_MGR_ERROR;
}
ps_mv_buf++;
}
return ret;
}
Commit Message: Check only allocated mv bufs for releasing from reference
When checking mv bufs for releasing from reference, unallocated
mv bufs were also checked. This issue was fixed by restricting
the loop count to allocated number of mv bufs.
Bug: 34896906
Bug: 34819017
Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb
(cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2)
CWE ID:
|
IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 i;
WORD32 max_dpb_size;
WORD32 mv_bank_size_allocated;
WORD32 pic_mv_bank_size;
sps_t *ps_sps;
UWORD8 *pu1_buf;
mv_buf_t *ps_mv_buf;
/* Initialize MV Bank buffer manager */
ps_sps = ps_codec->s_parse.ps_sps;
/* Compute the number of MV Bank buffers needed */
max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1];
/* Allocate one extra MV Bank to handle current frame
* In case of asynchronous parsing and processing, number of buffers should increase here
* based on when parsing and processing threads are synchronized
*/
max_dpb_size++;
ps_codec->i4_max_dpb_size = max_dpb_size;
pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base;
ps_mv_buf = (mv_buf_t *)pu1_buf;
pu1_buf += max_dpb_size * sizeof(mv_buf_t);
ps_codec->ps_mv_buf = ps_mv_buf;
mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t);
/* Compute MV bank size per picture */
pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples));
for(i = 0; i < max_dpb_size; i++)
{
WORD32 buf_ret;
WORD32 num_pu;
WORD32 num_ctb;
WORD32 pic_size;
pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) *
ALIGN64(ps_sps->i2_pic_height_in_luma_samples);
num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE);
num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE);
mv_bank_size_allocated -= pic_mv_bank_size;
if(mv_bank_size_allocated < 0)
{
ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK;
return IHEVCD_INSUFFICIENT_MEM_MVBANK;
}
ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf;
pu1_buf += (num_ctb + 1) * sizeof(WORD32);
ps_mv_buf->pu1_pic_pu_map = pu1_buf;
pu1_buf += num_pu;
ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf;
pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16));
ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf;
pu1_buf += num_pu * sizeof(pu_t);
buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i);
if(0 != buf_ret)
{
ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR;
return IHEVCD_BUF_MGR_ERROR;
}
ps_mv_buf++;
}
return ret;
}
| 173,999
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TabContentsTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
old_browser_client_(NULL) {
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
TabContentsTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
old_client_(NULL),
old_browser_client_(NULL) {
}
| 171,015
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool AXNodeObject::isChecked() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLInputElement(*node))
return toHTMLInputElement(*node).shouldAppearChecked();
switch (ariaRoleAttribute()) {
case CheckBoxRole:
case MenuItemCheckBoxRole:
case MenuItemRadioRole:
case RadioButtonRole:
case SwitchRole:
if (equalIgnoringCase(
getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked),
"true"))
return true;
return false;
default:
break;
}
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXNodeObject::isChecked() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLInputElement(*node))
return toHTMLInputElement(*node).shouldAppearChecked();
switch (ariaRoleAttribute()) {
case CheckBoxRole:
case MenuItemCheckBoxRole:
case MenuItemRadioRole:
case RadioButtonRole:
case SwitchRole:
if (equalIgnoringASCIICase(
getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked),
"true"))
return true;
return false;
default:
break;
}
return false;
}
| 171,914
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const Cluster* BlockEntry::GetCluster() const
{
return m_pCluster;
}
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
|
const Cluster* BlockEntry::GetCluster() const
| 174,291
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const CuePoint* Cues::GetFirst() const
{
if (m_cue_points == NULL)
return NULL;
if (m_count == 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
#endif
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[0];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
return pCP;
}
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
|
const CuePoint* Cues::GetFirst() const
if (m_count == 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
#endif
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[0];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
return pCP;
}
| 174,321
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[512], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
}
Commit Message: Fixed possible foveon buffer overrun (Secunia SA750000)
CWE ID: CWE-119
|
void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[1024], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
}
| 168,313
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt & 0xFF;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
Commit Message: vhost/scsi: potential memory corruption
This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt"
to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16.
I looked at the context and it turns out that in
vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into
the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so
anything higher than 255 then it is invalid. I have made that the limit
now.
In vhost_scsi_send_evt() we mask away values higher than 255, but now
that the limit has changed, we don't need the mask.
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Nicholas Bellinger <nab@linux-iscsi.org>
CWE ID: CWE-119
|
vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
| 166,616
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
paused_(false) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
}
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
|
ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
paused_(false) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
if (speech_synthesizer_) {
ULONGLONG event_mask =
SPFEI(SPEI_START_INPUT_STREAM) |
SPFEI(SPEI_TTS_BOOKMARK) |
SPFEI(SPEI_WORD_BOUNDARY) |
SPFEI(SPEI_SENTENCE_BOUNDARY) |
SPFEI(SPEI_END_INPUT_STREAM);
speech_synthesizer_->SetInterest(event_mask, event_mask);
speech_synthesizer_->SetNotifyCallbackFunction(
ExtensionTtsPlatformImplWin::SpeechEventCallback, 0, 0);
}
}
| 170,401
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PromoResourceService::PostNotification(int64 delay_ms) {
if (web_resource_update_scheduled_)
return;
if (delay_ms > 0) {
web_resource_update_scheduled_ = true;
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PromoResourceService::PromoResourceStateChange,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(delay_ms));
} else if (delay_ms == 0) {
PromoResourceStateChange();
}
}
Commit Message: Refresh promo notifications as they're fetched
The "guard" existed for notification scheduling was preventing
"turn-off a promo" and "update a promo" scenarios.
Yet I do not believe it was adding any actual safety: if things
on a server backend go wrong, the clients will be affected one
way or the other, and it is better to have an option to shut
the malformed promo down "as quickly as possible" (~in 12-24 hours).
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10696204
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void PromoResourceService::PostNotification(int64 delay_ms) {
// Note that this could cause re-issuing a notification every time
// we receive an update from a server if something goes wrong.
// Given that this couldn't happen more frequently than every
// kCacheUpdateDelay milliseconds, we should be fine.
if (delay_ms > 0) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PromoResourceService::PromoResourceStateChange,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(delay_ms));
} else if (delay_ms == 0) {
PromoResourceStateChange();
}
}
| 170,781
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(get_html_translation_table)
{
long all = HTML_SPECIALCHARS,
flags = ENT_COMPAT;
int doctype;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
char *charset_hint = NULL;
int charset_hint_len;
enum entity_charset charset;
/* in this function we have to jump through some loops because we're
* getting the translated table from data structures that are optimized for
* random access, not traversal */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls",
&all, &flags, &charset_hint, &charset_hint_len) == FAILURE) {
return;
}
charset = determine_charset(charset_hint TSRMLS_CC);
doctype = flags & ENT_HTML_DOC_TYPE_MASK;
LIMIT_ALL(all, doctype, charset);
array_init(return_value);
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */
const entity_stage1_row *ms_table = entity_table.ms_table;
if (CHARSET_UNICODE_COMPAT(charset)) {
unsigned i, j, k,
max_i, max_j, max_k;
/* no mapping to unicode required */
if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */
max_i = 1; max_j = 4; max_k = 64;
} else {
max_i = 0x1E; max_j = 64; max_k = 64;
}
for (i = 0; i < max_i; i++) {
if (ms_table[i] == empty_stage2_table)
continue;
for (j = 0; j < max_j; j++) {
if (ms_table[i][j] == empty_stage3_table)
continue;
for (k = 0; k < max_k; k++) {
const entity_stage3_row *r = &ms_table[i][j][k];
unsigned code;
if (r->data.ent.entity == NULL)
continue;
code = ENT_CODE_POINT_FROM_STAGES(i, j, k);
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
write_s3row_data(r, code, charset, return_value);
}
}
}
} else {
/* we have to iterate through the set of code points for this
* encoding and map them to unicode code points */
unsigned i;
for (i = 0; i <= 0xFF; i++) {
const entity_stage3_row *r;
unsigned uni_cp;
/* can be done before mapping, they're invariant */
if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
map_to_unicode(i, to_uni_table, &uni_cp);
r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)];
if (r->data.ent.entity == NULL)
continue;
write_s3row_data(r, i, charset, return_value);
}
}
} else {
/* we could use sizeof(stage3_table_be_apos_00000) as well */
unsigned j,
numelems = sizeof(stage3_table_be_noapos_00000) /
sizeof(*stage3_table_be_noapos_00000);
for (j = 0; j < numelems; j++) {
const entity_stage3_row *r = &entity_table.table[j];
if (r->data.ent.entity == NULL)
continue;
if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
/* charset is indifferent, used cs_8859_1 for efficiency */
write_s3row_data(r, j, cs_8859_1, return_value);
}
}
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
|
PHP_FUNCTION(get_html_translation_table)
{
long all = HTML_SPECIALCHARS,
flags = ENT_COMPAT;
int doctype;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
char *charset_hint = NULL;
int charset_hint_len;
enum entity_charset charset;
/* in this function we have to jump through some loops because we're
* getting the translated table from data structures that are optimized for
* random access, not traversal */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls",
&all, &flags, &charset_hint, &charset_hint_len) == FAILURE) {
return;
}
charset = determine_charset(charset_hint TSRMLS_CC);
doctype = flags & ENT_HTML_DOC_TYPE_MASK;
LIMIT_ALL(all, doctype, charset);
array_init(return_value);
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */
const entity_stage1_row *ms_table = entity_table.ms_table;
if (CHARSET_UNICODE_COMPAT(charset)) {
unsigned i, j, k,
max_i, max_j, max_k;
/* no mapping to unicode required */
if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */
max_i = 1; max_j = 4; max_k = 64;
} else {
max_i = 0x1E; max_j = 64; max_k = 64;
}
for (i = 0; i < max_i; i++) {
if (ms_table[i] == empty_stage2_table)
continue;
for (j = 0; j < max_j; j++) {
if (ms_table[i][j] == empty_stage3_table)
continue;
for (k = 0; k < max_k; k++) {
const entity_stage3_row *r = &ms_table[i][j][k];
unsigned code;
if (r->data.ent.entity == NULL)
continue;
code = ENT_CODE_POINT_FROM_STAGES(i, j, k);
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
write_s3row_data(r, code, charset, return_value);
}
}
}
} else {
/* we have to iterate through the set of code points for this
* encoding and map them to unicode code points */
unsigned i;
for (i = 0; i <= 0xFF; i++) {
const entity_stage3_row *r;
unsigned uni_cp;
/* can be done before mapping, they're invariant */
if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
map_to_unicode(i, to_uni_table, &uni_cp);
r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)];
if (r->data.ent.entity == NULL)
continue;
write_s3row_data(r, i, charset, return_value);
}
}
} else {
/* we could use sizeof(stage3_table_be_apos_00000) as well */
unsigned j,
numelems = sizeof(stage3_table_be_noapos_00000) /
sizeof(*stage3_table_be_noapos_00000);
for (j = 0; j < numelems; j++) {
const entity_stage3_row *r = &entity_table.table[j];
if (r->data.ent.entity == NULL)
continue;
if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
/* charset is indifferent, used cs_8859_1 for efficiency */
write_s3row_data(r, j, cs_8859_1, return_value);
}
}
}
| 167,168
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: std::string* GetTestingDMToken() {
static std::string dm_token;
return &dm_token;
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org>
Reviewed-by: Tien Mai <tienmai@chromium.org>
Reviewed-by: Daniel Rubery <drubery@chromium.org>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20
|
std::string* GetTestingDMToken() {
const char** GetTestingDMTokenStorage() {
static const char* dm_token = "";
return &dm_token;
}
| 172,354
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Cues::Init() const {
if (m_cue_points)
return;
assert(m_count == 0);
assert(m_preload_count == 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop) {
const long long idpos = pos;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x3B) // CuePoint ID
PreloadCuePoint(cue_points_size, idpos);
pos += size; // consume payload
assert(pos <= stop);
}
}
Commit Message: 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 Cues::Init() const {
bool Cues::Init() const {
if (m_cue_points)
return true;
if (m_count != 0 || m_preload_count != 0)
return false;
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop) {
const long long idpos = pos;
long len;
const long long id = ReadID(pReader, pos, len);
if (id < 0 || (pos + len) > stop) {
return false;
}
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
if (size < 0 || (pos + len > stop)) {
return false;
}
pos += len; // consume Size field
if (pos + size > stop) {
return false;
}
if (id == 0x3B) { // CuePoint ID
if (!PreloadCuePoint(cue_points_size, idpos))
return false;
}
pos += size; // skip payload
}
return true;
}
| 173,827
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->MaxLen < 1)
fields->MaxLen = fields->Len;
Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125
|
void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->MaxLen < 1)
fields->MaxLen = fields->Len;
Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
}
| 169,279
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct desc_struct *get_desc(unsigned short sel)
{
struct desc_ptr gdt_desc = {0, 0};
unsigned long desc_base;
#ifdef CONFIG_MODIFY_LDT_SYSCALL
if ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) {
struct desc_struct *desc = NULL;
struct ldt_struct *ldt;
/* Bits [15:3] contain the index of the desired entry. */
sel >>= 3;
mutex_lock(¤t->active_mm->context.lock);
ldt = current->active_mm->context.ldt;
if (ldt && sel < ldt->nr_entries)
desc = &ldt->entries[sel];
mutex_unlock(¤t->active_mm->context.lock);
return desc;
}
#endif
native_store_gdt(&gdt_desc);
/*
* Segment descriptors have a size of 8 bytes. Thus, the index is
* multiplied by 8 to obtain the memory offset of the desired descriptor
* from the base of the GDT. As bits [15:3] of the segment selector
* contain the index, it can be regarded as multiplied by 8 already.
* All that remains is to clear bits [2:0].
*/
desc_base = sel & ~(SEGMENT_RPL_MASK | SEGMENT_TI_MASK);
if (desc_base > gdt_desc.size)
return NULL;
return (struct desc_struct *)(gdt_desc.address + desc_base);
}
Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry
get_desc() computes a pointer into the LDT while holding a lock that
protects the LDT from being freed, but then drops the lock and returns the
(now potentially dangling) pointer to its caller.
Fix it by giving the caller a copy of the LDT entry instead.
Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor")
Cc: stable@vger.kernel.org
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-362
|
static struct desc_struct *get_desc(unsigned short sel)
static bool get_desc(struct desc_struct *out, unsigned short sel)
{
struct desc_ptr gdt_desc = {0, 0};
unsigned long desc_base;
#ifdef CONFIG_MODIFY_LDT_SYSCALL
if ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) {
bool success = false;
struct ldt_struct *ldt;
/* Bits [15:3] contain the index of the desired entry. */
sel >>= 3;
mutex_lock(¤t->active_mm->context.lock);
ldt = current->active_mm->context.ldt;
if (ldt && sel < ldt->nr_entries) {
*out = ldt->entries[sel];
success = true;
}
mutex_unlock(¤t->active_mm->context.lock);
return success;
}
#endif
native_store_gdt(&gdt_desc);
/*
* Segment descriptors have a size of 8 bytes. Thus, the index is
* multiplied by 8 to obtain the memory offset of the desired descriptor
* from the base of the GDT. As bits [15:3] of the segment selector
* contain the index, it can be regarded as multiplied by 8 already.
* All that remains is to clear bits [2:0].
*/
desc_base = sel & ~(SEGMENT_RPL_MASK | SEGMENT_TI_MASK);
if (desc_base > gdt_desc.size)
return false;
*out = *(struct desc_struct *)(gdt_desc.address + desc_base);
return true;
}
| 169,607
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: P2PQuicTransportImpl::P2PQuicTransportImpl(
P2PQuicTransportConfig p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
quic::QuicClock* clock)
: quic::QuicSession(connection.get(),
nullptr /* visitor */,
quic_config,
quic::CurrentSupportedVersions()),
helper_(std::move(helper)),
connection_(std::move(connection)),
perspective_(p2p_transport_config.is_server
? quic::Perspective::IS_SERVER
: quic::Perspective::IS_CLIENT),
packet_transport_(p2p_transport_config.packet_transport),
delegate_(p2p_transport_config.delegate),
clock_(clock) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
DCHECK(clock_);
DCHECK(packet_transport_);
DCHECK_GT(p2p_transport_config.certificates.size(), 0u);
if (p2p_transport_config.can_respond_to_crypto_handshake) {
InitializeCryptoStream();
}
certificate_ = p2p_transport_config.certificates[0];
packet_transport_->SetReceiveDelegate(this);
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <shampson@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
|
P2PQuicTransportImpl::P2PQuicTransportImpl(
P2PQuicTransportConfig p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
quic::QuicClock* clock)
: quic::QuicSession(connection.get(),
nullptr /* visitor */,
quic_config,
quic::CurrentSupportedVersions()),
helper_(std::move(helper)),
connection_(std::move(connection)),
perspective_(p2p_transport_config.is_server
? quic::Perspective::IS_SERVER
: quic::Perspective::IS_CLIENT),
packet_transport_(p2p_transport_config.packet_transport),
delegate_(p2p_transport_config.delegate),
clock_(clock),
stream_write_buffer_size_(p2p_transport_config.stream_write_buffer_size) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
DCHECK(clock_);
DCHECK(packet_transport_);
DCHECK_GT(stream_write_buffer_size_, 0u);
DCHECK_GT(p2p_transport_config.certificates.size(), 0u);
if (p2p_transport_config.can_respond_to_crypto_handshake) {
InitializeCryptoStream();
}
certificate_ = p2p_transport_config.certificates[0];
packet_transport_->SetReceiveDelegate(this);
}
| 172,266
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void setup_test_dir(char *tmp_dir, const char *files, ...) {
va_list ap;
assert_se(mkdtemp(tmp_dir) != NULL);
va_start(ap, files);
while (files != NULL) {
_cleanup_free_ char *path = strappend(tmp_dir, files);
assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0) == 0);
files = va_arg(ap, const char *);
}
va_end(ap);
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264
|
static void setup_test_dir(char *tmp_dir, const char *files, ...) {
va_list ap;
assert_se(mkdtemp(tmp_dir) != NULL);
va_start(ap, files);
while (files != NULL) {
_cleanup_free_ char *path = strappend(tmp_dir, files);
assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID) == 0);
files = va_arg(ap, const char *);
}
va_end(ap);
}
| 170,108
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int virtio_net_load(QEMUFile *f, void *opaque, int version_id)
{
VirtIONet *n = opaque;
VirtIODevice *vdev = VIRTIO_DEVICE(n);
int ret, i, link_down;
if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION)
return -EINVAL;
ret = virtio_load(vdev, f);
if (ret) {
return ret;
}
qemu_get_buffer(f, n->mac, ETH_ALEN);
n->vqs[0].tx_waiting = qemu_get_be32(f);
virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f));
if (version_id >= 3)
n->status = qemu_get_be16(f);
if (version_id >= 4) {
if (version_id < 8) {
n->promisc = qemu_get_be32(f);
n->allmulti = qemu_get_be32(f);
} else {
n->promisc = qemu_get_byte(f);
n->allmulti = qemu_get_byte(f);
}
}
if (version_id >= 5) {
n->mac_table.in_use = qemu_get_be32(f);
/* MAC_TABLE_ENTRIES may be different from the saved image */
if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) {
qemu_get_buffer(f, n->mac_table.macs,
n->mac_table.in_use * ETH_ALEN);
} else if (n->mac_table.in_use) {
uint8_t *buf = g_malloc0(n->mac_table.in_use);
qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN);
g_free(buf);
n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1;
n->mac_table.in_use = 0;
}
}
if (version_id >= 6)
qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3);
if (version_id >= 7) {
if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) {
error_report("virtio-net: saved image requires vnet_hdr=on");
return -1;
}
}
if (version_id >= 9) {
n->mac_table.multi_overflow = qemu_get_byte(f);
n->mac_table.uni_overflow = qemu_get_byte(f);
}
if (version_id >= 10) {
n->alluni = qemu_get_byte(f);
n->nomulti = qemu_get_byte(f);
n->nouni = qemu_get_byte(f);
n->nobcast = qemu_get_byte(f);
}
if (version_id >= 11) {
if (qemu_get_byte(f) && !peer_has_ufo(n)) {
error_report("virtio-net: saved image requires TUN_F_UFO support");
return -1;
}
}
if (n->max_queues > 1) {
if (n->max_queues != qemu_get_be16(f)) {
error_report("virtio-net: different max_queues ");
return -1;
}
n->curr_queues = qemu_get_be16(f);
for (i = 1; i < n->curr_queues; i++) {
n->vqs[i].tx_waiting = qemu_get_be32(f);
}
n->curr_guest_offloads = virtio_net_supported_guest_offloads(n);
}
if (peer_has_vnet_hdr(n)) {
virtio_net_apply_guest_offloads(n);
}
virtio_net_set_queues(n);
/* Find the first multicast entry in the saved MAC filter */
for (i = 0; i < n->mac_table.in_use; i++) {
if (n->mac_table.macs[i * ETH_ALEN] & 1) {
break;
}
}
n->mac_table.first_multi = i;
/* nc.link_down can't be migrated, so infer link_down according
* to link status bit in n->status */
link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0;
for (i = 0; i < n->max_queues; i++) {
qemu_get_subqueue(n->nic, i)->link_down = link_down;
}
return 0;
}
Commit Message:
CWE ID: CWE-119
|
static int virtio_net_load(QEMUFile *f, void *opaque, int version_id)
{
VirtIONet *n = opaque;
VirtIODevice *vdev = VIRTIO_DEVICE(n);
int ret, i, link_down;
if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION)
return -EINVAL;
ret = virtio_load(vdev, f);
if (ret) {
return ret;
}
qemu_get_buffer(f, n->mac, ETH_ALEN);
n->vqs[0].tx_waiting = qemu_get_be32(f);
virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f));
if (version_id >= 3)
n->status = qemu_get_be16(f);
if (version_id >= 4) {
if (version_id < 8) {
n->promisc = qemu_get_be32(f);
n->allmulti = qemu_get_be32(f);
} else {
n->promisc = qemu_get_byte(f);
n->allmulti = qemu_get_byte(f);
}
}
if (version_id >= 5) {
n->mac_table.in_use = qemu_get_be32(f);
/* MAC_TABLE_ENTRIES may be different from the saved image */
if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) {
qemu_get_buffer(f, n->mac_table.macs,
n->mac_table.in_use * ETH_ALEN);
} else if (n->mac_table.in_use) {
uint8_t *buf = g_malloc0(n->mac_table.in_use);
qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN);
g_free(buf);
n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1;
n->mac_table.in_use = 0;
}
}
if (version_id >= 6)
qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3);
if (version_id >= 7) {
if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) {
error_report("virtio-net: saved image requires vnet_hdr=on");
return -1;
}
}
if (version_id >= 9) {
n->mac_table.multi_overflow = qemu_get_byte(f);
n->mac_table.uni_overflow = qemu_get_byte(f);
}
if (version_id >= 10) {
n->alluni = qemu_get_byte(f);
n->nomulti = qemu_get_byte(f);
n->nouni = qemu_get_byte(f);
n->nobcast = qemu_get_byte(f);
}
if (version_id >= 11) {
if (qemu_get_byte(f) && !peer_has_ufo(n)) {
error_report("virtio-net: saved image requires TUN_F_UFO support");
return -1;
}
}
if (n->max_queues > 1) {
if (n->max_queues != qemu_get_be16(f)) {
error_report("virtio-net: different max_queues ");
return -1;
}
n->curr_queues = qemu_get_be16(f);
if (n->curr_queues > n->max_queues) {
error_report("virtio-net: curr_queues %x > max_queues %x",
n->curr_queues, n->max_queues);
return -1;
}
for (i = 1; i < n->curr_queues; i++) {
n->vqs[i].tx_waiting = qemu_get_be32(f);
}
n->curr_guest_offloads = virtio_net_supported_guest_offloads(n);
}
if (peer_has_vnet_hdr(n)) {
virtio_net_apply_guest_offloads(n);
}
virtio_net_set_queues(n);
/* Find the first multicast entry in the saved MAC filter */
for (i = 0; i < n->mac_table.in_use; i++) {
if (n->mac_table.macs[i * ETH_ALEN] & 1) {
break;
}
}
n->mac_table.first_multi = i;
/* nc.link_down can't be migrated, so infer link_down according
* to link status bit in n->status */
link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0;
for (i = 0; i < n->max_queues; i++) {
qemu_get_subqueue(n->nic, i)->link_down = link_down;
}
return 0;
}
| 165,362
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BlobURLRegistry::unregisterURL(const KURL& url)
{
ThreadableBlobRegistry::unregisterBlobURL(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:
|
void BlobURLRegistry::unregisterURL(const KURL& url)
{
BlobRegistry::unregisterBlobURL(url);
}
| 170,678
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static Image *ReadHALDImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
size_t
cube_size,
level;
ssize_t
y;
/*
Create HALD color lookup table image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
level=0;
if (*image_info->filename != '\0')
level=StringToUnsignedLong(image_info->filename);
if (level < 2)
level=8;
status=MagickTrue;
cube_size=level*level;
image->columns=(size_t) (level*cube_size);
image->rows=(size_t) (level*cube_size);
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) level)
{
ssize_t
blue,
green,
red;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=QueueAuthenticPixels(image,0,y,image->columns,(size_t) level,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
blue=y/(ssize_t) level;
for (green=0; green < (ssize_t) cube_size; green++)
{
for (red=0; red < (ssize_t) cube_size; red++)
{
SetPixelRed(q,ClampToQuantum((MagickRealType)
(QuantumRange*red/(cube_size-1.0))));
SetPixelGreen(q,ClampToQuantum((MagickRealType)
(QuantumRange*green/(cube_size-1.0))));
SetPixelBlue(q,ClampToQuantum((MagickRealType)
(QuantumRange*blue/(cube_size-1.0))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
|
static Image *ReadHALDImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
size_t
cube_size,
level;
ssize_t
y;
/*
Create HALD color lookup table image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
level=0;
if (*image_info->filename != '\0')
level=StringToUnsignedLong(image_info->filename);
if (level < 2)
level=8;
status=MagickTrue;
cube_size=level*level;
image->columns=(size_t) (level*cube_size);
image->rows=(size_t) (level*cube_size);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) level)
{
ssize_t
blue,
green,
red;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=QueueAuthenticPixels(image,0,y,image->columns,(size_t) level,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
blue=y/(ssize_t) level;
for (green=0; green < (ssize_t) cube_size; green++)
{
for (red=0; red < (ssize_t) cube_size; red++)
{
SetPixelRed(q,ClampToQuantum((MagickRealType)
(QuantumRange*red/(cube_size-1.0))));
SetPixelGreen(q,ClampToQuantum((MagickRealType)
(QuantumRange*green/(cube_size-1.0))));
SetPixelBlue(q,ClampToQuantum((MagickRealType)
(QuantumRange*blue/(cube_size-1.0))));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(GetFirstImageInList(image));
}
| 168,569
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
if (WARN_ON(ret < match32->match_size))
return -EINVAL;
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
WARN_ON(type == EBT_COMPAT_TARGET && size_left);
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets
We need to make sure the offsets are not out of range of the
total size.
Also check that they are in ascending order.
The WARN_ON triggered by syzkaller (it sets panic_on_warn) is
changed to also bail out, no point in continuing parsing.
Briefly tested with simple ruleset of
-A INPUT --limit 1/s' --log
plus jump to custom chains using 32bit ebtables binary.
Reported-by: <syzbot+845a53d13171abf8bf29@syzkaller.appspotmail.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
CWE ID: CWE-787
|
static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
if (WARN_ON(ret < match32->match_size))
return -EINVAL;
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
if (WARN_ON(type == EBT_COMPAT_TARGET && size_left))
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
| 169,357
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int main(int argc, char *argv[])
{
char buff[1024];
int fd, nr, nw;
if (argc < 2) {
fprintf(stderr,
"usage: %s output-filename\n"
" %s |output-command\n"
" %s :host:port\n", argv[0], argv[0], argv[0]);
return 1;
}
fd = open_gen_fd(argv[1]);
if (fd < 0) {
perror("open_gen_fd");
exit(EXIT_FAILURE);
}
while ((nr = read(0, buff, sizeof (buff))) != 0) {
if (nr < 0) {
if (errno == EINTR)
continue;
perror("read");
exit(EXIT_FAILURE);
}
nw = write(fd, buff, nr);
if (nw < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
return 0;
}
Commit Message: misc oom and possible memory leak fix
CWE ID:
|
int main(int argc, char *argv[])
{
char buff[1024];
int fd, nr, nw;
if (argc < 2) {
fprintf(stderr,
"usage: %s output-filename\n"
" %s |output-command\n"
" %s :host:port\n", argv[0], argv[0], argv[0]);
return 1;
}
fd = open_gen_fd(argv[1]);
if (fd < 0) {
perror("open_gen_fd");
exit(EXIT_FAILURE);
}
while ((nr = read(0, buff, sizeof (buff))) != 0) {
if (nr < 0) {
if (errno == EINTR)
continue;
perror("read");
exit(EXIT_FAILURE);
}
nw = write(fd, buff, nr);
if (nw < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
close(fd);
return 0;
}
| 169,758
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ProfileSyncService::RegisterNewDataType(syncable::ModelType data_type) {
if (data_type_controllers_.count(data_type) > 0)
return;
switch (data_type) {
case syncable::SESSIONS:
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableSyncTabs)) {
return;
}
RegisterDataTypeController(
new browser_sync::SessionDataTypeController(factory_.get(),
profile_,
this));
return;
default:
break;
}
NOTREACHED();
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
void ProfileSyncService::RegisterNewDataType(syncable::ModelType data_type) {
if (data_type_controllers_.count(data_type) > 0)
return;
NOTREACHED();
}
| 170,788
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static char *create_output_name(unsigned char *fname, unsigned char *dir,
int lower, int isunix, int utf8)
{
unsigned char *p, *name, c, *fe, sep, slash;
unsigned int x;
sep = (isunix) ? '/' : '\\'; /* the path-seperator */
slash = (isunix) ? '\\' : '/'; /* the other slash */
/* length of filename */
x = strlen((char *) fname);
/* UTF8 worst case scenario: tolower() expands all chars from 1 to 3 bytes */
if (utf8) x *= 3;
/* length of output directory */
if (dir) x += strlen((char *) dir);
if (!(name = (unsigned char *) malloc(x + 2))) {
fprintf(stderr, "out of memory!\n");
return NULL;
}
/* start with blank name */
*name = '\0';
/* add output directory if needed */
if (dir) {
strcpy((char *) name, (char *) dir);
strcat((char *) name, "/");
}
/* remove leading slashes */
while (*fname == sep) fname++;
/* copy from fi->filename to new name, converting MS-DOS slashes to UNIX
* slashes as we go. Also lowercases characters if needed.
*/
p = &name[strlen((char *)name)];
fe = &fname[strlen((char *)fname)];
if (utf8) {
/* UTF8 translates two-byte unicode characters into 1, 2 or 3 bytes.
* %000000000xxxxxxx -> %0xxxxxxx
* %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy
* %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz
*
* Therefore, the inverse is as follows:
* First char:
* 0x00 - 0x7F = one byte char
* 0x80 - 0xBF = invalid
* 0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid)
* 0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid)
* 0xF0 - 0xFF = invalid
*/
do {
if (fname >= fe) {
free(name);
return NULL;
}
/* get next UTF8 char */
if ((c = *fname++) < 0x80) x = c;
else {
if ((c >= 0xC0) && (c < 0xE0)) {
x = (c & 0x1F) << 6;
x |= *fname++ & 0x3F;
}
else if ((c >= 0xE0) && (c < 0xF0)) {
x = (c & 0xF) << 12;
x |= (*fname++ & 0x3F) << 6;
x |= *fname++ & 0x3F;
}
else x = '?';
}
/* whatever is the path seperator -> '/'
* whatever is the other slash -> '\\'
* otherwise, if lower is set, the lowercase version */
if (x == sep) x = '/';
else if (x == slash) x = '\\';
else if (lower) x = (unsigned int) tolower((int) x);
/* integer back to UTF8 */
if (x < 0x80) {
*p++ = (unsigned char) x;
}
else if (x < 0x800) {
*p++ = 0xC0 | (x >> 6);
*p++ = 0x80 | (x & 0x3F);
}
else {
*p++ = 0xE0 | (x >> 12);
*p++ = 0x80 | ((x >> 6) & 0x3F);
*p++ = 0x80 | (x & 0x3F);
}
} while (x);
}
else {
/* regular non-utf8 version */
do {
c = *fname++;
if (c == sep) c = '/';
else if (c == slash) c = '\\';
else if (lower) c = (unsigned char) tolower((int) c);
} while ((*p++ = c));
}
return (char *) name;
}
Commit Message: add anti "../" and leading slash protection to chmextract
CWE ID: CWE-22
|
static char *create_output_name(unsigned char *fname, unsigned char *dir,
char *create_output_name(char *fname) {
char *out, *p;
if ((out = malloc(strlen(fname) + 1))) {
/* remove leading slashes */
while (*fname == '/' || *fname == '\\') fname++;
/* if that removes all characters, just call it "x" */
strcpy(out, (*fname) ? fname : "x");
/* change "../" to "xx/" */
for (p = out; *p; p++) {
if (p[0] == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\\')) {
p[0] = p[1] = 'x';
}
}
}
return out;
}
| 169,001
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
Commit Message: CVE-2017-13026/IS-IS: Clean up processing of subTLVs.
Add bounds checks, do a common check to make sure we captured the entire
subTLV, add checks to make sure the subTLV fits within the TLV.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add tests using the capture files supplied by the reporter(s), modified
so the capture files won't be rejected as an invalid capture.
Update existing tests for changes to IS-IS dissector.
CWE ID: CWE-125
|
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
if (stlv_len < 8)
goto trunc;
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
| 167,864
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result==1) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
Commit Message: fix bug #64660 - yyparse can return 2, not only 1
CWE ID: CWE-20
|
ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval=NULL;
int compiler_result;
zend_bool compilation_successful=0;
znode retval_znode;
zend_bool original_in_compilation = CG(in_compilation);
retval_znode.op_type = IS_CONST;
retval_znode.u.constant.type = IS_LONG;
retval_znode.u.constant.value.lval = 1;
Z_UNSET_ISREF(retval_znode.u.constant);
Z_SET_REFCOUNT(retval_znode.u.constant, 1);
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
retval = op_array; /* success oriented */
if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) {
if (type==ZEND_REQUIRE) {
zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC);
zend_bailout();
} else {
zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC);
}
compilation_successful=0;
} else {
init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(in_compilation) = 1;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
compiler_result = zendparse(TSRMLS_C);
zend_do_return(&retval_znode, 0 TSRMLS_CC);
CG(in_compilation) = original_in_compilation;
if (compiler_result != 0) { /* parser error */
zend_bailout();
}
compilation_successful=1;
}
if (retval) {
CG(active_op_array) = original_active_op_array;
if (compilation_successful) {
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
} else {
efree(op_array);
retval = NULL;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
return retval;
}
| 166,023
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ChromotingInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
CHECK(!initialized_);
initialized_ = true;
VLOG(1) << "Started ChromotingInstance::Init";
if (!media::IsMediaLibraryInitialized()) {
LOG(ERROR) << "Media library not initialized.";
return false;
}
net::EnableSSLServerSockets();
context_.Start();
scoped_refptr<FrameConsumerProxy> consumer_proxy =
new FrameConsumerProxy(plugin_task_runner_);
rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(),
context_.decode_task_runner(),
consumer_proxy);
view_.reset(new PepperView(this, &context_, rectangle_decoder_.get()));
consumer_proxy->Attach(view_->AsWeakPtr());
return true;
}
Commit Message: Restrict the Chromoting client plugin to use by extensions & apps.
BUG=160456
Review URL: https://chromiumcodereview.appspot.com/11365276
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
bool ChromotingInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
CHECK(!initialized_);
initialized_ = true;
VLOG(1) << "Started ChromotingInstance::Init";
if (!media::IsMediaLibraryInitialized()) {
LOG(ERROR) << "Media library not initialized.";
return false;
}
// Check that the calling content is part of an app or extension.
if (!IsCallerAppOrExtension()) {
LOG(ERROR) << "Not an app or extension";
return false;
}
net::EnableSSLServerSockets();
context_.Start();
scoped_refptr<FrameConsumerProxy> consumer_proxy =
new FrameConsumerProxy(plugin_task_runner_);
rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(),
context_.decode_task_runner(),
consumer_proxy);
view_.reset(new PepperView(this, &context_, rectangle_decoder_.get()));
consumer_proxy->Attach(view_->AsWeakPtr());
return true;
}
| 170,671
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CoordinatorImpl::UnregisterClientProcess(
mojom::ClientProcess* client_process) {
QueuedRequest* request = GetCurrentRequest();
if (request != nullptr) {
auto it = request->pending_responses.begin();
while (it != request->pending_responses.end()) {
std::set<QueuedRequest::PendingResponse>::iterator current = it++;
if (current->client != client_process)
continue;
RemovePendingResponse(client_process, current->type);
request->failed_memory_dump_count++;
}
FinalizeGlobalMemoryDumpIfAllManagersReplied();
}
for (auto& pair : in_progress_vm_region_requests_) {
QueuedVmRegionRequest* request = pair.second.get();
auto it = request->pending_responses.begin();
while (it != request->pending_responses.end()) {
auto current = it++;
if (*current == client_process) {
request->pending_responses.erase(current);
}
}
}
for (auto& pair : in_progress_vm_region_requests_) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&CoordinatorImpl::FinalizeVmRegionDumpIfAllManagersReplied,
base::Unretained(this), pair.second->dump_guid));
}
size_t num_deleted = clients_.erase(client_process);
DCHECK(num_deleted == 1);
}
Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained
Bug: 856578
Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9
Reviewed-on: https://chromium-review.googlesource.com/1114617
Reviewed-by: Hector Dearman <hjd@chromium.org>
Commit-Queue: Hector Dearman <hjd@chromium.org>
Cr-Commit-Position: refs/heads/master@{#571528}
CWE ID: CWE-416
|
void CoordinatorImpl::UnregisterClientProcess(
mojom::ClientProcess* client_process) {
QueuedRequest* request = GetCurrentRequest();
if (request != nullptr) {
auto it = request->pending_responses.begin();
while (it != request->pending_responses.end()) {
std::set<QueuedRequest::PendingResponse>::iterator current = it++;
if (current->client != client_process)
continue;
RemovePendingResponse(client_process, current->type);
request->failed_memory_dump_count++;
}
FinalizeGlobalMemoryDumpIfAllManagersReplied();
}
for (auto& pair : in_progress_vm_region_requests_) {
QueuedVmRegionRequest* request = pair.second.get();
auto it = request->pending_responses.begin();
while (it != request->pending_responses.end()) {
auto current = it++;
if (*current == client_process) {
request->pending_responses.erase(current);
}
}
}
for (auto& pair : in_progress_vm_region_requests_) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&CoordinatorImpl::FinalizeVmRegionDumpIfAllManagersReplied,
weak_ptr_factory_.GetWeakPtr(), pair.second->dump_guid));
}
size_t num_deleted = clients_.erase(client_process);
DCHECK(num_deleted == 1);
}
| 173,216
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::AuthorizeService(
const dbus::ObjectPath& device_path,
const std::string& uuid,
const ConfirmationCallback& callback) {
callback.Run(CANCELLED);
}
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::AuthorizeService(
| 171,216
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Chapters::~Chapters()
{
while (m_editions_count > 0)
{
Edition& e = m_editions[--m_editions_count];
e.Clear();
}
}
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
|
Chapters::~Chapters()
| 174,457
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PrintPreviewMessageHandler::OnMetafileReadyForPrinting(
const PrintHostMsg_DidPreviewDocument_Params& params) {
StopWorker(params.document_cookie);
if (params.expected_pages_count <= 0) {
NOTREACHED();
return;
}
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI();
if (!print_preview_ui)
return;
scoped_refptr<base::RefCountedBytes> data_bytes =
GetDataFromHandle(params.metafile_data_handle, params.data_size);
if (!data_bytes || !data_bytes->size())
return;
print_preview_ui->SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX,
std::move(data_bytes));
print_preview_ui->OnPreviewDataIsAvailable(
params.expected_pages_count, params.preview_request_id);
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
TBR=jzfeng@chromium.org
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <weili@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254
|
void PrintPreviewMessageHandler::OnMetafileReadyForPrinting(
const PrintHostMsg_DidPreviewDocument_Params& params) {
StopWorker(params.document_cookie);
if (params.expected_pages_count <= 0) {
NOTREACHED();
return;
}
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI();
if (!print_preview_ui)
return;
if (IsOopifEnabled() && print_preview_ui->source_is_modifiable()) {
auto* client = PrintCompositeClient::FromWebContents(web_contents());
DCHECK(client);
client->DoComposite(
params.metafile_data_handle, params.data_size,
base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfDocumentDone,
weak_ptr_factory_.GetWeakPtr(),
params.expected_pages_count, params.preview_request_id));
} else {
NotifyUIPreviewDocumentReady(
params.expected_pages_count, params.preview_request_id,
GetDataFromHandle(params.metafile_data_handle, params.data_size));
}
}
| 171,890
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GLOzone* X11SurfaceFactory::GetGLOzone(gl::GLImplementation implementation) {
switch (implementation) {
case gl::kGLImplementationDesktopGL:
return glx_implementation_.get();
case gl::kGLImplementationEGLGLES2:
return egl_implementation_.get();
default:
return nullptr;
}
}
Commit Message: Add ThreadChecker for Ozone X11 GPU.
Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM.
BUG=none
Review-Url: https://codereview.chromium.org/2366643002
Cr-Commit-Position: refs/heads/master@{#421817}
CWE ID: CWE-284
|
GLOzone* X11SurfaceFactory::GetGLOzone(gl::GLImplementation implementation) {
DCHECK(thread_checker_.CalledOnValidThread());
switch (implementation) {
case gl::kGLImplementationDesktopGL:
return glx_implementation_.get();
case gl::kGLImplementationEGLGLES2:
return egl_implementation_.get();
default:
return nullptr;
}
}
| 171,603
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
if (interstitial_page_)
return interstitial_page_->GetView();
if (render_frame_host_)
return render_frame_host_->GetView();
return nullptr;
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20
|
RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const {
if (delegate_->GetInterstitialForRenderManager())
return delegate_->GetInterstitialForRenderManager()->GetView();
if (render_frame_host_)
return render_frame_host_->GetView();
return nullptr;
}
| 172,322
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: archive_read_format_cpio_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct cpio *cpio;
const void *h;
struct archive_string_conv *sconv;
size_t namelength;
size_t name_pad;
int r;
cpio = (struct cpio *)(a->format->data);
sconv = cpio->opt_sconv;
if (sconv == NULL) {
if (!cpio->init_default_conversion) {
cpio->sconv_default =
archive_string_default_conversion_for_read(
&(a->archive));
cpio->init_default_conversion = 1;
}
sconv = cpio->sconv_default;
}
r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad));
if (r < ARCHIVE_WARN)
return (r);
/* Read name from buffer. */
h = __archive_read_ahead(a, namelength + name_pad, NULL);
if (h == NULL)
return (ARCHIVE_FATAL);
if (archive_entry_copy_pathname_l(entry,
(const char *)h, namelength, sconv) != 0) {
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Pathname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Pathname can't be converted from %s to current locale.",
archive_string_conversion_charset_name(sconv));
r = ARCHIVE_WARN;
}
cpio->entry_offset = 0;
__archive_read_consume(a, namelength + name_pad);
/* If this is a symlink, read the link contents. */
if (archive_entry_filetype(entry) == AE_IFLNK) {
h = __archive_read_ahead(a,
(size_t)cpio->entry_bytes_remaining, NULL);
if (h == NULL)
return (ARCHIVE_FATAL);
if (archive_entry_copy_symlink_l(entry, (const char *)h,
(size_t)cpio->entry_bytes_remaining, sconv) != 0) {
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Linkname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Linkname can't be converted from %s to "
"current locale.",
archive_string_conversion_charset_name(sconv));
r = ARCHIVE_WARN;
}
__archive_read_consume(a, cpio->entry_bytes_remaining);
cpio->entry_bytes_remaining = 0;
}
/* XXX TODO: If the full mode is 0160200, then this is a Solaris
* ACL description for the following entry. Read this body
* and parse it as a Solaris-style ACL, then read the next
* header. XXX */
/* Compare name to "TRAILER!!!" to test for end-of-archive. */
if (namelength == 11 && strcmp((const char *)h, "TRAILER!!!") == 0) {
/* TODO: Store file location of start of block. */
archive_clear_error(&a->archive);
return (ARCHIVE_EOF);
}
/* Detect and record hardlinks to previously-extracted entries. */
if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) {
return (ARCHIVE_FATAL);
}
return (r);
}
Commit Message: Reject cpio symlinks that exceed 1MB
CWE ID: CWE-20
|
archive_read_format_cpio_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct cpio *cpio;
const void *h;
struct archive_string_conv *sconv;
size_t namelength;
size_t name_pad;
int r;
cpio = (struct cpio *)(a->format->data);
sconv = cpio->opt_sconv;
if (sconv == NULL) {
if (!cpio->init_default_conversion) {
cpio->sconv_default =
archive_string_default_conversion_for_read(
&(a->archive));
cpio->init_default_conversion = 1;
}
sconv = cpio->sconv_default;
}
r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad));
if (r < ARCHIVE_WARN)
return (r);
/* Read name from buffer. */
h = __archive_read_ahead(a, namelength + name_pad, NULL);
if (h == NULL)
return (ARCHIVE_FATAL);
if (archive_entry_copy_pathname_l(entry,
(const char *)h, namelength, sconv) != 0) {
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Pathname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Pathname can't be converted from %s to current locale.",
archive_string_conversion_charset_name(sconv));
r = ARCHIVE_WARN;
}
cpio->entry_offset = 0;
__archive_read_consume(a, namelength + name_pad);
/* If this is a symlink, read the link contents. */
if (archive_entry_filetype(entry) == AE_IFLNK) {
if (cpio->entry_bytes_remaining > 1024 * 1024) {
archive_set_error(&a->archive, ENOMEM,
"Rejecting malformed cpio archive: symlink contents exceed 1 megabyte");
return (ARCHIVE_FATAL);
}
h = __archive_read_ahead(a,
(size_t)cpio->entry_bytes_remaining, NULL);
if (h == NULL)
return (ARCHIVE_FATAL);
if (archive_entry_copy_symlink_l(entry, (const char *)h,
(size_t)cpio->entry_bytes_remaining, sconv) != 0) {
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Linkname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Linkname can't be converted from %s to "
"current locale.",
archive_string_conversion_charset_name(sconv));
r = ARCHIVE_WARN;
}
__archive_read_consume(a, cpio->entry_bytes_remaining);
cpio->entry_bytes_remaining = 0;
}
/* XXX TODO: If the full mode is 0160200, then this is a Solaris
* ACL description for the following entry. Read this body
* and parse it as a Solaris-style ACL, then read the next
* header. XXX */
/* Compare name to "TRAILER!!!" to test for end-of-archive. */
if (namelength == 11 && strcmp((const char *)h, "TRAILER!!!") == 0) {
/* TODO: Store file location of start of block. */
archive_clear_error(&a->archive);
return (ARCHIVE_EOF);
}
/* Detect and record hardlinks to previously-extracted entries. */
if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) {
return (ARCHIVE_FATAL);
}
return (r);
}
| 167,228
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void *sock_poll_thread(void *arg)
{
struct pollfd pfds[MAX_POLL];
memset(pfds, 0, sizeof(pfds));
int h = (intptr_t)arg;
for(;;)
{
prepare_poll_fds(h, pfds);
int ret = poll(pfds, ts[h].poll_count, -1);
if(ret == -1)
{
APPL_TRACE_ERROR("poll ret -1, exit the thread, errno:%d, err:%s", errno, strerror(errno));
break;
}
if(ret != 0)
{
int need_process_data_fd = TRUE;
if(pfds[0].revents) //cmd fd always is the first one
{
asrt(pfds[0].fd == ts[h].cmd_fdr);
if(!process_cmd_sock(h))
{
APPL_TRACE_DEBUG("h:%d, process_cmd_sock return false, exit...", h);
break;
}
if(ret == 1)
need_process_data_fd = FALSE;
else ret--; //exclude the cmd fd
}
if(need_process_data_fd)
process_data_sock(h, pfds, ret);
}
else {APPL_TRACE_DEBUG("no data, select ret: %d", ret)};
}
ts[h].thread_id = -1;
APPL_TRACE_DEBUG("socket poll thread exiting, h:%d", h);
return 0;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static void *sock_poll_thread(void *arg)
{
struct pollfd pfds[MAX_POLL];
memset(pfds, 0, sizeof(pfds));
int h = (intptr_t)arg;
for(;;)
{
prepare_poll_fds(h, pfds);
int ret = TEMP_FAILURE_RETRY(poll(pfds, ts[h].poll_count, -1));
if(ret == -1)
{
APPL_TRACE_ERROR("poll ret -1, exit the thread, errno:%d, err:%s", errno, strerror(errno));
break;
}
if(ret != 0)
{
int need_process_data_fd = TRUE;
if(pfds[0].revents) //cmd fd always is the first one
{
asrt(pfds[0].fd == ts[h].cmd_fdr);
if(!process_cmd_sock(h))
{
APPL_TRACE_DEBUG("h:%d, process_cmd_sock return false, exit...", h);
break;
}
if(ret == 1)
need_process_data_fd = FALSE;
else ret--; //exclude the cmd fd
}
if(need_process_data_fd)
process_data_sock(h, pfds, ret);
}
else {APPL_TRACE_DEBUG("no data, select ret: %d", ret)};
}
ts[h].thread_id = -1;
APPL_TRACE_DEBUG("socket poll thread exiting, h:%d", h);
return 0;
}
| 173,467
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
scale_factor(1.0f),
rasterize_pdf(false),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_id(-1),
preview_request_id(0),
is_first_request(false),
print_scaling_option(blink::kWebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
title(),
url(),
should_print_backgrounds(false),
printed_doc_type(printing::SkiaDocumentType::PDF) {}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Jianzhou Feng <jzfeng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20
|
PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
scale_factor(1.0f),
rasterize_pdf(false),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_id(-1),
preview_request_id(0),
is_first_request(false),
print_scaling_option(blink::kWebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
title(),
url(),
header_template(),
footer_template(),
should_print_backgrounds(false),
printed_doc_type(printing::SkiaDocumentType::PDF) {}
| 172,897
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
VpxVideoReader *reader = NULL;
const VpxInterface *decoder = NULL;
const VpxVideoInfo *info = NULL;
exec_name = argv[0];
if (argc != 3)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing.", argv[2]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->interface()));
if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0))
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0))
die_codec(&codec, "Failed to decode frame.");
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) {
vpx_img_write(img, outfile);
++frame_cnt;
}
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
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
|
int main(int argc, char **argv) {
int frame_cnt = 0;
FILE *outfile = NULL;
vpx_codec_ctx_t codec;
VpxVideoReader *reader = NULL;
const VpxInterface *decoder = NULL;
const VpxVideoInfo *info = NULL;
exec_name = argv[0];
if (argc != 3)
die("Invalid number of arguments.");
reader = vpx_video_reader_open(argv[1]);
if (!reader)
die("Failed to open %s for reading.", argv[1]);
if (!(outfile = fopen(argv[2], "wb")))
die("Failed to open %s for writing.", argv[2]);
info = vpx_video_reader_get_info(reader);
decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
if (!decoder)
die("Unknown input codec.");
printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface()));
if (vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, 0))
die_codec(&codec, "Failed to initialize decoder.");
while (vpx_video_reader_read_frame(reader)) {
vpx_codec_iter_t iter = NULL;
vpx_image_t *img = NULL;
size_t frame_size = 0;
const unsigned char *frame = vpx_video_reader_get_frame(reader,
&frame_size);
if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0))
die_codec(&codec, "Failed to decode frame.");
while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) {
vpx_img_write(img, outfile);
++frame_cnt;
}
}
printf("Processed %d frames.\n", frame_cnt);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec");
printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
info->frame_width, info->frame_height, argv[2]);
vpx_video_reader_close(reader);
fclose(outfile);
return EXIT_SUCCESS;
}
| 174,487
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Tracks::Parse() {
assert(m_trackEntries == NULL);
assert(m_trackEntriesEnd == NULL);
const long long stop = m_start + m_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
int count = 0;
long long pos = m_start;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x2E) // TrackEntry ID
++count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
if (count <= 0)
return 0; // success
m_trackEntries = new (std::nothrow) Track* [count];
if (m_trackEntries == NULL)
return -1;
m_trackEntriesEnd = m_trackEntries;
pos = m_start;
while (pos < stop) {
const long long element_start = pos;
long long id, payload_size;
const long status =
ParseElementHeader(pReader, pos, stop, id, payload_size);
if (status < 0) // error
return status;
if (payload_size == 0) // weird
continue;
const long long payload_stop = pos + payload_size;
assert(payload_stop <= stop); // checked in ParseElement
const long long element_size = payload_stop - element_start;
if (id == 0x2E) { // TrackEntry ID
Track*& pTrack = *m_trackEntriesEnd;
pTrack = NULL;
const long status = ParseTrackEntry(pos, payload_size, element_start,
element_size, pTrack);
if (status)
return status;
if (pTrack)
++m_trackEntriesEnd;
}
pos = payload_stop;
assert(pos <= stop);
}
assert(pos == stop);
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long Tracks::Parse() {
assert(m_trackEntries == NULL);
assert(m_trackEntriesEnd == NULL);
const long long stop = m_start + m_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
int count = 0;
long long pos = m_start;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x2E) // TrackEntry ID
++count;
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
if (count <= 0)
return 0; // success
m_trackEntries = new (std::nothrow) Track*[count];
if (m_trackEntries == NULL)
return -1;
m_trackEntriesEnd = m_trackEntries;
pos = m_start;
while (pos < stop) {
const long long element_start = pos;
long long id, payload_size;
const long status =
ParseElementHeader(pReader, pos, stop, id, payload_size);
if (status < 0) // error
return status;
if (payload_size == 0) // weird
continue;
const long long payload_stop = pos + payload_size;
assert(payload_stop <= stop); // checked in ParseElement
const long long element_size = payload_stop - element_start;
if (id == 0x2E) { // TrackEntry ID
Track*& pTrack = *m_trackEntriesEnd;
pTrack = NULL;
const long status = ParseTrackEntry(pos, payload_size, element_start,
element_size, pTrack);
if (status)
return status;
if (pTrack)
++m_trackEntriesEnd;
}
pos = payload_stop;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 173,845
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: mcs_parse_domain_params(STREAM s)
{
int length;
ber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);
in_uint8s(s, length);
return s_check(s);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
|
mcs_parse_domain_params(STREAM s)
{
uint32 length;
struct stream packet = *s;
ber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);
if (!s_check_rem(s, length))
{
rdp_protocol_error("mcs_parse_domain_params(), consume domain params from stream would overrun", &packet);
}
in_uint8s(s, length);
return s_check(s);
}
| 169,799
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: MediaStreamManagerTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
audio_manager_ = std::make_unique<MockAudioManager>();
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>();
video_capture_provider_ = video_capture_provider.get();
media_stream_manager_ = std::make_unique<MediaStreamManager>(
audio_system_.get(), audio_manager_->GetTaskRunner(),
std::move(video_capture_provider));
base::RunLoop().RunUntilIdle();
ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_))
.WillByDefault(Invoke(
[](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) {
std::vector<media::VideoCaptureDeviceInfo> stub_results;
base::ResetAndReturn(&result_callback).Run(stub_results);
}));
}
Commit Message: Fix MediaObserver notifications in MediaStreamManager.
This CL fixes the stream type used to notify MediaObserver about
cancelled MediaStream requests.
Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate
that all stream types should be cancelled.
However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this
way and the request to update the UI is ignored.
This CL sends a separate notification for each stream type so that the
UI actually gets updated for all stream types in use.
Bug: 816033
Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405
Reviewed-on: https://chromium-review.googlesource.com/939630
Commit-Queue: Guido Urdaneta <guidou@chromium.org>
Reviewed-by: Raymes Khoury <raymes@chromium.org>
Cr-Commit-Position: refs/heads/master@{#540122}
CWE ID: CWE-20
|
MediaStreamManagerTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
audio_manager_ = std::make_unique<MockAudioManager>();
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>();
video_capture_provider_ = video_capture_provider.get();
media_stream_manager_ = std::make_unique<MediaStreamManager>(
audio_system_.get(), audio_manager_->GetTaskRunner(),
std::move(video_capture_provider));
media_observer_ = std::make_unique<MockMediaObserver>();
browser_content_client_ =
std::make_unique<TestBrowserClient>(media_observer_.get());
SetBrowserClientForTesting(browser_content_client_.get());
base::RunLoop().RunUntilIdle();
ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_))
.WillByDefault(Invoke(
[](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) {
std::vector<media::VideoCaptureDeviceInfo> stub_results;
base::ResetAndReturn(&result_callback).Run(stub_results);
}));
}
| 172,735
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200
|
int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (venc_handle->is_secure_session()) {
DEBUG_PRINT_ERROR("logging secure output buffers is not allowed!");
return -1;
}
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
| 173,507
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PPB_URLLoader_Impl::FinishLoading(int32_t done_status) {
done_status_ = done_status;
if (TrackedCallback::IsPending(pending_callback_))
RunCallback(done_status_);
}
Commit Message: Remove possibility of stale user_buffer_ member in PPB_URLLoader_Impl when FinishedLoading() is called.
BUG=137778
Review URL: https://chromiumcodereview.appspot.com/10797037
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@147914 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void PPB_URLLoader_Impl::FinishLoading(int32_t done_status) {
done_status_ = done_status;
user_buffer_ = NULL;
user_buffer_size_ = 0;
if (TrackedCallback::IsPending(pending_callback_))
RunCallback(done_status_);
}
| 170,900
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PromoResourceService::ScheduleNotification(double promo_start,
double promo_end) {
if (promo_start > 0 && promo_end > 0) {
const int64 ms_until_start =
static_cast<int64>((base::Time::FromDoubleT(
promo_start) - base::Time::Now()).InMilliseconds());
const int64 ms_until_end =
static_cast<int64>((base::Time::FromDoubleT(
promo_end) - base::Time::Now()).InMilliseconds());
if (ms_until_start > 0) {
PostNotification(ms_until_start);
} else if (ms_until_end > 0) {
if (ms_until_start <= 0) {
PostNotification(0);
}
PostNotification(ms_until_end);
}
}
}
Commit Message: Refresh promo notifications as they're fetched
The "guard" existed for notification scheduling was preventing
"turn-off a promo" and "update a promo" scenarios.
Yet I do not believe it was adding any actual safety: if things
on a server backend go wrong, the clients will be affected one
way or the other, and it is better to have an option to shut
the malformed promo down "as quickly as possible" (~in 12-24 hours).
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10696204
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void PromoResourceService::ScheduleNotification(double promo_start,
double promo_end) {
if (promo_start > 0 && promo_end > 0) {
const int64 ms_until_start =
static_cast<int64>((base::Time::FromDoubleT(
promo_start) - base::Time::Now()).InMilliseconds());
const int64 ms_until_end =
static_cast<int64>((base::Time::FromDoubleT(
promo_end) - base::Time::Now()).InMilliseconds());
if (ms_until_start > 0) {
PostNotification(ms_until_start);
} else if (ms_until_end > 0) {
if (ms_until_start <= 0) {
// The promo is active. Notify immediately.
PostNotification(0);
}
PostNotification(ms_until_end);
} else {
// The promo (if any) has finished. Notify immediately.
PostNotification(0);
}
} else {
// The promo (if any) was apparently cancelled. Notify immediately.
PostNotification(0);
}
}
| 170,784
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
phaseFrac = (EAS_I32)pWTVoice->phaseFrac;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
|
void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
phaseFrac = (EAS_I32)pWTVoice->phaseFrac;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
| 173,919
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8)
{
const unsigned char *p, *pm;
int pklen, pmlen;
int ptype;
void *pval;
ASN1_STRING *pstr;
X509_ALGOR *palg;
ASN1_INTEGER *privkey = NULL;
BN_CTX *ctx = NULL;
STACK_OF(ASN1_TYPE) *ndsa = NULL;
DSA *dsa = NULL;
if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
return 0;
X509_ALGOR_get0(NULL, &ptype, &pval, palg);
if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
ASN1_TYPE *t1, *t2;
if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen)))
goto decerr;
if (sk_ASN1_TYPE_num(ndsa) != 2)
goto decerr;
/*-
* Handle Two broken types:
* SEQUENCE {parameters, priv_key}
* SEQUENCE {pub_key, priv_key}
*/
t1 = sk_ASN1_TYPE_value(ndsa, 0);
t2 = sk_ASN1_TYPE_value(ndsa, 1);
if (t1->type == V_ASN1_SEQUENCE) {
p8->broken = PKCS8_EMBEDDED_PARAM;
pval = t1->value.ptr;
} else if (ptype == V_ASN1_SEQUENCE)
p8->broken = PKCS8_NS_DB;
else
goto decerr;
if (t2->type != V_ASN1_INTEGER)
goto decerr;
privkey = t2->value.integer;
} else {
const unsigned char *q = p;
if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)))
goto decerr;
if (privkey->type == V_ASN1_NEG_INTEGER) {
p8->broken = PKCS8_NEG_PRIVKEY;
ASN1_STRING_clear_free(privkey);
if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen)))
goto decerr;
}
if (ptype != V_ASN1_SEQUENCE)
goto decerr;
}
pstr = pval;
pm = pstr->data;
pmlen = pstr->length;
if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen)))
goto decerr;
/* We have parameters now set private key */
if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) {
DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR);
goto dsaerr;
}
/* Calculate public key */
if (!(dsa->pub_key = BN_new())) {
DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE);
goto dsaerr;
}
if (!(ctx = BN_CTX_new())) {
DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE);
goto dsaerr;
}
if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) {
DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR);
goto dsaerr;
}
}
Commit Message:
CWE ID:
|
static int dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8)
{
const unsigned char *p, *pm;
int pklen, pmlen;
int ptype;
void *pval;
ASN1_STRING *pstr;
X509_ALGOR *palg;
ASN1_INTEGER *privkey = NULL;
BN_CTX *ctx = NULL;
STACK_OF(ASN1_TYPE) *ndsa = NULL;
DSA *dsa = NULL;
int ret = 0;
if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
return 0;
X509_ALGOR_get0(NULL, &ptype, &pval, palg);
if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
ASN1_TYPE *t1, *t2;
if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen)))
goto decerr;
if (sk_ASN1_TYPE_num(ndsa) != 2)
goto decerr;
/*-
* Handle Two broken types:
* SEQUENCE {parameters, priv_key}
* SEQUENCE {pub_key, priv_key}
*/
t1 = sk_ASN1_TYPE_value(ndsa, 0);
t2 = sk_ASN1_TYPE_value(ndsa, 1);
if (t1->type == V_ASN1_SEQUENCE) {
p8->broken = PKCS8_EMBEDDED_PARAM;
pval = t1->value.ptr;
} else if (ptype == V_ASN1_SEQUENCE)
p8->broken = PKCS8_NS_DB;
else
goto decerr;
if (t2->type != V_ASN1_INTEGER)
goto decerr;
privkey = t2->value.integer;
} else {
const unsigned char *q = p;
if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)))
goto decerr;
if (privkey->type == V_ASN1_NEG_INTEGER) {
p8->broken = PKCS8_NEG_PRIVKEY;
ASN1_STRING_clear_free(privkey);
if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen)))
goto decerr;
}
if (ptype != V_ASN1_SEQUENCE)
goto decerr;
}
pstr = pval;
pm = pstr->data;
pmlen = pstr->length;
if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen)))
goto decerr;
/* We have parameters now set private key */
if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) {
DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR);
goto dsaerr;
}
/* Calculate public key */
if (!(dsa->pub_key = BN_new())) {
DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE);
goto dsaerr;
}
if (!(ctx = BN_CTX_new())) {
DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE);
goto dsaerr;
}
if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) {
DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR);
goto dsaerr;
}
}
| 165,253
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ExtensionTtsSpeakFunction::RunImpl() {
std::string text;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &text));
DictionaryValue* options = NULL;
if (args_->GetSize() >= 2)
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &options));
Task* completion_task = NewRunnableMethod(
this, &ExtensionTtsSpeakFunction::SpeechFinished);
utterance_ = new Utterance(profile(), text, options, completion_task);
AddRef(); // Balanced in SpeechFinished().
ExtensionTtsController::GetInstance()->SpeakOrEnqueue(utterance_);
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 ExtensionTtsSpeakFunction::RunImpl() {
int src_id = -1;
EXTENSION_FUNCTION_VALIDATE(
options->GetInteger(constants::kSrcIdKey, &src_id));
// If we got this far, the arguments were all in the valid format, so
// send the success response to the callback now - this ensures that
// the callback response always arrives before events, which makes
// the behavior more predictable and easier to write unit tests for too.
SendResponse(true);
UtteranceContinuousParameters continuous_params;
continuous_params.rate = rate;
continuous_params.pitch = pitch;
continuous_params.volume = volume;
Utterance* utterance = new Utterance(profile());
utterance->set_text(text);
utterance->set_voice_name(voice_name);
utterance->set_src_extension_id(extension_id());
utterance->set_src_id(src_id);
utterance->set_src_url(source_url());
utterance->set_lang(lang);
utterance->set_gender(gender);
utterance->set_continuous_parameters(continuous_params);
utterance->set_can_enqueue(can_enqueue);
utterance->set_required_event_types(required_event_types);
utterance->set_desired_event_types(desired_event_types);
utterance->set_extension_id(voice_extension_id);
utterance->set_options(options.get());
ExtensionTtsController* controller = ExtensionTtsController::GetInstance();
controller->SpeakOrEnqueue(utterance);
return true;
}
| 170,384
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value)
{
char *dst;
if (!value.length)
return NULL;
/* allocate destination string, it will be at most 3 times the source */
dst = talloc_array(mem_ctx, char, value.length * 3 + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
ldb_dn_escape_internal(dst, (const char *)value.data, value.length);
dst = talloc_realloc(mem_ctx, dst, char, strlen(dst) + 1);
return dst;
}
Commit Message:
CWE ID: CWE-200
|
char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value)
{
char *dst;
size_t len;
if (!value.length)
return NULL;
/* allocate destination string, it will be at most 3 times the source */
dst = talloc_array(mem_ctx, char, value.length * 3 + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
len = ldb_dn_escape_internal(dst, (const char *)value.data, value.length);
dst = talloc_realloc(mem_ctx, dst, char, len + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
dst[len] = '\0';
return dst;
}
| 164,674
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) {
while (!pending_queries_.empty()) {
const PendingQuery& query = pending_queries_.front();
GLuint result_available = GL_FALSE;
GLuint64 result = 0;
switch (query.target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
DCHECK(query.commands_completed_fence != nullptr);
result_available =
did_finish || query.commands_completed_fence->HasCompleted();
result = result_available;
break;
case GL_COMMANDS_ISSUED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
break;
case GL_LATENCY_QUERY_CHROMIUM:
result_available = GL_TRUE;
result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
break;
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
for (const PendingReadPixels& pending_read_pixels :
pending_read_pixels_) {
if (pending_read_pixels.waiting_async_pack_queries.count(
query.service_id) > 0) {
DCHECK(!did_finish);
result_available = GL_FALSE;
result = GL_FALSE;
break;
}
}
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
DCHECK(query.buffer_shadow_update_fence);
if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) {
ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates);
result_available = GL_TRUE;
result = 0;
}
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
result_available = GL_TRUE;
FlushErrors();
result = PopError();
break;
default:
DCHECK(!IsEmulatedQueryTarget(query.target));
if (did_finish) {
result_available = GL_TRUE;
} else {
api()->glGetQueryObjectuivFn(
query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available);
}
if (result_available == GL_TRUE) {
if (feature_info_->feature_flags().ext_disjoint_timer_query) {
api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT,
&result);
} else {
GLuint temp_result = 0;
api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT,
&temp_result);
result = temp_result;
}
}
break;
}
if (!result_available) {
break;
}
query.sync->result = result;
base::subtle::Release_Store(&query.sync->process_count, query.submit_count);
pending_queries_.pop_front();
}
DCHECK(!did_finish || pending_queries_.empty());
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
|
error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) {
bool program_completion_query_deferred = false;
while (!pending_queries_.empty()) {
PendingQuery& query = pending_queries_.front();
GLuint result_available = GL_FALSE;
GLuint64 result = 0;
switch (query.target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
DCHECK(query.commands_completed_fence != nullptr);
result_available =
did_finish || query.commands_completed_fence->HasCompleted();
result = result_available;
break;
case GL_COMMANDS_ISSUED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
break;
case GL_LATENCY_QUERY_CHROMIUM:
result_available = GL_TRUE;
result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
break;
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
for (const PendingReadPixels& pending_read_pixels :
pending_read_pixels_) {
if (pending_read_pixels.waiting_async_pack_queries.count(
query.service_id) > 0) {
DCHECK(!did_finish);
result_available = GL_FALSE;
result = GL_FALSE;
break;
}
}
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
DCHECK(query.buffer_shadow_update_fence);
if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) {
ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates);
result_available = GL_TRUE;
result = 0;
}
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
result_available = GL_TRUE;
FlushErrors();
result = PopError();
break;
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
GLint status;
if (!api()->glIsProgramFn(query.program_service_id)) {
status = GL_TRUE;
} else {
api()->glGetProgramivFn(query.program_service_id,
GL_COMPLETION_STATUS_KHR, &status);
}
result_available = (status == GL_TRUE);
if (!result_available) {
// Move the query to the end of queue, so that other queries may have
// chance to be processed.
auto temp = std::move(query);
pending_queries_.pop_front();
pending_queries_.emplace_back(std::move(temp));
if (did_finish && !OnlyHasPendingProgramCompletionQueries()) {
continue;
} else {
program_completion_query_deferred = true;
}
}
result = 0;
break;
default:
DCHECK(!IsEmulatedQueryTarget(query.target));
if (did_finish) {
result_available = GL_TRUE;
} else {
api()->glGetQueryObjectuivFn(
query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available);
}
if (result_available == GL_TRUE) {
if (feature_info_->feature_flags().ext_disjoint_timer_query) {
api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT,
&result);
} else {
GLuint temp_result = 0;
api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT,
&temp_result);
result = temp_result;
}
}
break;
}
if (!result_available) {
break;
}
query.sync->result = result;
base::subtle::Release_Store(&query.sync->process_count, query.submit_count);
pending_queries_.pop_front();
}
DCHECK(!did_finish || pending_queries_.empty() ||
program_completion_query_deferred);
return error::kNoError;
}
| 172,531
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, u32 features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *mac_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
int offset;
__wsum csum;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
int type = skb_shinfo(skb)->gso_type;
if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY) ||
!(type & (SKB_GSO_UDP))))
goto out;
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
segs = NULL;
goto out;
}
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
offset = skb_checksum_start_offset(skb);
csum = skb_checksum(skb, offset, skb->len- offset, 0);
offset += skb->csum_offset;
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
skb->ip_summed = CHECKSUM_NONE;
/* Check if there is enough headroom to insert fragment header. */
if ((skb_mac_header(skb) < skb->head + frag_hdr_sz) &&
pskb_expand_head(skb, frag_hdr_sz, 0, GFP_ATOMIC))
goto out;
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = skb_network_header(skb) - skb_mac_header(skb) +
unfrag_ip6hlen;
mac_start = skb_mac_header(skb);
memmove(mac_start-frag_hdr_sz, mac_start, unfrag_len);
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
ipv6_select_ident(fptr);
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
out:
return segs;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <fernando@gont.com.ar>
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
|
static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, u32 features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *mac_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
int offset;
__wsum csum;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
int type = skb_shinfo(skb)->gso_type;
if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY) ||
!(type & (SKB_GSO_UDP))))
goto out;
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
segs = NULL;
goto out;
}
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
offset = skb_checksum_start_offset(skb);
csum = skb_checksum(skb, offset, skb->len- offset, 0);
offset += skb->csum_offset;
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
skb->ip_summed = CHECKSUM_NONE;
/* Check if there is enough headroom to insert fragment header. */
if ((skb_mac_header(skb) < skb->head + frag_hdr_sz) &&
pskb_expand_head(skb, frag_hdr_sz, 0, GFP_ATOMIC))
goto out;
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = skb_network_header(skb) - skb_mac_header(skb) +
unfrag_ip6hlen;
mac_start = skb_mac_header(skb);
memmove(mac_start-frag_hdr_sz, mac_start, unfrag_len);
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
ipv6_select_ident(fptr, (struct rt6_info *)skb_dst(skb));
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
out:
return segs;
}
| 165,854
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: flac_read_loop (SF_PRIVATE *psf, unsigned len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
pflac->pos = 0 ;
pflac->len = len ;
pflac->remain = len ;
/* First copy data that has already been decoded and buffered. */
if (pflac->frame != NULL && pflac->bufferpos < pflac->frame->header.blocksize)
flac_buffer_copy (psf) ;
/* Decode some more. */
while (pflac->pos < pflac->len)
{ if (FLAC__stream_decoder_process_single (pflac->fsd) == 0)
break ;
if (FLAC__stream_decoder_get_state (pflac->fsd) >= FLAC__STREAM_DECODER_END_OF_STREAM)
break ;
} ;
pflac->ptr = NULL ;
return pflac->pos ;
} /* flac_read_loop */
Commit Message: src/flac.c: Improve error handling
Especially when dealing with corrupt or malicious files.
CWE ID: CWE-119
|
flac_read_loop (SF_PRIVATE *psf, unsigned len)
{ FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
FLAC__StreamDecoderState state ;
pflac->pos = 0 ;
pflac->len = len ;
pflac->remain = len ;
state = FLAC__stream_decoder_get_state (pflac->fsd) ;
if (state > FLAC__STREAM_DECODER_END_OF_STREAM)
{ psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
/* Current frame is busted, so NULL the pointer. */
pflac->frame = NULL ;
} ;
/* First copy data that has already been decoded and buffered. */
if (pflac->frame != NULL && pflac->bufferpos < pflac->frame->header.blocksize)
flac_buffer_copy (psf) ;
/* Decode some more. */
while (pflac->pos < pflac->len)
{ if (FLAC__stream_decoder_process_single (pflac->fsd) == 0)
break ;
state = FLAC__stream_decoder_get_state (pflac->fsd) ;
if (state >= FLAC__STREAM_DECODER_END_OF_STREAM)
{ psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
/* Current frame is busted, so NULL the pointer. */
pflac->frame = NULL ;
break ;
} ;
} ;
pflac->ptr = NULL ;
return pflac->pos ;
} /* flac_read_loop */
| 168,255
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int SeekHead::GetVoidElementCount() const
{
return m_void_element_count;
}
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
|
int SeekHead::GetVoidElementCount() const
| 174,381
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder)
{
RELEASE_ASSERT(!holder.IsEmpty());
RELEASE_ASSERT(holder->IsObject());
v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder);
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Context> context = scriptState->context();
auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate);
if (privateIsInitialized.hasValue(context, holderObject))
return; // Already initialized.
v8::TryCatch block(isolate);
v8::Local<v8::Value> initializeFunction;
if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) {
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(initializeFunction), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) {
fprintf(stderr, "Private script error: Object constructor threw an exception.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (classObject->GetPrototype() != holderObject->GetPrototype()) {
if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate));
}
Commit Message: Blink-in-JS should not run micro tasks
If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug
(see 645211 for concrete steps).
This CL makes Blink-in-JS use callInternalFunction (instead of callFunction)
to avoid running micro tasks after Blink-in-JS' callbacks.
BUG=645211
Review-Url: https://codereview.chromium.org/2330843002
Cr-Commit-Position: refs/heads/master@{#417874}
CWE ID: CWE-79
|
static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder)
{
RELEASE_ASSERT(!holder.IsEmpty());
RELEASE_ASSERT(holder->IsObject());
v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder);
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Context> context = scriptState->context();
auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate);
if (privateIsInitialized.hasValue(context, holderObject))
return; // Already initialized.
v8::TryCatch block(isolate);
v8::Local<v8::Value> initializeFunction;
if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) {
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(initializeFunction), holder, 0, 0, isolate).ToLocal(&result)) {
fprintf(stderr, "Private script error: Object constructor threw an exception.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (classObject->GetPrototype() != holderObject->GetPrototype()) {
if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate));
}
| 172,074
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void voutf(struct GlobalConfig *config,
const char *prefix,
const char *fmt,
va_list ap)
{
size_t width = (79 - strlen(prefix));
if(!config->mute) {
size_t len;
char *ptr;
char *print_buffer;
print_buffer = curlx_mvaprintf(fmt, ap);
if(!print_buffer)
return;
len = strlen(print_buffer);
ptr = print_buffer;
while(len > 0) {
fputs(prefix, config->errors);
if(len > width) {
size_t cut = width-1;
while(!ISSPACE(ptr[cut]) && cut) {
cut--;
}
if(0 == cut)
/* not a single cutting position was found, just cut it at the
max text width then! */
cut = width-1;
(void)fwrite(ptr, cut + 1, 1, config->errors);
fputs("\n", config->errors);
ptr += cut + 1; /* skip the space too */
len -= cut;
}
else {
fputs(ptr, config->errors);
len = 0;
}
}
curl_free(print_buffer);
}
}
Commit Message: voutf: fix bad arethmetic when outputting warnings to stderr
CVE-2018-16842
Reported-by: Brian Carpenter
Bug: https://curl.haxx.se/docs/CVE-2018-16842.html
CWE ID: CWE-125
|
static void voutf(struct GlobalConfig *config,
const char *prefix,
const char *fmt,
va_list ap)
{
size_t width = (79 - strlen(prefix));
if(!config->mute) {
size_t len;
char *ptr;
char *print_buffer;
print_buffer = curlx_mvaprintf(fmt, ap);
if(!print_buffer)
return;
len = strlen(print_buffer);
ptr = print_buffer;
while(len > 0) {
fputs(prefix, config->errors);
if(len > width) {
size_t cut = width-1;
while(!ISSPACE(ptr[cut]) && cut) {
cut--;
}
if(0 == cut)
/* not a single cutting position was found, just cut it at the
max text width then! */
cut = width-1;
(void)fwrite(ptr, cut + 1, 1, config->errors);
fputs("\n", config->errors);
ptr += cut + 1; /* skip the space too */
len -= cut + 1;
}
else {
fputs(ptr, config->errors);
len = 0;
}
}
curl_free(print_buffer);
}
}
| 169,029
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
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 read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file && file->size > 0 ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
| 169,082
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static uint32_t readU32(const uint8_t* data, size_t offset) {
return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
}
Commit Message: Avoid integer overflows in parsing fonts
A malformed TTF can cause size calculations to overflow. This patch
checks the maximum reasonable value so that the total size fits in 32
bits. It also adds some explicit casting to avoid possible technical
undefined behavior when parsing sized unsigned values.
Bug: 25645298
Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616
(cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274)
CWE ID: CWE-19
|
static uint32_t readU32(const uint8_t* data, size_t offset) {
return ((uint32_t)data[offset]) << 24 | ((uint32_t)data[offset + 1]) << 16 |
((uint32_t)data[offset + 2]) << 8 | ((uint32_t)data[offset + 3]);
}
| 173,967
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool CheckClientDownloadRequest::ShouldUploadForDlpScan() {
if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads))
return false;
int check_content_compliance = g_browser_process->local_state()->GetInteger(
prefs::kCheckContentCompliance);
if (check_content_compliance !=
CheckContentComplianceValues::CHECK_DOWNLOADS &&
check_content_compliance !=
CheckContentComplianceValues::CHECK_UPLOADS_AND_DOWNLOADS)
return false;
if (policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty())
return false;
const base::ListValue* domains = g_browser_process->local_state()->GetList(
prefs::kURLsToCheckComplianceOfDownloadedContent);
url_matcher::URLMatcher matcher;
policy::url_util::AddAllowFilters(&matcher, domains);
return !matcher.MatchURL(item_->GetURL()).empty();
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org>
Reviewed-by: Tien Mai <tienmai@chromium.org>
Reviewed-by: Daniel Rubery <drubery@chromium.org>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20
|
bool CheckClientDownloadRequest::ShouldUploadForDlpScan() {
if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads))
return false;
int check_content_compliance = g_browser_process->local_state()->GetInteger(
prefs::kCheckContentCompliance);
if (check_content_compliance !=
CheckContentComplianceValues::CHECK_DOWNLOADS &&
check_content_compliance !=
CheckContentComplianceValues::CHECK_UPLOADS_AND_DOWNLOADS)
return false;
// If there's no valid DM token, the upload will fail, so we can skip
// uploading now.
if (!BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken().is_valid())
return false;
const base::ListValue* domains = g_browser_process->local_state()->GetList(
prefs::kURLsToCheckComplianceOfDownloadedContent);
url_matcher::URLMatcher matcher;
policy::url_util::AddAllowFilters(&matcher, domains);
return !matcher.MatchURL(item_->GetURL()).empty();
}
| 172,356
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: XineramaXvShmPutImage(ClientPtr client)
{
REQUEST(xvShmPutImageReq);
PanoramiXRes *draw, *gc, *port;
Bool send_event = stuff->send_event;
Bool isRoot;
int result, i, x, y;
REQUEST_SIZE_MATCH(xvShmPutImageReq);
result = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (result != Success)
result = dixLookupResourceByType((void **) &gc, stuff->gc,
XRT_GC, client, DixReadAccess);
if (result != Success)
return result;
result = dixLookupResourceByType((void **) &port, stuff->port,
XvXRTPort, client, DixReadAccess);
if (result != Success)
return result;
isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
x = stuff->drw_x;
y = stuff->drw_y;
FOR_NSCREENS_BACKWARD(i) {
if (port->info[i].id) {
stuff->drawable = draw->info[i].id;
stuff->port = port->info[i].id;
stuff->gc = gc->info[i].id;
stuff->drw_x = x;
stuff->drw_y = y;
if (isRoot) {
stuff->drw_x -= screenInfo.screens[i]->x;
stuff->drw_y -= screenInfo.screens[i]->y;
}
stuff->send_event = (send_event && !i) ? 1 : 0;
result = ProcXvShmPutImage(client);
}
}
return result;
}
Commit Message:
CWE ID: CWE-20
|
XineramaXvShmPutImage(ClientPtr client)
{
REQUEST(xvShmPutImageReq);
PanoramiXRes *draw, *gc, *port;
Bool send_event;
Bool isRoot;
int result, i, x, y;
REQUEST_SIZE_MATCH(xvShmPutImageReq);
send_event = stuff->send_event;
result = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (result != Success)
result = dixLookupResourceByType((void **) &gc, stuff->gc,
XRT_GC, client, DixReadAccess);
if (result != Success)
return result;
result = dixLookupResourceByType((void **) &port, stuff->port,
XvXRTPort, client, DixReadAccess);
if (result != Success)
return result;
isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
x = stuff->drw_x;
y = stuff->drw_y;
FOR_NSCREENS_BACKWARD(i) {
if (port->info[i].id) {
stuff->drawable = draw->info[i].id;
stuff->port = port->info[i].id;
stuff->gc = gc->info[i].id;
stuff->drw_x = x;
stuff->drw_y = y;
if (isRoot) {
stuff->drw_x -= screenInfo.screens[i]->x;
stuff->drw_y -= screenInfo.screens[i]->y;
}
stuff->send_event = (send_event && !i) ? 1 : 0;
result = ProcXvShmPutImage(client);
}
}
return result;
}
| 165,436
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) {
int i, j;
Guchar *inp, *tmp_line;
switch (colorSpace->getMode()) {
case csIndexed:
case csSeparation:
tmp_line = (Guchar *) gmalloc (length * nComps2);
for (i = 0; i < length; i++) {
for (j = 0; j < nComps2; j++) {
tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j];
}
}
colorSpace2->getRGBLine(tmp_line, out, length);
gfree (tmp_line);
break;
default:
inp = in;
for (j = 0; j < length; j++)
for (i = 0; i < nComps; i++) {
*inp = byte_lookup[*inp * nComps + i];
inp++;
}
colorSpace->getRGBLine(in, out, length);
break;
}
}
Commit Message:
CWE ID: CWE-189
|
void GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) {
int i, j;
Guchar *inp, *tmp_line;
switch (colorSpace->getMode()) {
case csIndexed:
case csSeparation:
tmp_line = (Guchar *) gmallocn (length, nComps2);
for (i = 0; i < length; i++) {
for (j = 0; j < nComps2; j++) {
tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j];
}
}
colorSpace2->getRGBLine(tmp_line, out, length);
gfree (tmp_line);
break;
default:
inp = in;
for (j = 0; j < length; j++)
for (i = 0; i < nComps; i++) {
*inp = byte_lookup[*inp * nComps + i];
inp++;
}
colorSpace->getRGBLine(in, out, length);
break;
}
}
| 164,611
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SiteInstanceTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
old_browser_client_(NULL) {
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
SiteInstanceTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
old_client_(NULL),
old_browser_client_(NULL) {
}
| 171,011
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int send_reply(struct svcxprt_rdma *rdma,
struct svc_rqst *rqstp,
struct page *page,
struct rpcrdma_msg *rdma_resp,
struct svc_rdma_req_map *vec,
int byte_count,
u32 inv_rkey)
{
struct svc_rdma_op_ctxt *ctxt;
struct ib_send_wr send_wr;
u32 xdr_off;
int sge_no;
int sge_bytes;
int page_no;
int pages;
int ret = -EIO;
/* Prepare the context */
ctxt = svc_rdma_get_context(rdma);
ctxt->direction = DMA_TO_DEVICE;
ctxt->pages[0] = page;
ctxt->count = 1;
/* Prepare the SGE for the RPCRDMA Header */
ctxt->sge[0].lkey = rdma->sc_pd->local_dma_lkey;
ctxt->sge[0].length =
svc_rdma_xdr_get_reply_hdr_len((__be32 *)rdma_resp);
ctxt->sge[0].addr =
ib_dma_map_page(rdma->sc_cm_id->device, page, 0,
ctxt->sge[0].length, DMA_TO_DEVICE);
if (ib_dma_mapping_error(rdma->sc_cm_id->device, ctxt->sge[0].addr))
goto err;
svc_rdma_count_mappings(rdma, ctxt);
ctxt->direction = DMA_TO_DEVICE;
/* Map the payload indicated by 'byte_count' */
xdr_off = 0;
for (sge_no = 1; byte_count && sge_no < vec->count; sge_no++) {
sge_bytes = min_t(size_t, vec->sge[sge_no].iov_len, byte_count);
byte_count -= sge_bytes;
ctxt->sge[sge_no].addr =
dma_map_xdr(rdma, &rqstp->rq_res, xdr_off,
sge_bytes, DMA_TO_DEVICE);
xdr_off += sge_bytes;
if (ib_dma_mapping_error(rdma->sc_cm_id->device,
ctxt->sge[sge_no].addr))
goto err;
svc_rdma_count_mappings(rdma, ctxt);
ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey;
ctxt->sge[sge_no].length = sge_bytes;
}
if (byte_count != 0) {
pr_err("svcrdma: Could not map %d bytes\n", byte_count);
goto err;
}
/* Save all respages in the ctxt and remove them from the
* respages array. They are our pages until the I/O
* completes.
*/
pages = rqstp->rq_next_page - rqstp->rq_respages;
for (page_no = 0; page_no < pages; page_no++) {
ctxt->pages[page_no+1] = rqstp->rq_respages[page_no];
ctxt->count++;
rqstp->rq_respages[page_no] = NULL;
}
rqstp->rq_next_page = rqstp->rq_respages + 1;
if (sge_no > rdma->sc_max_sge) {
pr_err("svcrdma: Too many sges (%d)\n", sge_no);
goto err;
}
memset(&send_wr, 0, sizeof send_wr);
ctxt->cqe.done = svc_rdma_wc_send;
send_wr.wr_cqe = &ctxt->cqe;
send_wr.sg_list = ctxt->sge;
send_wr.num_sge = sge_no;
if (inv_rkey) {
send_wr.opcode = IB_WR_SEND_WITH_INV;
send_wr.ex.invalidate_rkey = inv_rkey;
} else
send_wr.opcode = IB_WR_SEND;
send_wr.send_flags = IB_SEND_SIGNALED;
ret = svc_rdma_send(rdma, &send_wr);
if (ret)
goto err;
return 0;
err:
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
return ret;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
static int send_reply(struct svcxprt_rdma *rdma,
static int svc_rdma_send_reply_msg(struct svcxprt_rdma *rdma,
__be32 *rdma_argp, __be32 *rdma_resp,
struct svc_rqst *rqstp,
__be32 *wr_lst, __be32 *rp_ch)
{
struct svc_rdma_op_ctxt *ctxt;
u32 inv_rkey;
int ret;
dprintk("svcrdma: sending %s reply: head=%zu, pagelen=%u, tail=%zu\n",
(rp_ch ? "RDMA_NOMSG" : "RDMA_MSG"),
rqstp->rq_res.head[0].iov_len,
rqstp->rq_res.page_len,
rqstp->rq_res.tail[0].iov_len);
ctxt = svc_rdma_get_context(rdma);
ret = svc_rdma_map_reply_hdr(rdma, ctxt, rdma_resp,
svc_rdma_reply_hdr_len(rdma_resp));
if (ret < 0)
goto err;
if (!rp_ch) {
ret = svc_rdma_map_reply_msg(rdma, ctxt,
&rqstp->rq_res, wr_lst);
if (ret < 0)
goto err;
}
svc_rdma_save_io_pages(rqstp, ctxt);
inv_rkey = 0;
if (rdma->sc_snd_w_inv)
inv_rkey = svc_rdma_get_inv_rkey(rdma_argp, wr_lst, rp_ch);
ret = svc_rdma_post_send_wr(rdma, ctxt, 1 + ret, inv_rkey);
if (ret)
goto err;
return 0;
err:
pr_err("svcrdma: failed to post Send WR (%d)\n", ret);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
return ret;
}
/* Given the client-provided Write and Reply chunks, the server was not
* able to form a complete reply. Return an RDMA_ERROR message so the
* client can retire this RPC transaction. As above, the Send completion
* routine releases payload pages that were part of a previous RDMA Write.
*
* Remote Invalidation is skipped for simplicity.
*/
static int svc_rdma_send_error_msg(struct svcxprt_rdma *rdma,
__be32 *rdma_resp, struct svc_rqst *rqstp)
{
struct svc_rdma_op_ctxt *ctxt;
__be32 *p;
int ret;
ctxt = svc_rdma_get_context(rdma);
/* Replace the original transport header with an
* RDMA_ERROR response. XID etc are preserved.
*/
p = rdma_resp + 3;
*p++ = rdma_error;
*p = err_chunk;
ret = svc_rdma_map_reply_hdr(rdma, ctxt, rdma_resp, 20);
if (ret < 0)
goto err;
svc_rdma_save_io_pages(rqstp, ctxt);
ret = svc_rdma_post_send_wr(rdma, ctxt, 1 + ret, 0);
if (ret)
goto err;
return 0;
err:
pr_err("svcrdma: failed to post Send WR (%d)\n", ret);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
return ret;
}
| 168,167
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message:
CWE ID: CWE-310
|
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
| 164,791
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ExtensionTtsPlatformImplChromeOs::Speak(
const std::string& utterance,
const std::string& locale,
const std::string& gender,
double rate,
double pitch,
double volume) {
chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get();
if (!cros_library->EnsureLoaded()) {
set_error(kCrosLibraryNotLoadedError);
return false;
}
std::string options;
if (!locale.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyLocale,
locale,
&options);
}
if (!gender.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyGender,
gender,
&options);
}
if (rate >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyRate,
DoubleToString(rate * 5),
&options);
}
if (pitch >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyPitch,
DoubleToString(pitch * 2),
&options);
}
if (volume >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyVolume,
DoubleToString(volume * 5),
&options);
}
if (!options.empty()) {
cros_library->GetSpeechSynthesisLibrary()->SetSpeakProperties(
options.c_str());
}
return cros_library->GetSpeechSynthesisLibrary()->Speak(utterance.c_str());
}
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 ExtensionTtsPlatformImplChromeOs::Speak(
int utterance_id,
const std::string& utterance,
const std::string& lang,
const UtteranceContinuousParameters& params) {
chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get();
if (!cros_library->EnsureLoaded()) {
set_error(kCrosLibraryNotLoadedError);
return false;
}
utterance_id_ = utterance_id;
utterance_length_ = utterance.size();
std::string options;
if (!lang.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyLocale,
lang,
&options);
}
if (params.rate >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyRate,
DoubleToString(1.5 + params.rate * 2.5),
&options);
}
if (params.pitch >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyPitch,
DoubleToString(params.pitch),
&options);
}
if (params.volume >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyVolume,
DoubleToString(params.volume * 5),
&options);
}
if (!options.empty()) {
cros_library->GetSpeechSynthesisLibrary()->SetSpeakProperties(
options.c_str());
}
bool result =
cros_library->GetSpeechSynthesisLibrary()->Speak(utterance.c_str());
if (result) {
ExtensionTtsController* controller = ExtensionTtsController::GetInstance();
controller->OnTtsEvent(utterance_id_, TTS_EVENT_START, 0, std::string());
PollUntilSpeechFinishes(utterance_id_);
}
return result;
}
| 170,399
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: uint64 Clipboard::GetSequenceNumber(Buffer buffer) {
return 0;
}
Commit Message: Use XFixes to update the clipboard sequence number.
BUG=73478
TEST=manual testing
Review URL: http://codereview.chromium.org/8501002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109528 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
uint64 Clipboard::GetSequenceNumber(Buffer buffer) {
if (buffer == BUFFER_STANDARD)
return SelectionChangeObserver::GetInstance()->clipboard_sequence_number();
else
return SelectionChangeObserver::GetInstance()->primary_sequence_number();
}
| 170,962
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void ext2_put_super (struct super_block * sb)
{
int db_count;
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
ext2_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
struct ext2_super_block *es = sbi->s_es;
spin_lock(&sbi->s_lock);
es->s_state = cpu_to_le16(sbi->s_mount_state);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, 1);
}
db_count = sbi->s_gdb_count;
for (i = 0; i < db_count; i++)
if (sbi->s_group_desc[i])
brelse (sbi->s_group_desc[i]);
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
brelse (sbi->s_sbh);
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
static void ext2_put_super (struct super_block * sb)
{
int db_count;
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
if (sbi->s_mb_cache) {
ext2_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (!(sb->s_flags & MS_RDONLY)) {
struct ext2_super_block *es = sbi->s_es;
spin_lock(&sbi->s_lock);
es->s_state = cpu_to_le16(sbi->s_mount_state);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, 1);
}
db_count = sbi->s_gdb_count;
for (i = 0; i < db_count; i++)
if (sbi->s_group_desc[i])
brelse (sbi->s_group_desc[i]);
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
brelse (sbi->s_sbh);
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
| 169,974
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
int prediction_resistance,
const unsigned char *adin, size_t adinlen)
{
int reseed_required = 0;
if (drbg->state != DRBG_READY) {
rand_drbg_restart(drbg, NULL, 0, 0);
if (drbg->state == DRBG_ERROR) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
return 0;
}
if (drbg->state == DRBG_UNINITIALISED) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
return 0;
}
}
if (outlen > drbg->max_request) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
return 0;
}
if (adinlen > drbg->max_adinlen) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
return 0;
return 0;
}
if (drbg->fork_count != rand_fork_count) {
drbg->fork_count = rand_fork_count;
reseed_required = 1;
}
}
Commit Message:
CWE ID: CWE-330
|
int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
int prediction_resistance,
const unsigned char *adin, size_t adinlen)
{
int fork_id;
int reseed_required = 0;
if (drbg->state != DRBG_READY) {
rand_drbg_restart(drbg, NULL, 0, 0);
if (drbg->state == DRBG_ERROR) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
return 0;
}
if (drbg->state == DRBG_UNINITIALISED) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
return 0;
}
}
if (outlen > drbg->max_request) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
return 0;
}
if (adinlen > drbg->max_adinlen) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
return 0;
return 0;
}
fork_id = openssl_get_fork_id();
if (drbg->fork_id != fork_id) {
drbg->fork_id = fork_id;
reseed_required = 1;
}
}
| 165,143
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext2_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb_cache_entry_release(ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb2_cache_entry *ce;
struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb2_cache_entry_find_first(ext2_mb_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
/*
* We have to be careful about races with freeing or
* rehashing of xattr block. Once we hold buffer lock
* xattr block's state is stable so we can check
* whether the block got freed / rehashed or not.
* Since we unhash mbcache entry under buffer lock when
* freeing / rehashing xattr block, checking whether
* entry is still hashed is reliable.
*/
if (hlist_bl_unhashed(&ce->e_hash_list)) {
mb2_cache_entry_put(ext2_mb_cache, ce);
unlock_buffer(bh);
brelse(bh);
goto again;
} else if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb2_cache_entry_touch(ext2_mb_cache, ce);
mb2_cache_entry_put(ext2_mb_cache, ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb2_cache_entry_find_next(ext2_mb_cache, ce);
}
return NULL;
}
| 169,977
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.