instruction
stringclasses 1
value | input
stringlengths 93
3.53k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool AddInitialUrlToPreconnectPrediction(const GURL& initial_url,
PreconnectPrediction* prediction) {
GURL initial_origin = initial_url.GetOrigin();
static const int kMinSockets = 2;
if (!prediction->requests.empty() &&
prediction->requests.front().origin == initial_origin) {
prediction->requests.front().num_sockets =
std::max(prediction->requests.front().num_sockets, kMinSockets);
} else if (initial_origin.is_valid() &&
initial_origin.SchemeIsHTTPOrHTTPS()) {
url::Origin origin = url::Origin::Create(initial_origin);
prediction->requests.emplace(prediction->requests.begin(), initial_origin,
kMinSockets,
net::NetworkIsolationKey(origin, origin));
}
return !prediction->requests.empty();
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
bool AddInitialUrlToPreconnectPrediction(const GURL& initial_url,
PreconnectPrediction* prediction) {
url::Origin initial_origin = url::Origin::Create(initial_url);
static const int kMinSockets = 2;
if (!prediction->requests.empty() &&
prediction->requests.front().origin == initial_origin) {
prediction->requests.front().num_sockets =
std::max(prediction->requests.front().num_sockets, kMinSockets);
} else if (!initial_origin.opaque() &&
(initial_origin.scheme() == url::kHttpScheme ||
initial_origin.scheme() == url::kHttpsScheme)) {
prediction->requests.emplace(
prediction->requests.begin(), initial_origin, kMinSockets,
net::NetworkIsolationKey(initial_origin, initial_origin));
}
return !prediction->requests.empty();
}
| 172,369
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PPB_URLLoader_Impl::~PPB_URLLoader_Impl() {
}
Commit Message: Break path whereby AssociatedURLLoader::~AssociatedURLLoader() is re-entered on top of itself.
BUG=159429
Review URL: https://chromiumcodereview.appspot.com/11359222
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168150 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
|
PPB_URLLoader_Impl::~PPB_URLLoader_Impl() {
// There is a path whereby the destructor for the loader_ member can
// invoke InstanceWasDeleted() upon this PPB_URLLoader_Impl, thereby
// re-entering the scoped_ptr destructor with the same scoped_ptr object
// via loader_.reset(). Be sure that loader_ is first NULL then destroy
// the scoped_ptr. See http://crbug.com/159429.
scoped_ptr<WebKit::WebURLLoader> for_destruction_only(loader_.release());
}
| 170,670
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void WebContentsImpl::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(interstitial_page);
render_manager_.set_interstitial_page(interstitial_page);
FOR_EACH_OBSERVER(WebContentsObserver, observers_,
DidAttachInterstitialPage());
}
Commit Message: Cancel JavaScript dialogs when an interstitial appears.
BUG=295695
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/24360011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void WebContentsImpl::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(interstitial_page);
render_manager_.set_interstitial_page(interstitial_page);
// Cancel any visible dialogs so that they don't interfere with the
// interstitial.
if (dialog_manager_)
dialog_manager_->CancelActiveAndPendingDialogs(this);
FOR_EACH_OBSERVER(WebContentsObserver, observers_,
DidAttachInterstitialPage());
}
| 171,160
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void Encoder::EncodeFrameInternal(const VideoSource &video,
const unsigned long frame_flags) {
vpx_codec_err_t res;
const vpx_image_t *img = video.img();
if (!encoder_.priv) {
cfg_.g_w = img->d_w;
cfg_.g_h = img->d_h;
cfg_.g_timebase = video.timebase();
cfg_.rc_twopass_stats_in = stats_->buf();
res = vpx_codec_enc_init(&encoder_, CodecInterface(), &cfg_,
init_flags_);
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) {
cfg_.g_w = img->d_w;
cfg_.g_h = img->d_h;
res = vpx_codec_enc_config_set(&encoder_, &cfg_);
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
REGISTER_STATE_CHECK(
res = vpx_codec_encode(&encoder_,
video.img(), video.pts(), video.duration(),
frame_flags, deadline_));
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void Encoder::EncodeFrameInternal(const VideoSource &video,
const unsigned long frame_flags) {
vpx_codec_err_t res;
const vpx_image_t *img = video.img();
if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) {
cfg_.g_w = img->d_w;
cfg_.g_h = img->d_h;
res = vpx_codec_enc_config_set(&encoder_, &cfg_);
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
API_REGISTER_STATE_CHECK(
res = vpx_codec_encode(&encoder_, img, video.pts(), video.duration(),
frame_flags, deadline_));
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
| 174,536
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual void ChangeInputMethod(const std::string& input_method_id) {
tentative_current_input_method_id_ = input_method_id;
if (ibus_daemon_process_handle_ == base::kNullProcessHandle &&
chromeos::input_method::IsKeyboardLayout(input_method_id)) {
ChangeCurrentInputMethodFromId(input_method_id);
} else {
StartInputMethodDaemon();
if (!ChangeInputMethodViaIBus(input_method_id)) {
VLOG(1) << "Failed to change the input method to " << input_method_id
<< " (deferring)";
}
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual void ChangeInputMethod(const std::string& input_method_id) {
tentative_current_input_method_id_ = input_method_id;
if (ibus_daemon_process_handle_ == base::kNullProcessHandle &&
input_method::IsKeyboardLayout(input_method_id)) {
ChangeCurrentInputMethodFromId(input_method_id);
} else {
StartInputMethodDaemon();
if (!ChangeInputMethodViaIBus(input_method_id)) {
VLOG(1) << "Failed to change the input method to " << input_method_id
<< " (deferring)";
}
}
}
| 170,480
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
}
Commit Message:
CWE ID: CWE-200
|
xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
}
| 164,728
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
UINT status;
UINT32 Length;
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
Length = drdynvc_read_variable_uint(s, Sp);
WLog_Print(drdynvc->log, WLOG_DEBUG,
"process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp,
cbChId, ChannelId, Length);
status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId,
Length);
if (status)
return status;
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID:
|
static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
UINT status;
UINT32 Length;
UINT32 ChannelId;
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId) + drdynvc_cblen_to_bytes(Sp))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
Length = drdynvc_read_variable_uint(s, Sp);
WLog_Print(drdynvc->log, WLOG_DEBUG,
"process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp,
cbChId, ChannelId, Length);
status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId,
Length);
if (status)
return status;
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
| 168,938
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: FrameView::FrameView(LocalFrame* frame)
: m_frame(frame)
, m_canHaveScrollbars(true)
, m_slowRepaintObjectCount(0)
, m_hasPendingLayout(false)
, m_layoutSubtreeRoot(0)
, m_inSynchronousPostLayout(false)
, m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
, m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
, m_isTransparent(false)
, m_baseBackgroundColor(Color::white)
, m_mediaType("screen")
, m_overflowStatusDirty(true)
, m_viewportRenderer(0)
, m_wasScrolledByUser(false)
, m_inProgrammaticScroll(false)
, m_safeToPropagateScrollToParent(true)
, m_isTrackingPaintInvalidations(false)
, m_scrollCorner(nullptr)
, m_hasSoftwareFilters(false)
, m_visibleContentScaleFactor(1)
, m_inputEventsScaleFactorForEmulation(1)
, m_layoutSizeFixedToFrameSize(true)
, m_didScrollTimer(this, &FrameView::didScrollTimerFired)
{
ASSERT(m_frame);
init();
if (!m_frame->isMainFrame())
return;
ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
}
Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea.
updateWidgetPositions() can destroy the render tree, so it should never
be called from inside RenderLayerScrollableArea. Leaving it there allows
for the potential of use-after-free bugs.
BUG=402407
R=vollick@chromium.org
Review URL: https://codereview.chromium.org/490473003
git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416
|
FrameView::FrameView(LocalFrame* frame)
: m_frame(frame)
, m_canHaveScrollbars(true)
, m_slowRepaintObjectCount(0)
, m_hasPendingLayout(false)
, m_layoutSubtreeRoot(0)
, m_inSynchronousPostLayout(false)
, m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
, m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
, m_isTransparent(false)
, m_baseBackgroundColor(Color::white)
, m_mediaType("screen")
, m_overflowStatusDirty(true)
, m_viewportRenderer(0)
, m_wasScrolledByUser(false)
, m_inProgrammaticScroll(false)
, m_safeToPropagateScrollToParent(true)
, m_isTrackingPaintInvalidations(false)
, m_scrollCorner(nullptr)
, m_hasSoftwareFilters(false)
, m_visibleContentScaleFactor(1)
, m_inputEventsScaleFactorForEmulation(1)
, m_layoutSizeFixedToFrameSize(true)
, m_didScrollTimer(this, &FrameView::didScrollTimerFired)
, m_needsUpdateWidgetPositions(false)
{
ASSERT(m_frame);
init();
if (!m_frame->isMainFrame())
return;
ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
}
| 171,635
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SegmentInfo::SegmentInfo(
Segment* pSegment,
long long start,
long long size_,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_start(start),
m_size(size_),
m_element_start(element_start),
m_element_size(element_size),
m_pMuxingAppAsUTF8(NULL),
m_pWritingAppAsUTF8(NULL),
m_pTitleAsUTF8(NULL)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
SegmentInfo::SegmentInfo(
| 174,439
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool PermissionsRemoveFunction::RunImpl() {
scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
scoped_refptr<PermissionSet> permissions =
helpers::UnpackPermissionSet(params->permissions, &error_);
if (!permissions.get())
return false;
const extensions::Extension* extension = GetExtension();
APIPermissionSet apis = permissions->apis();
for (APIPermissionSet::const_iterator i = apis.begin();
i != apis.end(); ++i) {
if (!i->info()->supports_optional()) {
error_ = ErrorUtils::FormatErrorMessage(
kNotWhitelistedError, i->name());
return false;
}
}
const PermissionSet* required = extension->required_permission_set();
scoped_refptr<PermissionSet> intersection(
PermissionSet::CreateIntersection(permissions.get(), required));
if (!intersection->IsEmpty()) {
error_ = kCantRemoveRequiredPermissionsError;
results_ = Remove::Results::Create(false);
return false;
}
PermissionsUpdater(profile()).RemovePermissions(extension, permissions.get());
results_ = Remove::Results::Create(true);
return true;
}
Commit Message: Check prefs before allowing extension file access in the permissions API.
R=mpcomplete@chromium.org
BUG=169632
Review URL: https://chromiumcodereview.appspot.com/11884008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool PermissionsRemoveFunction::RunImpl() {
scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
ExtensionPrefs* prefs = ExtensionSystem::Get(profile_)->extension_prefs();
scoped_refptr<PermissionSet> permissions =
helpers::UnpackPermissionSet(params->permissions,
prefs->AllowFileAccess(extension_->id()),
&error_);
if (!permissions.get())
return false;
const extensions::Extension* extension = GetExtension();
APIPermissionSet apis = permissions->apis();
for (APIPermissionSet::const_iterator i = apis.begin();
i != apis.end(); ++i) {
if (!i->info()->supports_optional()) {
error_ = ErrorUtils::FormatErrorMessage(
kNotWhitelistedError, i->name());
return false;
}
}
const PermissionSet* required = extension->required_permission_set();
scoped_refptr<PermissionSet> intersection(
PermissionSet::CreateIntersection(permissions.get(), required));
if (!intersection->IsEmpty()) {
error_ = kCantRemoveRequiredPermissionsError;
results_ = Remove::Results::Create(false);
return false;
}
PermissionsUpdater(profile()).RemovePermissions(extension, permissions.get());
results_ = Remove::Results::Create(true);
return true;
}
| 171,443
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: P2PQuicStreamTest()
: connection_(
new quic::test::MockQuicConnection(&connection_helper_,
&alarm_factory_,
quic::Perspective::IS_CLIENT)),
session_(connection_) {
session_.Initialize();
stream_ = new P2PQuicStreamImpl(kStreamId, &session_);
stream_->SetDelegate(&delegate_);
session_.ActivateStream(std::unique_ptr<P2PQuicStreamImpl>(stream_));
connection_helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
}
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
|
P2PQuicStreamTest()
: connection_(
new quic::test::MockQuicConnection(&connection_helper_,
&alarm_factory_,
quic::Perspective::IS_CLIENT)),
session_(connection_) {
session_.Initialize();
stream_ = new P2PQuicStreamImpl(kStreamId, &session_, kWriteBufferSize);
stream_->SetDelegate(&delegate_);
session_.ActivateStream(std::unique_ptr<P2PQuicStreamImpl>(stream_));
connection_helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
}
| 172,264
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
blobRegistry().addDataToStream(url, streamData);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
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 ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
void BlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry()) {
WebThreadSafeData webThreadSafeData(streamData);
registry->addDataToStream(url, webThreadSafeData);
}
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
| 170,680
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Segment::Segment(
IMkvReader* pReader,
long long elem_start,
long long start,
long long size) :
m_pReader(pReader),
m_element_start(elem_start),
m_start(start),
m_size(size),
m_pos(start),
m_pUnknownSize(0),
m_pSeekHead(NULL),
m_pInfo(NULL),
m_pTracks(NULL),
m_pCues(NULL),
m_pChapters(NULL),
m_clusters(NULL),
m_clusterCount(0),
m_clusterPreloadCount(0),
m_clusterSize(0)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Segment::Segment(
| 174,438
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static size_t TrimTrailingSpaces ( char * firstChar, size_t origLen )
{
if ( origLen == 0 ) return 0;
char * lastChar = firstChar + origLen - 1;
if ( (*lastChar != ' ') && (*lastChar != 0) ) return origLen; // Nothing to do.
while ( (firstChar <= lastChar) && ((*lastChar == ' ') || (*lastChar == 0)) ) --lastChar;
XMP_Assert ( (lastChar == firstChar-1) ||
((lastChar >= firstChar) && (*lastChar != ' ') && (*lastChar != 0)) );
size_t newLen = (size_t)((lastChar+1) - firstChar);
XMP_Assert ( newLen <= origLen );
if ( newLen < origLen ) {
++lastChar;
*lastChar = 0;
}
return newLen;
} // TrimTrailingSpaces
Commit Message:
CWE ID: CWE-416
|
static size_t TrimTrailingSpaces ( char * firstChar, size_t origLen )
{
if ( !firstChar || origLen == 0 ) return 0;
char * lastChar = firstChar + origLen - 1;
if ( (*lastChar != ' ') && (*lastChar != 0) ) return origLen; // Nothing to do.
while ( (firstChar <= lastChar) && ((*lastChar == ' ') || (*lastChar == 0)) ) --lastChar;
XMP_Assert ( (lastChar == firstChar-1) ||
((lastChar >= firstChar) && (*lastChar != ' ') && (*lastChar != 0)) );
size_t newLen = (size_t)((lastChar+1) - firstChar);
XMP_Assert ( newLen <= origLen );
if ( newLen < origLen ) {
++lastChar;
*lastChar = 0;
}
return newLen;
} // TrimTrailingSpaces
| 165,367
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
Commit Message: Fix bounds checks again.
CWE ID: CWE-119
|
cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SHORT_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
| 165,625
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PaintLayerScrollableArea::UpdateCompositingLayersAfterScroll() {
PaintLayerCompositor* compositor = GetLayoutBox()->View()->Compositor();
if (!compositor->InCompositingMode())
return;
if (UsesCompositedScrolling()) {
DCHECK(Layer()->HasCompositedLayerMapping());
ScrollingCoordinator* scrolling_coordinator = GetScrollingCoordinator();
bool handled_scroll =
Layer()->IsRootLayer() && scrolling_coordinator &&
scrolling_coordinator->UpdateCompositedScrollOffset(this);
if (!handled_scroll) {
if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
Layer()->GetCompositedLayerMapping()->SetNeedsGraphicsLayerUpdate(
kGraphicsLayerUpdateSubtree);
}
compositor->SetNeedsCompositingUpdate(
kCompositingUpdateAfterGeometryChange);
}
if (Layer()->IsRootLayer()) {
LocalFrame* frame = GetLayoutBox()->GetFrame();
if (frame && frame->View() &&
frame->View()->HasViewportConstrainedObjects()) {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
} else {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer
Bug: 927560
Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4
Reviewed-on: https://chromium-review.googlesource.com/c/1452701
Reviewed-by: Chris Harrelson <chrishtr@chromium.org>
Commit-Queue: Mason Freed <masonfreed@chromium.org>
Cr-Commit-Position: refs/heads/master@{#628942}
CWE ID: CWE-79
|
void PaintLayerScrollableArea::UpdateCompositingLayersAfterScroll() {
PaintLayerCompositor* compositor = GetLayoutBox()->View()->Compositor();
if (!compositor->InCompositingMode())
return;
if (UsesCompositedScrolling()) {
DCHECK(Layer()->HasCompositedLayerMapping());
ScrollingCoordinator* scrolling_coordinator = GetScrollingCoordinator();
bool handled_scroll =
(Layer()->IsRootLayer() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) &&
scrolling_coordinator &&
scrolling_coordinator->UpdateCompositedScrollOffset(this);
if (!handled_scroll) {
if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
Layer()->GetCompositedLayerMapping()->SetNeedsGraphicsLayerUpdate(
kGraphicsLayerUpdateSubtree);
}
compositor->SetNeedsCompositingUpdate(
kCompositingUpdateAfterGeometryChange);
}
if (Layer()->IsRootLayer()) {
LocalFrame* frame = GetLayoutBox()->GetFrame();
if (frame && frame->View() &&
frame->View()->HasViewportConstrainedObjects()) {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
} else {
Layer()->SetNeedsCompositingInputsUpdate();
}
}
| 172,047
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long long Chapters::Atom::GetTime(
const Chapters* pChapters,
long long timecode)
{
if (pChapters == NULL)
return -1;
Segment* const pSegment = pChapters->m_pSegment;
if (pSegment == NULL) // weird
return -1;
const SegmentInfo* const pInfo = pSegment->GetInfo();
if (pInfo == NULL)
return -1;
const long long timecode_scale = pInfo->GetTimeCodeScale();
if (timecode_scale < 1) // weird
return -1;
if (timecode < 0)
return -1;
const long long result = timecode_scale * timecode;
return result;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Chapters::Atom::GetTime(
| 174,361
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() {
if (original_skia_image_) {
std::unique_ptr<gpu::SyncToken> sync_token =
base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken()));
if (original_skia_image_thread_id_ !=
Platform::Current()->CurrentThread()->ThreadId()) {
PostCrossThreadTask(
*original_skia_image_task_runner_, FROM_HERE,
CrossThreadBind(
&DestroySkImageOnOriginalThread, std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
WTF::Passed(std::move(sync_token))));
} else {
DestroySkImageOnOriginalThread(
std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
std::move(sync_token));
}
}
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (original_skia_image_) {
std::unique_ptr<gpu::SyncToken> sync_token =
base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken()));
if (!original_skia_image_task_runner_->BelongsToCurrentThread()) {
PostCrossThreadTask(
*original_skia_image_task_runner_, FROM_HERE,
CrossThreadBind(
&DestroySkImageOnOriginalThread, std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
WTF::Passed(std::move(sync_token))));
} else {
DestroySkImageOnOriginalThread(
std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
std::move(sync_token));
}
}
}
| 172,599
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RenderViewImpl::OnSwapOut(const ViewMsg_SwapOut_Params& params) {
OnStop();
if (!is_swapped_out_) {
SyncNavigationState();
webview()->dispatchUnloadEvent();
SetSwappedOut(true);
WebURLRequest request(GURL("about:swappedout"));
webview()->mainFrame()->loadRequest(request);
}
Send(new ViewHostMsg_SwapOut_ACK(routing_id_, params));
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderViewImpl::OnSwapOut(const ViewMsg_SwapOut_Params& params) {
OnStop();
if (!is_swapped_out_) {
SyncNavigationState();
webview()->dispatchUnloadEvent();
SetSwappedOut(true);
// to chrome::kSwappedOutURL. If that happens to be to the page we had been
GURL swappedOutURL(chrome::kSwappedOutURL);
WebURLRequest request(swappedOutURL);
webview()->mainFrame()->loadRequest(request);
}
Send(new ViewHostMsg_SwapOut_ACK(routing_id_, params));
}
| 171,031
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl(
DownloadStatus status,
ContentSetting setting) {
DCHECK((GetSettingFromDownloadStatus(status) == setting) ||
(GetDownloadStatusFromSetting(setting) == status))
<< "status " << status << " and setting " << setting
<< " do not correspond to each other";
ContentSetting last_setting = GetSettingFromDownloadStatus(status_);
DownloadUiStatus last_ui_status = ui_status_;
status_ = status;
ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_);
if (!web_contents())
return;
if (last_setting == setting && last_ui_status == ui_status_)
return;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
content::Source<content::WebContents>(web_contents()),
content::NotificationService::NoDetails());
}
Commit Message: Don't reset TabDownloadState on history back/forward
Currently performing forward/backward on a tab will reset the TabDownloadState.
Which allows javascript code to do trigger multiple downloads.
This CL disables that behavior by not resetting the TabDownloadState on
forward/back.
It is still possible to reset the TabDownloadState through user gesture
or using browser initiated download.
BUG=848535
Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863
Reviewed-on: https://chromium-review.googlesource.com/1108959
Commit-Queue: Min Qin <qinmin@chromium.org>
Reviewed-by: Xing Liu <xingliu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#574437}
CWE ID:
|
void DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl(
DownloadStatus status,
ContentSetting setting) {
DCHECK((GetSettingFromDownloadStatus(status) == setting) ||
(GetDownloadStatusFromSetting(setting) == status))
<< "status " << status << " and setting " << setting
<< " do not correspond to each other";
ContentSetting last_setting = GetSettingFromDownloadStatus(status_);
DownloadUiStatus last_ui_status = ui_status_;
status_ = status;
ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_);
if (!web_contents())
return;
if (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED) {
if (!initial_page_host_.empty())
restricted_hosts_.emplace(initial_page_host_);
}
if (last_setting == setting && last_ui_status == ui_status_)
return;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
content::Source<content::WebContents>(web_contents()),
content::NotificationService::NoDetails());
}
| 173,190
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
chr[ len ++ ] = 0;
return chr;
}
Commit Message: New Pre Source
CWE ID: CWE-119
|
SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
chr[ len ++ ] = 0;
return chr;
}
| 169,314
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) {
WaitableEvent done(false, false);
scoped_refptr<WorkerTask> task(new WorkerTask(work, &done));
history_service_->ScheduleDBTask(task.get(), this);
done.Wait();
}
Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed.
BUG=69561
TEST=Run sync manually and run integration tests, sync should not crash.
Review URL: http://codereview.chromium.org/7016007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) {
WaitableEvent done(false, false);
scoped_refptr<WorkerTask> task(new WorkerTask(work, &done));
history_service_->ScheduleDBTask(task.get(), &cancelable_consumer_);
done.Wait();
}
| 170,613
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: juniper_mlfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLC_UI):
case (LLC_UI<<8):
isoclns_print(ndo, p, l2info.length, l2info.caplen);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
juniper_mlfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLC_UI):
case (LLC_UI<<8):
isoclns_print(ndo, p, l2info.length);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
| 167,951
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool Track::VetEntry(const BlockEntry* pBlockEntry) const
{
assert(pBlockEntry);
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
assert(pBlock->GetTrackNumber() == m_info.number);
if (!pBlock || pBlock->GetTrackNumber() != m_info.number)
return false;
return true;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
bool Track::VetEntry(const BlockEntry* pBlockEntry) const
bool Track::VetEntry(const BlockEntry* pBlockEntry) const {
assert(pBlockEntry);
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
assert(pBlock->GetTrackNumber() == m_info.number);
if (!pBlock || pBlock->GetTrackNumber() != m_info.number)
return false;
// This function is used during a seek to determine whether the
// frame is a valid seek target. This default function simply
// returns true, which means all frames are valid seek targets.
// It gets overridden by the VideoTrack class, because only video
// keyframes can be used as seek target.
return true;
}
| 174,451
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue()
{
return JSStringCreateWithCharacters(0, 0);
}
Commit Message: [GTK][WTR] Implement AccessibilityUIElement::stringValue
https://bugs.webkit.org/show_bug.cgi?id=102951
Reviewed by Martin Robinson.
Implement AccessibilityUIElement::stringValue in the ATK backend
in the same manner it is implemented in DumpRenderTree.
* WebKitTestRunner/InjectedBundle/atk/AccessibilityUIElementAtk.cpp:
(WTR::replaceCharactersForResults):
(WTR):
(WTR::AccessibilityUIElement::stringValue):
git-svn-id: svn://svn.chromium.org/blink/trunk@135485 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue()
{
if (!m_element || !ATK_IS_TEXT(m_element))
return JSStringCreateWithCharacters(0, 0);
GOwnPtr<gchar> text(atk_text_get_text(ATK_TEXT(m_element), 0, -1));
GOwnPtr<gchar> textWithReplacedCharacters(replaceCharactersForResults(text.get()));
GOwnPtr<gchar> axValue(g_strdup_printf("AXValue: %s", textWithReplacedCharacters.get()));
return JSStringCreateWithUTF8CString(axValue.get());
}
| 170,899
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void set_roi_map(const vpx_codec_enc_cfg_t *cfg,
vpx_codec_ctx_t *codec) {
unsigned int i;
vpx_roi_map_t roi = {0};
roi.rows = (cfg->g_h + 15) / 16;
roi.cols = (cfg->g_w + 15) / 16;
roi.delta_q[0] = 0;
roi.delta_q[1] = -2;
roi.delta_q[2] = -4;
roi.delta_q[3] = -6;
roi.delta_lf[0] = 0;
roi.delta_lf[1] = 1;
roi.delta_lf[2] = 2;
roi.delta_lf[3] = 3;
roi.static_threshold[0] = 1500;
roi.static_threshold[1] = 1000;
roi.static_threshold[2] = 500;
roi.static_threshold[3] = 0;
roi.roi_map = (uint8_t *)malloc(roi.rows * roi.cols);
for (i = 0; i < roi.rows * roi.cols; ++i)
roi.roi_map[i] = i % 4;
if (vpx_codec_control(codec, VP8E_SET_ROI_MAP, &roi))
die_codec(codec, "Failed to set ROI map");
free(roi.roi_map);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
static void set_roi_map(const vpx_codec_enc_cfg_t *cfg,
vpx_codec_ctx_t *codec) {
unsigned int i;
vpx_roi_map_t roi;
memset(&roi, 0, sizeof(roi));
roi.rows = (cfg->g_h + 15) / 16;
roi.cols = (cfg->g_w + 15) / 16;
roi.delta_q[0] = 0;
roi.delta_q[1] = -2;
roi.delta_q[2] = -4;
roi.delta_q[3] = -6;
roi.delta_lf[0] = 0;
roi.delta_lf[1] = 1;
roi.delta_lf[2] = 2;
roi.delta_lf[3] = 3;
roi.static_threshold[0] = 1500;
roi.static_threshold[1] = 1000;
roi.static_threshold[2] = 500;
roi.static_threshold[3] = 0;
roi.roi_map = (uint8_t *)malloc(roi.rows * roi.cols);
for (i = 0; i < roi.rows * roi.cols; ++i)
roi.roi_map[i] = i % 4;
if (vpx_codec_control(codec, VP8E_SET_ROI_MAP, &roi))
die_codec(codec, "Failed to set ROI map");
free(roi.roi_map);
}
| 174,484
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tag_name,
Document& document)
: HTMLElement(tag_name, document),
content_frame_(nullptr),
embedded_content_view_(nullptr),
sandbox_flags_(kSandboxNone) {}
Commit Message: Resource Timing: Do not report subsequent navigations within subframes
We only want to record resource timing for the load that was initiated
by parent document. We filter out subsequent navigations for <iframe>,
but we should do it for other types of subframes too.
Bug: 780312
Change-Id: I3a7b9e1a365c99e24bb8dac190e88c7099fc3da5
Reviewed-on: https://chromium-review.googlesource.com/750487
Reviewed-by: Nate Chapin <japhet@chromium.org>
Commit-Queue: Kunihiko Sakamoto <ksakamoto@chromium.org>
Cr-Commit-Position: refs/heads/master@{#513665}
CWE ID: CWE-601
|
HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tag_name,
Document& document)
: HTMLElement(tag_name, document),
content_frame_(nullptr),
embedded_content_view_(nullptr),
| 172,928
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() {
progress_event_timer_.Stop();
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress())
ScheduleEvent(EventTypeNames::progress);
ScheduleEvent(EventTypeNames::suspend);
SetNetworkState(kNetworkIdle);
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <mlamouri@chromium.org>
Reviewed-by: Dale Curtis <dalecurtis@chromium.org>
Commit-Queue: Fredrik Hubinette <hubbe@chromium.org>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
|
void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() {
progress_event_timer_.Stop();
if (!MediaShouldBeOpaque()) {
// Schedule one last progress event so we guarantee that at least one is
// fired for files that load very quickly.
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress())
ScheduleEvent(EventTypeNames::progress);
ScheduleEvent(EventTypeNames::suspend);
SetNetworkState(kNetworkIdle);
}
}
| 173,161
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Tracks::Tracks(
Segment* pSegment,
long long start,
long long size_,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_start(start),
m_size(size_),
m_element_start(element_start),
m_element_size(element_size),
m_trackEntries(NULL),
m_trackEntriesEnd(NULL)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Tracks::Tracks(
| 174,446
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long Cluster::GetFirst(const BlockEntry*& pFirst) const
{
if (m_entries_count <= 0)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pFirst = NULL;
return status;
}
if (m_entries_count <= 0) //empty cluster
{
pFirst = NULL;
return 0;
}
}
assert(m_entries);
pFirst = m_entries[0];
assert(pFirst);
return 0; //success
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long Cluster::GetFirst(const BlockEntry*& pFirst) const
| 174,320
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo,
int PNG_CONST bdhi)
{
for (; bdlo <= bdhi; ++bdlo)
{
png_uint_32 width;
for (width = 1; width <= 16; ++width)
{
png_uint_32 height;
for (height = 1; height <= 16; ++height)
{
/* The four combinations of DIY interlace and interlace or not -
* no interlace + DIY should be identical to no interlace with
* libpng doing it.
*/
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
width, height, 0);
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
width, height, 1);
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
width, height, 0);
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
width, height, 1);
# endif
}
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo,
make_size(png_store* const ps, png_byte const colour_type, int bdlo,
int const bdhi)
{
for (; bdlo <= bdhi; ++bdlo)
{
png_uint_32 width;
for (width = 1; width <= 16; ++width)
{
png_uint_32 height;
for (height = 1; height <= 16; ++height)
{
/* The four combinations of DIY interlace and interlace or not -
* no interlace + DIY should be identical to no interlace with
* libpng doing it.
*/
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
width, height, 0);
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
width, height, 1);
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
width, height, 0);
# endif
# if CAN_WRITE_INTERLACE
/* 1.7.0 removes the hack that prevented app write of an interlaced
* image if WRITE_INTERLACE was not supported
*/
make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
width, height, 1);
# endif
}
}
}
}
| 173,663
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
{
int i, length;
segment->nb_index_entries = avio_rb32(pb);
length = avio_rb32(pb);
if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
!(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
!(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) {
av_freep(&segment->temporal_offset_entries);
av_freep(&segment->flag_entries);
return AVERROR(ENOMEM);
}
for (i = 0; i < segment->nb_index_entries; i++) {
segment->temporal_offset_entries[i] = avio_r8(pb);
avio_r8(pb); /* KeyFrameOffset */
segment->flag_entries[i] = avio_r8(pb);
segment->stream_offset_entries[i] = avio_rb64(pb);
avio_skip(pb, length - 11);
}
return 0;
}
Commit Message: avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array()
Fixes: 20170829A.mxf
Co-Author: 张洪亮(望初)" <wangchu.zhl@alibaba-inc.com>
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-834
|
static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
{
int i, length;
segment->nb_index_entries = avio_rb32(pb);
length = avio_rb32(pb);
if(segment->nb_index_entries && length < 11)
return AVERROR_INVALIDDATA;
if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
!(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
!(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) {
av_freep(&segment->temporal_offset_entries);
av_freep(&segment->flag_entries);
return AVERROR(ENOMEM);
}
for (i = 0; i < segment->nb_index_entries; i++) {
if(avio_feof(pb))
return AVERROR_INVALIDDATA;
segment->temporal_offset_entries[i] = avio_r8(pb);
avio_r8(pb); /* KeyFrameOffset */
segment->flag_entries[i] = avio_r8(pb);
segment->stream_offset_entries[i] = avio_rb64(pb);
avio_skip(pb, length - 11);
}
return 0;
}
| 167,765
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle,
TALLOC_CTX *ctx, const char *src, size_t n)
{
size_t size=0;
char *dest;
if (!src) {
return NULL;
}
/* this takes advantage of the fact that upper/lower can't
change the length of a character by more than 1 byte */
dest = talloc_array(ctx, char, 2*(n+1));
if (dest == NULL) {
return NULL;
}
while (n-- && *src) {
size_t c_size;
codepoint_t c = next_codepoint_handle(iconv_handle, src, &c_size);
src += c_size;
c = toupper_m(c);
c_size = push_codepoint_handle(iconv_handle, dest+size, c);
if (c_size == -1) {
talloc_free(dest);
return NULL;
}
size += c_size;
}
dest[size] = 0;
/* trim it so talloc_append_string() works */
dest = talloc_realloc(ctx, dest, char, size+1);
talloc_set_name_const(dest, dest);
return dest;
}
Commit Message:
CWE ID: CWE-200
|
_PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle,
TALLOC_CTX *ctx, const char *src, size_t n)
{
size_t size=0;
char *dest;
if (!src) {
return NULL;
}
/* this takes advantage of the fact that upper/lower can't
change the length of a character by more than 1 byte */
dest = talloc_array(ctx, char, 2*(n+1));
if (dest == NULL) {
return NULL;
}
while (n-- && *src) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n,
CH_UNIX, &c_size);
src += c_size;
c = toupper_m(c);
c_size = push_codepoint_handle(iconv_handle, dest+size, c);
if (c_size == -1) {
talloc_free(dest);
return NULL;
}
size += c_size;
}
dest[size] = 0;
/* trim it so talloc_append_string() works */
dest = talloc_realloc(ctx, dest, char, size+1);
talloc_set_name_const(dest, dest);
return dest;
}
| 164,672
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: RGBA32 AXNodeObject::colorValue() const {
if (!isHTMLInputElement(getNode()) || !isColorWell())
return AXObject::colorValue();
HTMLInputElement* input = toHTMLInputElement(getNode());
const AtomicString& type = input->getAttribute(typeAttr);
if (!equalIgnoringCase(type, "color"))
return AXObject::colorValue();
Color color;
bool success = color.setFromString(input->value());
DCHECK(success);
return color.rgb();
}
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
|
RGBA32 AXNodeObject::colorValue() const {
if (!isHTMLInputElement(getNode()) || !isColorWell())
return AXObject::colorValue();
HTMLInputElement* input = toHTMLInputElement(getNode());
const AtomicString& type = input->getAttribute(typeAttr);
if (!equalIgnoringASCIICase(type, "color"))
return AXObject::colorValue();
Color color;
bool success = color.setFromString(input->value());
DCHECK(success);
return color.rgb();
}
| 171,910
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files,
rpmpsm psm, int nodigest, int *setmeta,
int * firsthardlink)
{
int rc = 0;
int numHardlinks = rpmfiFNlink(fi);
if (numHardlinks > 1) {
/* Create first hardlinked file empty */
if (*firsthardlink < 0) {
*firsthardlink = rpmfiFX(fi);
rc = expandRegular(fi, dest, psm, nodigest, 1);
} else {
/* Create hard links for others */
char *fn = rpmfilesFN(files, *firsthardlink);
rc = link(fn, dest);
if (rc < 0) {
rc = RPMERR_LINK_FAILED;
}
free(fn);
}
}
/* Write normal files or fill the last hardlinked (already
existing) file with content */
if (numHardlinks<=1) {
if (!rc)
rc = expandRegular(fi, dest, psm, nodigest, 0);
} else if (rpmfiArchiveHasContent(fi)) {
if (!rc)
rc = expandRegular(fi, dest, psm, nodigest, 0);
*firsthardlink = -1;
} else {
*setmeta = 0;
}
return rc;
}
Commit Message: Don't follow symlinks on file creation (CVE-2017-7501)
Open newly created files with O_EXCL to prevent symlink tricks.
When reopening hardlinks for writing the actual content, use append
mode instead. This is compatible with the write-only permissions but
is not destructive in case we got redirected to somebody elses file,
verify the target before actually writing anything.
As these are files with the temporary suffix, errors mean a local
user with sufficient privileges to break the installation of the package
anyway is trying to goof us on purpose, don't bother trying to mend it
(we couldn't fix the hardlink case anyhow) but just bail out.
Based on a patch by Florian Festi.
CWE ID: CWE-59
|
static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files,
rpmpsm psm, int nodigest, int *setmeta,
int * firsthardlink)
{
int rc = 0;
int numHardlinks = rpmfiFNlink(fi);
if (numHardlinks > 1) {
/* Create first hardlinked file empty */
if (*firsthardlink < 0) {
*firsthardlink = rpmfiFX(fi);
rc = expandRegular(fi, dest, psm, 1, nodigest, 1);
} else {
/* Create hard links for others */
char *fn = rpmfilesFN(files, *firsthardlink);
rc = link(fn, dest);
if (rc < 0) {
rc = RPMERR_LINK_FAILED;
}
free(fn);
}
}
/* Write normal files or fill the last hardlinked (already
existing) file with content */
if (numHardlinks<=1) {
if (!rc)
rc = expandRegular(fi, dest, psm, 1, nodigest, 0);
} else if (rpmfiArchiveHasContent(fi)) {
if (!rc)
rc = expandRegular(fi, dest, psm, 0, nodigest, 0);
*firsthardlink = -1;
} else {
*setmeta = 0;
}
return rc;
}
| 168,268
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data)
{
HashAndString *data = (HashAndString*) user_data;
gchar *in = (gchar*) val;
g_hash_table_insert (data->hash, g_strdup ((gchar*) key),
g_strjoin (" ", data->string, in, NULL));
}
Commit Message:
CWE ID: CWE-264
|
hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data)
| 165,086
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message: Moved EOF check.
CWE ID: CWE-20
|
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 170,154
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PlatformNotificationData ToPlatformNotificationData(
const WebNotificationData& web_data) {
PlatformNotificationData platform_data;
platform_data.title = web_data.title;
switch (web_data.direction) {
case WebNotificationData::DirectionLeftToRight:
platform_data.direction =
PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT;
break;
case WebNotificationData::DirectionRightToLeft:
platform_data.direction =
PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT;
break;
case WebNotificationData::DirectionAuto:
platform_data.direction = PlatformNotificationData::DIRECTION_AUTO;
break;
}
platform_data.lang = base::UTF16ToUTF8(base::StringPiece16(web_data.lang));
platform_data.body = web_data.body;
platform_data.tag = base::UTF16ToUTF8(base::StringPiece16(web_data.tag));
platform_data.icon = blink::WebStringToGURL(web_data.icon.string());
platform_data.vibration_pattern.assign(web_data.vibrate.begin(),
web_data.vibrate.end());
platform_data.timestamp = base::Time::FromJsTime(web_data.timestamp);
platform_data.silent = web_data.silent;
platform_data.require_interaction = web_data.requireInteraction;
platform_data.data.assign(web_data.data.begin(), web_data.data.end());
platform_data.actions.resize(web_data.actions.size());
for (size_t i = 0; i < web_data.actions.size(); ++i) {
platform_data.actions[i].action =
base::UTF16ToUTF8(base::StringPiece16(web_data.actions[i].action));
platform_data.actions[i].title = web_data.actions[i].title;
}
return platform_data;
}
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:
|
PlatformNotificationData ToPlatformNotificationData(
const WebNotificationData& web_data) {
PlatformNotificationData platform_data;
platform_data.title = web_data.title;
switch (web_data.direction) {
case WebNotificationData::DirectionLeftToRight:
platform_data.direction =
PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT;
break;
case WebNotificationData::DirectionRightToLeft:
platform_data.direction =
PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT;
break;
case WebNotificationData::DirectionAuto:
platform_data.direction = PlatformNotificationData::DIRECTION_AUTO;
break;
}
platform_data.lang = base::UTF16ToUTF8(base::StringPiece16(web_data.lang));
platform_data.body = web_data.body;
platform_data.tag = base::UTF16ToUTF8(base::StringPiece16(web_data.tag));
platform_data.icon = blink::WebStringToGURL(web_data.icon.string());
platform_data.vibration_pattern.assign(web_data.vibrate.begin(),
web_data.vibrate.end());
platform_data.timestamp = base::Time::FromJsTime(web_data.timestamp);
platform_data.silent = web_data.silent;
platform_data.require_interaction = web_data.requireInteraction;
platform_data.data.assign(web_data.data.begin(), web_data.data.end());
platform_data.actions.resize(web_data.actions.size());
for (size_t i = 0; i < web_data.actions.size(); ++i) {
platform_data.actions[i].action =
base::UTF16ToUTF8(base::StringPiece16(web_data.actions[i].action));
platform_data.actions[i].title = web_data.actions[i].title;
platform_data.actions[i].icon =
blink::WebStringToGURL(web_data.actions[i].icon.string());
}
return platform_data;
}
| 171,631
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int search_old_relocation(struct reloc_struct_t *reloc_table, ut32 addr_to_patch, int n_reloc) {
int i;
for (i = 0; i < n_reloc; i++) {
if (addr_to_patch == reloc_table[i].data_offset) {
return i;
}
}
return -1;
}
Commit Message: Fix #6829 oob write because of using wrong struct
CWE ID: CWE-119
|
static int search_old_relocation(struct reloc_struct_t *reloc_table, ut32 addr_to_patch, int n_reloc) {
static int search_old_relocation (struct reloc_struct_t *reloc_table,
ut32 addr_to_patch, int n_reloc) {
int i;
for (i = 0; i < n_reloc; i++) {
if (addr_to_patch == reloc_table[i].data_offset) {
return i;
}
}
return -1;
}
| 168,365
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PepperDeviceEnumerationHostHelperTest()
: ppapi_host_(&sink_, ppapi::PpapiPermissions()),
resource_host_(&ppapi_host_, 12345, 67890),
device_enumeration_(&resource_host_,
&delegate_,
PP_DEVICETYPE_DEV_AUDIOCAPTURE,
GURL("http://example.com")) {}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399
|
PepperDeviceEnumerationHostHelperTest()
: ppapi_host_(&sink_, ppapi::PpapiPermissions()),
resource_host_(&ppapi_host_, 12345, 67890),
device_enumeration_(&resource_host_,
delegate_.AsWeakPtr(),
PP_DEVICETYPE_DEV_AUDIOCAPTURE,
GURL("http://example.com")) {}
| 171,607
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cJSON *cJSON_CreateString( const char *string )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_String;
item->valuestring = cJSON_strdup( string );
}
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <bmah@es.net>
CWE ID: CWE-119
|
cJSON *cJSON_CreateString( const char *string )
| 167,278
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ExtensionTtsController::SpeakNow(Utterance* utterance) {
std::string extension_id = GetMatchingExtensionId(utterance);
if (!extension_id.empty()) {
current_utterance_ = utterance;
utterance->set_extension_id(extension_id);
ListValue args;
args.Set(0, Value::CreateStringValue(utterance->text()));
DictionaryValue* options = static_cast<DictionaryValue*>(
utterance->options()->DeepCopy());
if (options->HasKey(util::kEnqueueKey))
options->Remove(util::kEnqueueKey, NULL);
args.Set(1, options);
args.Set(2, Value::CreateIntegerValue(utterance->id()));
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
utterance->profile()->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id,
events::kOnSpeak,
json_args,
utterance->profile(),
GURL());
return;
}
GetPlatformImpl()->clear_error();
bool success = GetPlatformImpl()->Speak(
utterance->text(),
utterance->locale(),
utterance->gender(),
utterance->rate(),
utterance->pitch(),
utterance->volume());
if (!success) {
utterance->set_error(GetPlatformImpl()->error());
utterance->FinishAndDestroy();
return;
}
current_utterance_ = utterance;
CheckSpeechStatus();
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void ExtensionTtsController::SpeakNow(Utterance* utterance) {
}
double pitch = 1.0;
if (options->HasKey(constants::kPitchKey)) {
EXTENSION_FUNCTION_VALIDATE(
options->GetDouble(constants::kPitchKey, &pitch));
if (pitch < 0.0 || pitch > 2.0) {
error_ = constants::kErrorInvalidPitch;
return false;
}
}
| 170,388
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
do {
entry = entry->next();
} while (entry != lru_list_.end() && entry->value()->parent() == to_doom);
if (!to_doom->InUse())
to_doom->Doom();
}
}
Commit Message: [MemCache] Fix bug while iterating LRU list in range doom
This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919
but on explicit mass-erase rather than eviction.
Thanks to nedwilliamson@ (on gmail) for the report and testcase.
Bug: 831963
Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102
Reviewed-on: https://chromium-review.googlesource.com/1014023
Commit-Queue: Maks Orlovich <morlovich@chromium.org>
Reviewed-by: Josh Karlin <jkarlin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#551205}
CWE ID: CWE-416
|
void MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
entry = NextSkippingChildren(lru_list_, entry);
if (!to_doom->InUse())
to_doom->Doom();
}
}
| 173,258
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
| 167,795
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DownloadController::OnDownloadStarted(
DownloadItem* download_item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = download_item->GetWebContents();
if (!web_contents)
return;
download_item->AddObserver(this);
ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted(
download_item->GetTargetFilePath().BaseName().value(),
download_item->GetMimeType());
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254
|
void DownloadController::OnDownloadStarted(
DownloadItem* download_item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = download_item->GetWebContents();
if (!web_contents)
return;
download_item->AddObserver(this);
ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted(
download_item->GetTargetFilePath().BaseName().value());
}
| 171,882
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_get_val (MyObject *obj, guint *ret, GError **error)
{
*ret = obj->val;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_get_val (MyObject *obj, guint *ret, GError **error)
| 165,103
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: vips_malloc( VipsObject *object, size_t size )
{
void *buf;
buf = g_malloc( size );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), buf );
object->local_memory += size;
}
return( buf );
}
Commit Message: zero memory on malloc
to prevent write of uninit memory under some error conditions
thanks Balint
CWE ID: CWE-200
|
vips_malloc( VipsObject *object, size_t size )
{
void *buf;
buf = g_malloc0( size );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), buf );
object->local_memory += size;
}
return( buf );
}
| 169,739
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: unsigned long Segment::GetCount() const
{
return m_clusterCount;
}
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
|
unsigned long Segment::GetCount() const
| 174,299
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BluetoothDeviceChromeOS::OnRegisterAgent(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Agent registered, now pairing";
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
Pair(object_path_,
base::Bind(&BluetoothDeviceChromeOS::OnPair,
weak_ptr_factory_.GetWeakPtr(),
callback, error_callback),
base::Bind(&BluetoothDeviceChromeOS::OnPairError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BluetoothDeviceChromeOS::OnRegisterAgent(
| 171,229
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck(
const KURL& current_src) {
DCHECK(IsMainThread());
return Context()->GetSecurityOrigin() &&
Context()->GetSecurityOrigin()->CanRequest(current_src);
}
Commit Message: Redirect should not circumvent same-origin restrictions
Check whether we have access to the audio data when the format is set.
At this point we have enough information to determine this. The old approach
based on when the src was changed was incorrect because at the point, we
only know the new src; none of the response headers have been read yet.
This new approach also removes the incorrect message reported in 619114.
Bug: 826552, 619114
Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6
Reviewed-on: https://chromium-review.googlesource.com/1069540
Commit-Queue: Raymond Toy <rtoy@chromium.org>
Reviewed-by: Yutaka Hirano <yhirano@chromium.org>
Reviewed-by: Hongchan Choi <hongchan@chromium.org>
Cr-Commit-Position: refs/heads/master@{#564313}
CWE ID: CWE-20
|
bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck(
// Test to see if the current media URL taint the origin of the audio context?
return Context()->WouldTaintOrigin(MediaElement()->currentSrc());
}
| 173,148
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b)
{
return (b[0]<<8) | b[1];
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682
|
IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b)
{
return ((unsigned int)b[0]<<8) | (unsigned int)b[1];
}
| 168,197
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: validate_T(void)
/* Validate the above table - this just builds the above values */
{
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i)
{
if (transform_info[i].when & TRANSFORM_R)
read_transforms |= transform_info[i].transform;
if (transform_info[i].when & TRANSFORM_W)
write_transforms |= transform_info[i].transform;
}
/* Reversible transforms are those which are supported on both read and
* write.
*/
rw_transforms = read_transforms & write_transforms;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
validate_T(void)
/* Validate the above table - this just builds the above values */
{
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i) if (transform_info[i].name != NULL)
{
if (transform_info[i].when & TRANSFORM_R)
read_transforms |= transform_info[i].transform;
if (transform_info[i].when & TRANSFORM_W)
write_transforms |= transform_info[i].transform;
}
/* Reversible transforms are those which are supported on both read and
* write.
*/
rw_transforms = read_transforms & write_transforms;
}
| 173,592
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: BlockGroup::BlockGroup(
Cluster* pCluster,
long idx,
long long block_start,
long long block_size,
long long prev,
long long next,
long long duration,
long long discard_padding) :
BlockEntry(pCluster, idx),
m_block(block_start, block_size, discard_padding),
m_prev(prev),
m_next(next),
m_duration(duration)
{
}
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
|
BlockGroup::BlockGroup(
| 174,242
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: chunk_grow(chunk_t *chunk, size_t sz)
{
off_t offset;
size_t memlen_orig = chunk->memlen;
tor_assert(sz > chunk->memlen);
offset = chunk->data - chunk->mem;
chunk = tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz));
chunk->memlen = sz;
chunk->data = chunk->mem + offset;
#ifdef DEBUG_CHUNK_ALLOC
tor_assert(chunk->DBG_alloc == CHUNK_ALLOC_SIZE(memlen_orig));
chunk->DBG_alloc = CHUNK_ALLOC_SIZE(sz);
#endif
total_bytes_allocated_in_chunks +=
CHUNK_ALLOC_SIZE(sz) - CHUNK_ALLOC_SIZE(memlen_orig);
return chunk;
}
Commit Message: Add a one-word sentinel value of 0x0 at the end of each buf_t chunk
This helps protect against bugs where any part of a buf_t's memory
is passed to a function that expects a NUL-terminated input.
It also closes TROVE-2016-10-001 (aka bug 20384).
CWE ID: CWE-119
|
chunk_grow(chunk_t *chunk, size_t sz)
{
off_t offset;
const size_t memlen_orig = chunk->memlen;
const size_t orig_alloc = CHUNK_ALLOC_SIZE(memlen_orig);
const size_t new_alloc = CHUNK_ALLOC_SIZE(sz);
tor_assert(sz > chunk->memlen);
offset = chunk->data - chunk->mem;
chunk = tor_realloc(chunk, new_alloc);
chunk->memlen = sz;
chunk->data = chunk->mem + offset;
#ifdef DEBUG_CHUNK_ALLOC
tor_assert(chunk->DBG_alloc == orig_alloc);
chunk->DBG_alloc = new_alloc;
#endif
total_bytes_allocated_in_chunks += new_alloc - orig_alloc;
CHUNK_SET_SENTINEL(chunk, new_alloc);
return chunk;
}
| 168,757
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
WebContentsImpl* old_contents = GetFocusedWebContents();
if (old_contents == this)
return;
GetOutermostWebContents()->node_.SetFocusedWebContents(this);
if (!GuestMode::IsCrossProcessFrameGuest(this) && browser_plugin_guest_)
return;
if (old_contents)
old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
if (GetRenderManager()->GetProxyToOuterDelegate())
GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
if (ShowingInterstitialPage()) {
static_cast<RenderFrameHostImpl*>(
GetRenderManager()->interstitial_page()->GetMainFrame())
->GetRenderWidgetHost()
->SetPageFocus(true);
} else {
GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
}
}
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
|
void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
WebContentsImpl* old_contents = GetFocusedWebContents();
if (old_contents == this)
return;
GetOutermostWebContents()->node_.SetFocusedWebContents(this);
if (!GuestMode::IsCrossProcessFrameGuest(this) && browser_plugin_guest_)
return;
if (old_contents)
old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
if (GetRenderManager()->GetProxyToOuterDelegate())
GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
if (ShowingInterstitialPage()) {
static_cast<RenderFrameHostImpl*>(interstitial_page_->GetMainFrame())
->GetRenderWidgetHost()
->SetPageFocus(true);
} else {
GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
}
}
| 172,333
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: std::unique_ptr<net::test_server::HttpResponse> GetConfigResponse(
const net::test_server::HttpRequest& request) {
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_content(config_.SerializeAsString());
response->set_content_type("text/plain");
if (config_run_loop_)
config_run_loop_->Quit();
return response;
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <tbansal@chromium.org>
Reviewed-by: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416
|
std::unique_ptr<net::test_server::HttpResponse> GetConfigResponse(
const net::test_server::HttpRequest& request) {
// Config should not be fetched when in holdback.
EXPECT_FALSE(
data_reduction_proxy::params::IsIncludedInHoldbackFieldTrial());
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_content(config_.SerializeAsString());
response->set_content_type("text/plain");
if (config_run_loop_)
config_run_loop_->Quit();
return response;
}
| 172,414
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
|
static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,954
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <sdy@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20
|
void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
#if defined(OS_MACOSX)
// On the Mac, the convention is to turn popups into new tabs when in
// fullscreen mode. Only worry about user-initiated fullscreen as showing a
// popup in HTML5 fullscreen would have kicked the page out of fullscreen.
if (disposition == WindowOpenDisposition::NEW_POPUP &&
exclusive_access_manager_->fullscreen_controller()
->IsFullscreenForBrowser()) {
disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
#endif
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
| 173,205
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg)
{
__be32 *p;
RESERVE_SPACE(4+NFS4_STATEID_SIZE+4);
WRITE32(OP_OPEN_DOWNGRADE);
WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->open_flags);
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg)
{
__be32 *p;
RESERVE_SPACE(4+NFS4_STATEID_SIZE+4);
WRITE32(OP_OPEN_DOWNGRADE);
WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->fmode);
return 0;
}
| 165,713
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void *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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_,
proto_tree *tree, guint8 *drep _U_, char **data,
int hf_name)
{
gint len, remaining;
char *text;
if (offset % 2)
offset += 2 - (offset % 2);
/* Get remaining data in buffer as a string */
remaining = tvb_captured_length_remaining(tvb, offset);
if (remaining <= 0) {
if (data)
*data = g_strdup("");
return offset;
}
text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN);
len = (int)strlen(text);
proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text);
if (data)
*data = text;
else
g_free(text);
return offset + (len + 1) * 2;
}
Commit Message: SPOOLSS: Try to avoid an infinite loop.
Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make
sure our offset always increments in dissect_spoolss_keybuffer.
Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793
Reviewed-on: https://code.wireshark.org/review/14687
Reviewed-by: Gerald Combs <gerald@wireshark.org>
Petri-Dish: Gerald Combs <gerald@wireshark.org>
Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org>
Reviewed-by: Michael Mann <mmann78@netscape.net>
CWE ID: CWE-399
|
dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_,
proto_tree *tree, guint8 *drep _U_, char **data,
int hf_name)
{
gint len, remaining;
char *text;
if (offset % 2)
offset += 2 - (offset % 2);
/* Get remaining data in buffer as a string */
remaining = tvb_reported_length_remaining(tvb, offset);
if (remaining <= 0) {
if (data)
*data = g_strdup("");
return offset;
}
text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN);
len = (int)strlen(text);
proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text);
if (data)
*data = text;
else
g_free(text);
return offset + (len + 1) * 2;
}
| 167,160
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
}
Commit Message: avcodec/mpeg4videodec: Check for bitstream end in read_quant_matrix_ext()
Fixes: out of array read
Fixes: asff-crash-0e53d0dc491dfdd507530b66562812fbd4c36678
Found-by: Paul Ch <paulcher@icloud.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-125
|
static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
return 0;
}
| 168,922
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: hash_foreach_stringify (gpointer key, gpointer val, gpointer user_data)
{
const char *keystr = key;
const GValue *value = val;
GValue *sval;
GHashTable *ret = user_data;
sval = g_new0 (GValue, 1);
g_value_init (sval, G_TYPE_STRING);
if (!g_value_transform (value, sval))
g_assert_not_reached ();
g_hash_table_insert (ret, g_strdup (keystr), sval);
}
Commit Message:
CWE ID: CWE-264
|
hash_foreach_stringify (gpointer key, gpointer val, gpointer user_data)
| 165,087
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObject* proxyImp = V8TestObject::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
R=jochen@chromium.org
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObject* proxyImp = V8TestObject::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
| 171,684
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ExtensionResourceRequestPolicy::CanRequestResource(
const GURL& resource_url,
const GURL& frame_url,
const ExtensionSet* loaded_extensions) {
CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));
const Extension* extension =
loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url));
if (!extension) {
return true;
}
std::string resource_root_relative_path =
resource_url.path().empty() ? "" : resource_url.path().substr(1);
if (extension->is_hosted_app() &&
!extension->icons().ContainsPath(resource_root_relative_path)) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " from "
<< "hosted app.";
return false;
}
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableExtensionsResourceWhitelist) &&
!frame_url.is_empty() &&
!frame_url.SchemeIs(chrome::kExtensionScheme) &&
!extension->IsResourceWebAccessible(resource_url.path())) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " which "
<< "is not a web accessible resource.";
return false;
}
return true;
}
Commit Message: Do not require DevTools extension resources to be white-listed in manifest.
Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is
(a) trusted and
(b) picky on the frames it loads.
This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check.
BUG=none
TEST=DevToolsExtensionTest.*
Review URL: https://chromiumcodereview.appspot.com/9663076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
bool ExtensionResourceRequestPolicy::CanRequestResource(
const GURL& resource_url,
const WebKit::WebFrame* frame,
const ExtensionSet* loaded_extensions) {
CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));
const Extension* extension =
loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url));
if (!extension) {
return true;
}
std::string resource_root_relative_path =
resource_url.path().empty() ? "" : resource_url.path().substr(1);
if (extension->is_hosted_app() &&
!extension->icons().ContainsPath(resource_root_relative_path)) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " from "
<< "hosted app.";
return false;
}
GURL frame_url = frame->document().url();
GURL page_url = frame->top()->document().url();
// - devtools (chrome-extension:// URLs are loaded into frames of devtools
// to support the devtools extension APIs)
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableExtensionsResourceWhitelist) &&
!frame_url.is_empty() &&
!frame_url.SchemeIs(chrome::kExtensionScheme) &&
!(page_url.SchemeIs(chrome::kChromeDevToolsScheme) &&
!extension->devtools_url().is_empty()) &&
!extension->IsResourceWebAccessible(resource_url.path())) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " which "
<< "is not a web accessible resource.";
return false;
}
return true;
}
| 171,001
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update)
{
EAS_U32 endPhaseAccum;
EAS_U32 endPhaseFrac;
EAS_I32 numSamples;
EAS_BOOL done = EAS_FALSE;
/* check to see if we hit the end of the waveform this time */
/*lint -e{703} use shift for performance */
endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS);
endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac);
if (endPhaseAccum >= pWTVoice->loopEnd)
{
/* calculate how far current ptr is from end */
numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum);
/* now account for the fractional portion */
/*lint -e{703} use shift for performance */
numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac);
if (pWTIntFrame->frame.phaseIncrement) {
pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement);
} else {
pWTIntFrame->numSamples = numSamples;
}
/* sound will be done this frame */
done = EAS_TRUE;
}
/* update data for off-chip synth */
if (update)
{
pWTVoice->phaseFrac = endPhaseFrac;
pWTVoice->phaseAccum = endPhaseAccum;
}
return done;
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
|
EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update)
{
EAS_U32 endPhaseAccum;
EAS_U32 endPhaseFrac;
EAS_I32 numSamples;
EAS_BOOL done = EAS_FALSE;
/* check to see if we hit the end of the waveform this time */
/*lint -e{703} use shift for performance */
endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS);
endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac);
if (endPhaseAccum >= pWTVoice->loopEnd)
{
/* calculate how far current ptr is from end */
numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum);
/* now account for the fractional portion */
/*lint -e{703} use shift for performance */
numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac);
if (pWTIntFrame->frame.phaseIncrement) {
pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement);
} else {
pWTIntFrame->numSamples = numSamples;
}
if (pWTIntFrame->numSamples < 0) {
ALOGE("b/26366256");
pWTIntFrame->numSamples = 0;
}
/* sound will be done this frame */
done = EAS_TRUE;
}
/* update data for off-chip synth */
if (update)
{
pWTVoice->phaseFrac = endPhaseFrac;
pWTVoice->phaseAccum = endPhaseAccum;
}
return done;
}
| 173,923
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void MemoryInstrumentation::GetVmRegionsForHeapProfiler(
RequestGlobalDumpCallback callback) {
const auto& coordinator = GetCoordinatorBindingForCurrentThread();
coordinator->GetVmRegionsForHeapProfiler(callback);
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <lalitm@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: oysteine <oysteine@chromium.org>
Reviewed-by: Albert J. Wong <ajwong@chromium.org>
Reviewed-by: Hector Dearman <hjd@chromium.org>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269
|
void MemoryInstrumentation::GetVmRegionsForHeapProfiler(
| 172,918
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p,
const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile)
{ /* i_ctx_p is NULL running arg (@) files.
* lib_path and mem are never NULL
*/
bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file;
bool search_with_no_combine = false;
bool search_with_combine = false;
char fmode[2] = { 'r', 0};
gx_io_device *iodev = iodev_default(mem);
gs_main_instance *minst = get_minst_from_memory(mem);
int code;
/* when starting arg files (@ files) iodev_default is not yet set */
if (iodev == 0)
iodev = (gx_io_device *)gx_io_device_table[0];
search_with_combine = false;
} else {
search_with_no_combine = starting_arg_file;
search_with_combine = true;
}
Commit Message:
CWE ID: CWE-200
|
lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p,
const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile)
{ /* i_ctx_p is NULL running arg (@) files.
* lib_path and mem are never NULL
*/
bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file;
bool search_with_no_combine = false;
bool search_with_combine = false;
char fmode[2] = { 'r', 0};
gx_io_device *iodev = iodev_default(mem);
gs_main_instance *minst = get_minst_from_memory(mem);
int code;
if (i_ctx_p && starting_arg_file)
i_ctx_p->starting_arg_file = false;
/* when starting arg files (@ files) iodev_default is not yet set */
if (iodev == 0)
iodev = (gx_io_device *)gx_io_device_table[0];
search_with_combine = false;
} else {
search_with_no_combine = starting_arg_file;
search_with_combine = true;
}
| 165,264
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t OMXNodeInstance::getConfig(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
status_t OMXNodeInstance::getConfig(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
| 174,134
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static ogg_uint32_t decpack(long entry,long used_entry,long quantvals,
codebook *b,oggpack_buffer *opb,int maptype){
ogg_uint32_t ret=0;
int j;
switch(b->dec_type){
case 0:
return (ogg_uint32_t)entry;
case 1:
if(maptype==1){
/* vals are already read into temporary column vector here */
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j);
}
}else{
for(j=0;j<b->dim;j++)
ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j);
}
return ret;
case 2:
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=off<<(b->q_pack*j);
}
return ret;
case 3:
return (ogg_uint32_t)used_entry;
}
return 0; /* silence compiler */
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200
|
static ogg_uint32_t decpack(long entry,long used_entry,long quantvals,
codebook *b,oggpack_buffer *opb,int maptype){
ogg_uint32_t ret=0;
int j;
switch(b->dec_type){
case 0:
return (ogg_uint32_t)entry;
case 1:
if(maptype==1){
/* vals are already read into temporary column vector here */
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j);
}
}else{
for(j=0;j<b->dim;j++)
ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j);
}
return ret;
case 2:
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=off<<(b->q_pack*j);
}
return ret;
case 3:
return (ogg_uint32_t)used_entry;
}
return 0; /* silence compiler */
}
| 173,985
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ImageBitmapFactories::Trace(blink::Visitor* visitor) {
visitor->Trace(pending_loaders_);
Supplement<LocalDOMWindow>::Trace(visitor);
Supplement<WorkerGlobalScope>::Trace(visitor);
}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Marijn Kruisselbrink <mek@chromium.org>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416
|
void ImageBitmapFactories::Trace(blink::Visitor* visitor) {
ImageBitmapFactories::ImageBitmapLoader::~ImageBitmapLoader() {
DCHECK(!loader_);
}
| 173,070
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int nntp_add_group(char *line, void *data)
{
struct NntpServer *nserv = data;
struct NntpData *nntp_data = NULL;
char group[LONG_STRING];
char desc[HUGE_STRING] = "";
char mod;
anum_t first, last;
if (!nserv || !line)
return 0;
if (sscanf(line, "%s " ANUM " " ANUM " %c %[^\n]", group, &last, &first, &mod, desc) < 4)
return 0;
nntp_data = nntp_data_find(nserv, group);
nntp_data->deleted = false;
nntp_data->first_message = first;
nntp_data->last_message = last;
nntp_data->allowed = (mod == 'y') || (mod == 'm');
mutt_str_replace(&nntp_data->desc, desc);
if (nntp_data->newsrc_ent || nntp_data->last_cached)
nntp_group_unread_stat(nntp_data);
else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message)
nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1;
else
nntp_data->unread = 0;
return 0;
}
Commit Message: Set length modifiers for group and desc
nntp_add_group parses a line controlled by the connected nntp server.
Restrict the maximum lengths read into the stack buffers group, and
desc.
CWE ID: CWE-119
|
int nntp_add_group(char *line, void *data)
{
struct NntpServer *nserv = data;
struct NntpData *nntp_data = NULL;
char group[LONG_STRING] = "";
char desc[HUGE_STRING] = "";
char mod;
anum_t first, last;
if (!nserv || !line)
return 0;
/* These sscanf limits must match the sizes of the group and desc arrays */
if (sscanf(line, "%1023s " ANUM " " ANUM " %c %8191[^\n]", group, &last, &first, &mod, desc) < 4)
{
mutt_debug(4, "Cannot parse server line: %s\n", line);
return 0;
}
nntp_data = nntp_data_find(nserv, group);
nntp_data->deleted = false;
nntp_data->first_message = first;
nntp_data->last_message = last;
nntp_data->allowed = (mod == 'y') || (mod == 'm');
mutt_str_replace(&nntp_data->desc, desc);
if (nntp_data->newsrc_ent || nntp_data->last_cached)
nntp_group_unread_stat(nntp_data);
else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message)
nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1;
else
nntp_data->unread = 0;
return 0;
}
| 169,125
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static char *pool_strdup(const char *s)
{
char *r = pool_alloc(strlen(s) + 1);
strcpy(r, s);
return r;
}
Commit Message: prefer memcpy to strcpy
When we already know the length of a string (e.g., because
we just malloc'd to fit it), it's nicer to use memcpy than
strcpy, as it makes it more obvious that we are not going to
overflow the buffer (because the size we pass matches the
size in the allocation).
This also eliminates calls to strcpy, which make auditing
the code base harder.
Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
CWE ID: CWE-119
|
static char *pool_strdup(const char *s)
{
size_t len = strlen(s) + 1;
char *r = pool_alloc(len);
memcpy(r, s, len);
return r;
}
| 167,428
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
int newUid, uid_t callerUid) {
ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
const int fd = socket.get();
struct stat info;
if (fstat(fd, &info)) {
return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
}
if (info.st_uid != callerUid) {
return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
}
if (S_ISSOCK(info.st_mode) == 0) {
return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
}
int optval;
socklen_t optlen;
netdutils::Status status =
getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
if (status != netdutils::status::ok) {
return status;
}
if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
}
if (fchown(fd, newUid, -1)) {
return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
}
return netdutils::status::ok;
}
Commit Message: Set optlen for UDP-encap check in XfrmController
When setting the socket owner for an encap socket XfrmController will
first attempt to verify that the socket has the UDP-encap socket option
set. When doing so it would pass in an uninitialized optlen parameter
which could cause the call to not modify the option value if the optlen
happened to be too short. So for example if the stack happened to
contain a zero where optlen was located the check would fail and the
socket owner would not be changed.
Fix this by setting optlen to the size of the option value parameter.
Test: run cts -m CtsNetTestCases
BUG: 111650288
Change-Id: I57b6e9dba09c1acda71e3ec2084652e961667bd9
(cherry picked from commit fc42a105147310bd680952d4b71fe32974bd8506)
CWE ID: CWE-909
|
netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
int newUid, uid_t callerUid) {
ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
const int fd = socket.get();
struct stat info;
if (fstat(fd, &info)) {
return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
}
if (info.st_uid != callerUid) {
return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
}
if (S_ISSOCK(info.st_mode) == 0) {
return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
}
int optval;
socklen_t optlen = sizeof(optval);
netdutils::Status status =
getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
if (status != netdutils::status::ok) {
return status;
}
if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
}
if (fchown(fd, newUid, -1)) {
return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
}
return netdutils::status::ok;
}
| 174,073
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long long Block::GetTrackNumber() const
{
return m_track;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Block::GetTrackNumber() const
bool Block::IsKey() const {
return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
}
| 174,372
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: StateBase* writeFileList(v8::Handle<v8::Value> value, StateBase* next)
{
FileList* fileList = V8FileList::toNative(value.As<v8::Object>());
if (!fileList)
return 0;
unsigned length = fileList->length();
Vector<int> blobIndices;
for (unsigned i = 0; i < length; ++i) {
int blobIndex = -1;
const File* file = fileList->item(i);
if (file->hasBeenClosed())
return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next);
m_blobDataHandles.add(file->uuid(), file->blobDataHandle());
if (appendFileInfo(file, &blobIndex)) {
ASSERT(!i || blobIndex > 0);
ASSERT(blobIndex >= 0);
blobIndices.append(blobIndex);
}
}
if (!blobIndices.isEmpty())
m_writer.writeFileListIndex(blobIndices);
else
m_writer.writeFileList(*fileList);
return 0;
}
Commit Message: Replace further questionable HashMap::add usages in bindings
BUG=390928
R=dcarney@chromium.org
Review URL: https://codereview.chromium.org/411273002
git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
StateBase* writeFileList(v8::Handle<v8::Value> value, StateBase* next)
{
FileList* fileList = V8FileList::toNative(value.As<v8::Object>());
if (!fileList)
return 0;
unsigned length = fileList->length();
Vector<int> blobIndices;
for (unsigned i = 0; i < length; ++i) {
int blobIndex = -1;
const File* file = fileList->item(i);
if (file->hasBeenClosed())
return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next);
m_blobDataHandles.set(file->uuid(), file->blobDataHandle());
if (appendFileInfo(file, &blobIndex)) {
ASSERT(!i || blobIndex > 0);
ASSERT(blobIndex >= 0);
blobIndices.append(blobIndex);
}
}
if (!blobIndices.isEmpty())
m_writer.writeFileListIndex(blobIndices);
else
m_writer.writeFileList(*fileList);
return 0;
}
| 171,652
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PluginChannel::OnChannelError() {
base::CloseProcessHandle(renderer_handle_);
renderer_handle_ = 0;
NPChannelBase::OnChannelError();
CleanUp();
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void PluginChannel::OnChannelError() {
NPChannelBase::OnChannelError();
CleanUp();
}
| 170,949
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]);
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j) {
input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_;
}
if (i == 0) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = mask_;
} else if (i == 1) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -mask_;
}
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
| 174,526
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin;
if (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) {
return NULL;
}
memset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t));
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new();
if (!r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
Commit Message: Fix #12374 - oobread crash in truncated dyldcache ##bin
CWE ID: CWE-125
|
struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin = R_NEW0 (struct r_bin_dyldcache_obj_t);
if (!bin) {
return NULL;
}
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new ();
if (!bin->b || !r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
| 168,955
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
bool store_print_pages_params = true;
if (result == FAIL_PRINT) {
DisplayPrintJobError();
if (notify_browser_of_print_failure_ && print_pages_params_.get()) {
int cookie = print_pages_params_->params.document_cookie;
Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
}
} else if (result == FAIL_PREVIEW) {
DCHECK(is_preview_);
store_print_pages_params = false;
int cookie = print_pages_params_->params.document_cookie;
if (notify_browser_of_print_failure_)
Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
else
Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
print_preview_context_.Failed(notify_browser_of_print_failure_);
}
if (print_web_view_) {
print_web_view_->close();
print_web_view_ = NULL;
}
if (store_print_pages_params) {
old_print_pages_params_.reset(print_pages_params_.release());
} else {
print_pages_params_.reset();
old_print_pages_params_.reset();
}
notify_browser_of_print_failure_ = true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
bool store_print_pages_params = true;
if (result == FAIL_PRINT) {
DisplayPrintJobError();
if (notify_browser_of_print_failure_ && print_pages_params_.get()) {
int cookie = print_pages_params_->params.document_cookie;
Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
}
} else if (result == FAIL_PREVIEW) {
DCHECK(is_preview_);
store_print_pages_params = false;
int cookie = print_pages_params_.get() ?
print_pages_params_->params.document_cookie : 0;
if (notify_browser_of_print_failure_)
Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
else
Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
print_preview_context_.Failed(notify_browser_of_print_failure_);
}
if (print_web_view_) {
print_web_view_->close();
print_web_view_ = NULL;
}
if (store_print_pages_params) {
old_print_pages_params_.reset(print_pages_params_.release());
} else {
print_pages_params_.reset();
old_print_pages_params_.reset();
}
notify_browser_of_print_failure_ = true;
}
| 170,258
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s)
{
asn1_write(data, s->data, s->length);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
|
bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s)
{
return asn1_write(data, s->data, s->length);
}
| 164,588
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void NavigateOnUIThread(
const GURL& url,
const std::vector<GURL> url_chain,
const Referrer& referrer,
bool has_user_gesture,
const ResourceRequestInfo::WebContentsGetter& wc_getter) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = wc_getter.Run();
if (web_contents) {
NavigationController::LoadURLParams params(url);
params.has_user_gesture = has_user_gesture;
params.referrer = referrer;
params.redirect_chain = url_chain;
web_contents->GetController().LoadURLWithParams(params);
}
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <japhet@chromium.org>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
|
void NavigateOnUIThread(
void NavigateOnUIThread(const GURL& url,
const std::vector<GURL> url_chain,
const Referrer& referrer,
bool has_user_gesture,
const ResourceRequestInfo::WebContentsGetter& wc_getter,
int frame_tree_node_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = wc_getter.Run();
if (web_contents) {
NavigationController::LoadURLParams params(url);
params.has_user_gesture = has_user_gesture;
params.referrer = referrer;
params.redirect_chain = url_chain;
params.frame_tree_node_id = frame_tree_node_id;
web_contents->GetController().LoadURLWithParams(params);
}
}
| 173,024
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: valid_length(uint8_t option, int dl, int *type)
{
const struct dhcp_opt *opt;
ssize_t sz;
if (dl == 0)
return -1;
for (opt = dhcp_opts; opt->option; opt++) {
if (opt->option != option)
continue;
if (type)
*type = opt->type;
if (opt->type == 0 ||
opt->type & (STRING | RFC3442 | RFC5969))
return 0;
sz = 0;
if (opt->type & (UINT32 | IPV4))
sz = sizeof(uint32_t);
if (opt->type & UINT16)
sz = sizeof(uint16_t);
if (opt->type & UINT8)
sz = sizeof(uint8_t);
if (opt->type & (IPV4 | ARRAY))
return dl % sz;
return (dl == sz ? 0 : -1);
}
/* unknown option, so let it pass */
return 0;
}
Commit Message: Improve length checks in DHCP Options parsing of dhcpcd.
Bug: 26461634
Change-Id: Ic4c2eb381a6819e181afc8ab13891f3fc58b7deb
CWE ID: CWE-119
|
valid_length(uint8_t option, int dl, int *type)
{
const struct dhcp_opt *opt;
ssize_t sz;
if (dl == 0)
return -1;
for (opt = dhcp_opts; opt->option; opt++) {
if (opt->option != option)
continue;
if (type)
*type = opt->type;
/* The size of RFC3442 and RFC5969 options is checked at a later
* stage in the code */
if (opt->type == 0 ||
opt->type & (STRING | RFC3442 | RFC5969))
return 0;
/* The code does not use SINT16 / SINT32 together with ARRAY.
* It is however far easier to reason about the code if all
* possible array elements are included, and also does not code
* any additional CPU resources. sizeof(uintXX_t) ==
* sizeof(intXX_t) can be assumed. */
sz = 0;
if (opt->type & (UINT32 | SINT32 | IPV4))
sz = sizeof(uint32_t);
else if (opt->type & (UINT16 | SINT16))
sz = sizeof(uint16_t);
else if (opt->type & UINT8)
sz = sizeof(uint8_t);
if (opt->type & ARRAY) {
/* The result of modulo zero is undefined. There are no
* options defined in this file that do not match one of
* the if-clauses above, so the following is not really
* necessary. However, to avoid confusion and unexpected
* behavior if the defined options are ever extended,
* returning false here seems sensible. */
if (!sz) return -1;
return (dl % sz == 0) ? 0 : -1;
}
return (sz == dl) ? 0 : -1;
}
/* unknown option, so let it pass */
return 0;
}
| 173,900
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void faad_resetbits(bitfile *ld, int bits)
{
uint32_t tmp;
int words = bits >> 5;
int remainder = bits & 0x1F;
ld->bytes_left = ld->buffer_size - words*4;
if (ld->bytes_left >= 4)
{
tmp = getdword(&ld->start[words]);
ld->bytes_left -= 4;
} else {
tmp = getdword_n(&ld->start[words], ld->bytes_left);
ld->bytes_left = 0;
}
ld->bufa = tmp;
if (ld->bytes_left >= 4)
{
tmp = getdword(&ld->start[words+1]);
ld->bytes_left -= 4;
} else {
tmp = getdword_n(&ld->start[words+1], ld->bytes_left);
ld->bytes_left = 0;
}
ld->bufb = tmp;
ld->bits_left = 32 - remainder;
ld->tail = &ld->start[words+2];
/* recheck for reading too many bytes */
ld->error = 0;
}
Commit Message: Fix a couple buffer overflows
https://hackerone.com/reports/502816
https://hackerone.com/reports/507858
https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch
CWE ID: CWE-119
|
void faad_resetbits(bitfile *ld, int bits)
{
uint32_t tmp;
int words = bits >> 5;
int remainder = bits & 0x1F;
if (ld->buffer_size < words * 4)
ld->bytes_left = 0;
else
ld->bytes_left = ld->buffer_size - words*4;
if (ld->bytes_left >= 4)
{
tmp = getdword(&ld->start[words]);
ld->bytes_left -= 4;
} else {
tmp = getdword_n(&ld->start[words], ld->bytes_left);
ld->bytes_left = 0;
}
ld->bufa = tmp;
if (ld->bytes_left >= 4)
{
tmp = getdword(&ld->start[words+1]);
ld->bytes_left -= 4;
} else {
tmp = getdword_n(&ld->start[words+1], ld->bytes_left);
ld->bytes_left = 0;
}
ld->bufb = tmp;
ld->bits_left = 32 - remainder;
ld->tail = &ld->start[words+2];
/* recheck for reading too many bytes */
ld->error = 0;
}
| 169,535
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: modifier_color_encoding_is_sRGB(PNG_CONST png_modifier *pm)
{
return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
pm->current_encoding->gamma == pm->current_gamma;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
modifier_color_encoding_is_sRGB(PNG_CONST png_modifier *pm)
modifier_color_encoding_is_sRGB(const png_modifier *pm)
{
return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
pm->current_encoding->gamma == pm->current_gamma;
}
| 173,667
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void php_mb_regex_free_cache(php_mb_regex_t **pre)
{
onig_free(*pre);
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
|
static void php_mb_regex_free_cache(php_mb_regex_t **pre)
static void php_mb_regex_free_cache(php_mb_regex_t **pre)
{
onig_free(*pre);
}
| 167,122
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n");
if (!CDROM_CAN(CDC_SELECT_DISC))
return -ENOSYS;
if (arg != CDSL_CURRENT && arg != CDSL_NONE) {
if ((int)arg >= cdi->capacity)
return -EINVAL;
}
/*
* ->select_disc is a hook to allow a driver-specific way of
* seleting disc. However, since there is no equivalent hook for
* cdrom_slot_status this may not actually be useful...
*/
if (cdi->ops->select_disc)
return cdi->ops->select_disc(cdi, arg);
cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n");
return cdrom_select_disc(cdi, arg);
}
Commit Message: cdrom: fix improper type cast, which can leat to information leak.
There is another cast from unsigned long to int which causes
a bounds check to fail with specially crafted input. The value is
then used as an index in the slot array in cdrom_slot_status().
This issue is similar to CVE-2018-16658 and CVE-2018-10940.
Signed-off-by: Young_X <YangX92@hotmail.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
CWE ID: CWE-200
|
static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi,
unsigned long arg)
{
cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n");
if (!CDROM_CAN(CDC_SELECT_DISC))
return -ENOSYS;
if (arg != CDSL_CURRENT && arg != CDSL_NONE) {
if (arg >= cdi->capacity)
return -EINVAL;
}
/*
* ->select_disc is a hook to allow a driver-specific way of
* seleting disc. However, since there is no equivalent hook for
* cdrom_slot_status this may not actually be useful...
*/
if (cdi->ops->select_disc)
return cdi->ops->select_disc(cdi, arg);
cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n");
return cdrom_select_disc(cdi, arg);
}
| 168,999
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SkiaOutputSurfaceImpl::Reshape(const gfx::Size& size,
float device_scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha,
bool use_stencil) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (initialize_waitable_event_) {
initialize_waitable_event_->Wait();
initialize_waitable_event_ = nullptr;
}
SkSurfaceCharacterization* characterization = nullptr;
if (characterization_.isValid()) {
characterization_ =
characterization_.createResized(size.width(), size.height());
RecreateRootRecorder();
} else {
characterization = &characterization_;
initialize_waitable_event_ = std::make_unique<base::WaitableEvent>(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
}
auto callback = base::BindOnce(
&SkiaOutputSurfaceImplOnGpu::Reshape,
base::Unretained(impl_on_gpu_.get()), size, device_scale_factor,
std::move(color_space), has_alpha, use_stencil, pre_transform_,
characterization, initialize_waitable_event_.get());
ScheduleGpuTask(std::move(callback), std::vector<gpu::SyncToken>());
}
Commit Message: SkiaRenderer: Support changing color space
SkiaOutputSurfaceImpl did not handle the color space changing after it
was created previously. The SkSurfaceCharacterization color space was
only set during the first time Reshape() ran when the charactization is
returned from the GPU thread. If the color space was changed later the
SkSurface and SkDDL color spaces no longer matched and draw failed.
Bug: 1009452
Change-Id: Ib6d2083efc7e7eb6f94782342e92a809b69d6fdc
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1841811
Reviewed-by: Peng Huang <penghuang@chromium.org>
Commit-Queue: kylechar <kylechar@chromium.org>
Cr-Commit-Position: refs/heads/master@{#702946}
CWE ID: CWE-704
|
void SkiaOutputSurfaceImpl::Reshape(const gfx::Size& size,
float device_scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha,
bool use_stencil) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (initialize_waitable_event_) {
initialize_waitable_event_->Wait();
initialize_waitable_event_.reset();
}
SkSurfaceCharacterization* characterization = nullptr;
if (characterization_.isValid()) {
sk_sp<SkColorSpace> sk_color_space = color_space.ToSkColorSpace();
if (!SkColorSpace::Equals(characterization_.refColorSpace().get(),
sk_color_space.get())) {
characterization_ = characterization_.createColorSpace(sk_color_space);
}
if (size.width() != characterization_.width() ||
size.height() != characterization_.height()) {
characterization_ =
characterization_.createResized(size.width(), size.height());
}
// TODO(kylechar): Update |characterization_| if |use_alpha| changes.
RecreateRootRecorder();
} else {
characterization = &characterization_;
initialize_waitable_event_ = std::make_unique<base::WaitableEvent>(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
}
auto task = base::BindOnce(&SkiaOutputSurfaceImplOnGpu::Reshape,
base::Unretained(impl_on_gpu_.get()), size,
device_scale_factor, color_space, has_alpha,
use_stencil, pre_transform_, characterization,
initialize_waitable_event_.get());
ScheduleGpuTask(std::move(task), {});
}
| 172,317
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ExtensionFunction::ResponseAction BluetoothSocketSendFunction::Run() {
DCHECK_CURRENTLY_ON(work_thread_id());
auto params = bluetooth_socket::Send::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params.get());
io_buffer_size_ = params->data.size();
io_buffer_ = new net::WrappedIOBuffer(params->data.data());
BluetoothApiSocket* socket = GetSocket(params->socket_id);
if (!socket)
return RespondNow(Error(kSocketNotFoundError));
socket->Send(io_buffer_,
io_buffer_size_,
base::Bind(&BluetoothSocketSendFunction::OnSuccess, this),
base::Bind(&BluetoothSocketSendFunction::OnError, this));
return did_respond() ? AlreadyResponded() : RespondLater();
}
Commit Message: chrome.bluetoothSocket: Fix regression in send()
In https://crrev.com/c/997098, params_ was changed to a local variable,
but it needs to last longer than that since net::WrappedIOBuffer may use
the data after the local variable goes out of scope.
This CL changed it back to be an instance variable.
Bug: 851799
Change-Id: I392f8acaef4c6473d6ea4fbee7209445aa09112e
Reviewed-on: https://chromium-review.googlesource.com/1103676
Reviewed-by: Toni Barzic <tbarzic@chromium.org>
Commit-Queue: Sonny Sasaka <sonnysasaka@chromium.org>
Cr-Commit-Position: refs/heads/master@{#568137}
CWE ID: CWE-416
|
ExtensionFunction::ResponseAction BluetoothSocketSendFunction::Run() {
DCHECK_CURRENTLY_ON(work_thread_id());
params_ = bluetooth_socket::Send::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
io_buffer_size_ = params_->data.size();
io_buffer_ = new net::WrappedIOBuffer(params_->data.data());
BluetoothApiSocket* socket = GetSocket(params_->socket_id);
if (!socket)
return RespondNow(Error(kSocketNotFoundError));
socket->Send(io_buffer_,
io_buffer_size_,
base::Bind(&BluetoothSocketSendFunction::OnSuccess, this),
base::Bind(&BluetoothSocketSendFunction::OnError, this));
return did_respond() ? AlreadyResponded() : RespondLater();
}
| 173,160
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error)
{
guint32 val;
GArray *array;
array = g_array_new (FALSE, TRUE, sizeof (guint32));
while (reqlen > 0) {
val = 42;
g_array_append_val (array, val);
val = 26;
g_array_append_val (array, val);
reqlen--;
}
val = 2;
g_array_append_val (array, val);
*ret = array;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error)
| 165,118
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: 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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: OMX_ERRORTYPE SoftRaw::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mChannelCount;
pcmParams->nSamplingRate = mSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftRaw::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mChannelCount;
pcmParams->nSamplingRate = mSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,218
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ikev2_sub0_print(ndo, base, np,
ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ikev2_sub0_print(ndo, base, np,
ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
| 167,802
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message: Moved EOF check.
CWE ID: CWE-20
|
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 170,155
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static gboolean nbd_negotiate_continue(QIOChannel *ioc,
GIOCondition condition,
void *opaque)
{
qemu_coroutine_enter(opaque);
return TRUE;
}
Commit Message:
CWE ID: CWE-20
|
static gboolean nbd_negotiate_continue(QIOChannel *ioc,
| 165,452
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: mrb_class_real(struct RClass* cl)
{
if (cl == 0)
return NULL;
while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {
cl = cl->super;
}
return cl;
}
Commit Message: `mrb_class_real()` did not work for `BasicObject`; fix #4037
CWE ID: CWE-476
|
mrb_class_real(struct RClass* cl)
{
if (cl == 0) return NULL;
while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {
cl = cl->super;
if (cl == 0) return NULL;
}
return cl;
}
| 169,200
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1)
: mIsValid(false),
mData(NULL),
mSize(0),
mFirstFrameOffset(0),
mVersion(ID3_UNKNOWN),
mRawSize(0) {
sp<MemorySource> source = new MemorySource(data, size);
mIsValid = parseV2(source, 0);
if (!mIsValid && !ignoreV1) {
mIsValid = parseV1(source);
}
}
Commit Message: better validation lengths of strings in ID3 tags
Validate lengths on strings in ID3 tags, particularly around 0.
Also added code to handle cases when we can't get memory for
copies of strings we want to extract from these tags.
Affects L/M/N/master, same patch for all of them.
Bug: 30744884
Change-Id: I2675a817a39f0927ec1f7e9f9c09f2e61020311e
Test: play mp3 file which caused a <0 length.
(cherry picked from commit d23c01546c4f82840a01a380def76ab6cae5d43f)
CWE ID: CWE-20
|
ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1)
: mIsValid(false),
mData(NULL),
mSize(0),
mFirstFrameOffset(0),
mVersion(ID3_UNKNOWN),
mRawSize(0) {
sp<MemorySource> source = new (std::nothrow) MemorySource(data, size);
if (source == NULL)
return;
mIsValid = parseV2(source, 0);
if (!mIsValid && !ignoreV1) {
mIsValid = parseV1(source);
}
}
| 173,392
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void usage()
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: pnm2png [options] <file>.<pnm> [<file>.png]\n");
fprintf (stderr, " or: ... | pnm2png [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -i[nterlace] write png-file with interlacing on\n");
fprintf (stderr, " -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
void usage()
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: pnm2png [options] <file>.<pnm> [<file>.png]\n");
fprintf (stderr, " or: ... | pnm2png [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -i[nterlace] write png-file with interlacing on\n");
fprintf (stderr,
" -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
| 173,726
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: WarmupURLFetcher::WarmupURLFetcher(
CreateCustomProxyConfigCallback create_custom_proxy_config_callback,
WarmupURLFetcherCallback callback,
GetHttpRttCallback get_http_rtt_callback,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
const std::string& user_agent)
: is_fetch_in_flight_(false),
previous_attempt_counts_(0),
create_custom_proxy_config_callback_(create_custom_proxy_config_callback),
callback_(callback),
get_http_rtt_callback_(get_http_rtt_callback),
user_agent_(user_agent),
ui_task_runner_(ui_task_runner) {
DCHECK(create_custom_proxy_config_callback);
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <tbansal@chromium.org>
Reviewed-by: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416
|
WarmupURLFetcher::WarmupURLFetcher(
CreateCustomProxyConfigCallback create_custom_proxy_config_callback,
WarmupURLFetcherCallback callback,
GetHttpRttCallback get_http_rtt_callback,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
const std::string& user_agent)
: is_fetch_in_flight_(false),
previous_attempt_counts_(0),
create_custom_proxy_config_callback_(create_custom_proxy_config_callback),
callback_(callback),
get_http_rtt_callback_(get_http_rtt_callback),
user_agent_(user_agent),
ui_task_runner_(ui_task_runner) {
DCHECK(create_custom_proxy_config_callback);
DCHECK(!params::IsIncludedInHoldbackFieldTrial());
}
| 172,426
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() {
InputMethodDescriptors* descriptors = new InputMethodDescriptors;
descriptors->push_back(
input_method::GetFallbackInputMethodDescriptor());
return descriptors;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() {
input_method::InputMethodDescriptors*
CrosMock::CreateInputMethodDescriptors() {
input_method::InputMethodDescriptors* descriptors =
new input_method::InputMethodDescriptors;
descriptors->push_back(
input_method::GetFallbackInputMethodDescriptor());
return descriptors;
}
| 170,475
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.