Dataset Viewer
Auto-converted to Parquet
instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Horizontal_Sweep_Drop( RAS_ARGS Short y, FT_F26Dot6 x1, FT_F26Dot6 x2, PProfile left, PProfile right ) { Long e1, e2, pxl; PByte bits; Byte f1; /* During the horizontal sweep, we only take care of drop-outs */ /* e1 + <-- pixel center */ /* | */ /* x1 ---+--> <-- contour */ /* | */ /* | */ /* x2 <--+--- <-- contour */ /* | */ /* | */ /* e2 + <-- pixel center */ e1 = CEILING( x1 ); e2 = FLOOR ( x2 ); pxl = e1; if ( e1 > e2 ) { Int dropOutControl = left->flags & 7; if ( e1 == e2 + ras.precision ) { switch ( dropOutControl ) { case 0: /* simple drop-outs including stubs */ pxl = e2; break; case 4: /* smart drop-outs including stubs */ pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half ); break; case 1: /* simple drop-outs excluding stubs */ case 5: /* smart drop-outs excluding stubs */ /* see Vertical_Sweep_Drop for details */ /* rightmost stub test */ if ( left->next == right && left->height <= 0 && !( left->flags & Overshoot_Top && x2 - x1 >= ras.precision_half ) ) return; /* leftmost stub test */ if ( right->next == left && left->start == y && !( left->flags & Overshoot_Bottom && x2 - x1 >= ras.precision_half ) ) return; if ( dropOutControl == 1 ) pxl = e2; else pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half ); break; default: /* modes 2, 3, 6, 7 */ return; /* no drop-out control */ } /* undocumented but confirmed: If the drop-out would result in a */ /* pixel outside of the bounding box, use the pixel inside of the */ /* bounding box instead */ if ( pxl < 0 ) pxl = e1; else if ( TRUNC( pxl ) >= ras.target.rows ) pxl = e2; /* check that the other pixel isn't set */ e1 = pxl == e1 ? e2 : e1; e1 = TRUNC( e1 ); bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); bits -= e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) bits += ( ras.target.rows - 1 ) * ras.target.pitch; if ( e1 >= 0 && e1 < ras.target.rows && *bits & f1 ) return; } else return; } bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); e1 = TRUNC( pxl ); if ( e1 >= 0 && e1 < ras.target.rows ) { bits -= e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) bits += ( ras.target.rows - 1 ) * ras.target.pitch; bits[0] |= f1; } } Commit Message: CWE ID: CWE-119
Horizontal_Sweep_Drop( RAS_ARGS Short y, FT_F26Dot6 x1, FT_F26Dot6 x2, PProfile left, PProfile right ) { Long e1, e2, pxl; PByte bits; Byte f1; /* During the horizontal sweep, we only take care of drop-outs */ /* e1 + <-- pixel center */ /* | */ /* x1 ---+--> <-- contour */ /* | */ /* | */ /* x2 <--+--- <-- contour */ /* | */ /* | */ /* e2 + <-- pixel center */ e1 = CEILING( x1 ); e2 = FLOOR ( x2 ); pxl = e1; if ( e1 > e2 ) { Int dropOutControl = left->flags & 7; if ( e1 == e2 + ras.precision ) { switch ( dropOutControl ) { case 0: /* simple drop-outs including stubs */ pxl = e2; break; case 4: /* smart drop-outs including stubs */ pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half ); break; case 1: /* simple drop-outs excluding stubs */ case 5: /* smart drop-outs excluding stubs */ /* see Vertical_Sweep_Drop for details */ /* rightmost stub test */ if ( left->next == right && left->height <= 0 && !( left->flags & Overshoot_Top && x2 - x1 >= ras.precision_half ) ) return; /* leftmost stub test */ if ( right->next == left && left->start == y && !( left->flags & Overshoot_Bottom && x2 - x1 >= ras.precision_half ) ) return; if ( dropOutControl == 1 ) pxl = e2; else pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half ); break; default: /* modes 2, 3, 6, 7 */ return; /* no drop-out control */ } /* undocumented but confirmed: If the drop-out would result in a */ /* pixel outside of the bounding box, use the pixel inside of the */ /* bounding box instead */ if ( pxl < 0 ) pxl = e1; else if ( (ULong)( TRUNC( pxl ) ) >= ras.target.rows ) pxl = e2; /* check that the other pixel isn't set */ e1 = pxl == e1 ? e2 : e1; e1 = TRUNC( e1 ); bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); bits -= e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) bits += ( ras.target.rows - 1 ) * ras.target.pitch; if ( e1 >= 0 && (ULong)e1 < ras.target.rows && *bits & f1 ) return; } else return; } bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); e1 = TRUNC( pxl ); if ( e1 >= 0 && (ULong)e1 < ras.target.rows ) { bits -= e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) bits += ( ras.target.rows - 1 ) * ras.target.pitch; bits[0] |= f1; } }
164,852
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { ActionReply reply; QMapIterator<QString, QVariant> it(args); proc.setOutputChannelMode(KProcess::SeparateChannels); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); #if defined(Q_OS_LINUX) proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true); #endif QVariantMap entry = it.value().toMap(); KProcess proc(this); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool userKill = false; QStringList command; #if defined(Q_OS_LINUX) command << entry["mh_command"].toString(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); else { } if (HelperSupport::isStopped()) { proc.kill(); userKill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!userKill) { reply.setType(ActionReply::HelperErrorType); reply.setErrorDescription(i18n("The mount process crashed.")); break; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed()); } } Commit Message: CWE ID: CWE-20
ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { // // The action reply // ActionReply reply; // Get the mount executable // const QString mount = findMountExecutable(); // QMapIterator<QString, QVariant> it(args); proc.setOutputChannelMode(KProcess::SeparateChannels); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); #if defined(Q_OS_LINUX) proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true); #endif QVariantMap entry = it.value().toMap(); // Check the executable // if (mount != entry["mh_command"].toString()) { // Something weird is going on, bail out. reply.setType(ActionReply::HelperErrorType); return reply; } else { // Do nothing } // KProcess proc(this); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool userKill = false; QStringList command; #if defined(Q_OS_LINUX) command << mount; command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << mount; command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); else { } if (HelperSupport::isStopped()) { proc.kill(); userKill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!userKill) { reply.setType(ActionReply::HelperErrorType); reply.setErrorDescription(i18n("The mount process crashed.")); break; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed()); } }
164,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OneClickSigninHelper::ShowInfoBarIfPossible(net::URLRequest* request, ProfileIOData* io_data, int child_id, int route_id) { std::string google_chrome_signin_value; std::string google_accounts_signin_value; request->GetResponseHeaderByName("Google-Chrome-SignIn", &google_chrome_signin_value); request->GetResponseHeaderByName("Google-Accounts-SignIn", &google_accounts_signin_value); if (!google_accounts_signin_value.empty() || !google_chrome_signin_value.empty()) { VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:" << " g-a-s='" << google_accounts_signin_value << "'" << " g-c-s='" << google_chrome_signin_value << "'"; } if (!gaia::IsGaiaSignonRealm(request->original_url().GetOrigin())) return; std::vector<std::pair<std::string, std::string> > pairs; base::SplitStringIntoKeyValuePairs(google_accounts_signin_value, '=', ',', &pairs); std::string session_index; std::string email; for (size_t i = 0; i < pairs.size(); ++i) { const std::pair<std::string, std::string>& pair = pairs[i]; const std::string& key = pair.first; const std::string& value = pair.second; if (key == "email") { TrimString(value, "\"", &email); } else if (key == "sessionindex") { session_index = value; } } if (!email.empty()) io_data->set_reverse_autologin_pending_email(email); if (!email.empty() || !session_index.empty()) { VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:" << " email=" << email << " sessionindex=" << session_index; } AutoAccept auto_accept = AUTO_ACCEPT_NONE; signin::Source source = signin::SOURCE_UNKNOWN; GURL continue_url; std::vector<std::string> tokens; base::SplitString(google_chrome_signin_value, ',', &tokens); for (size_t i = 0; i < tokens.size(); ++i) { const std::string& token = tokens[i]; if (token == "accepted") { auto_accept = AUTO_ACCEPT_ACCEPTED; } else if (token == "configure") { auto_accept = AUTO_ACCEPT_CONFIGURE; } else if (token == "rejected-for-profile") { auto_accept = AUTO_ACCEPT_REJECTED_FOR_PROFILE; } } source = GetSigninSource(request->url(), &continue_url); if (source != signin::SOURCE_UNKNOWN) auto_accept = AUTO_ACCEPT_EXPLICIT; if (auto_accept != AUTO_ACCEPT_NONE) { VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:" << " auto_accept=" << auto_accept; } if (session_index.empty() && email.empty() && auto_accept == AUTO_ACCEPT_NONE && !continue_url.is_valid()) { return; } content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&OneClickSigninHelper::ShowInfoBarUIThread, session_index, email, auto_accept, source, continue_url, child_id, route_id)); } Commit Message: During redirects in the one click sign in flow, check the current URL instead of original URL to validate gaia http headers. BUG=307159 Review URL: https://codereview.chromium.org/77343002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@236563 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
void OneClickSigninHelper::ShowInfoBarIfPossible(net::URLRequest* request, ProfileIOData* io_data, int child_id, int route_id) { std::string google_chrome_signin_value; std::string google_accounts_signin_value; request->GetResponseHeaderByName("Google-Chrome-SignIn", &google_chrome_signin_value); request->GetResponseHeaderByName("Google-Accounts-SignIn", &google_accounts_signin_value); if (!google_accounts_signin_value.empty() || !google_chrome_signin_value.empty()) { VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:" << " g-a-s='" << google_accounts_signin_value << "'" << " g-c-s='" << google_chrome_signin_value << "'"; } if (!gaia::IsGaiaSignonRealm(request->url().GetOrigin())) return; std::vector<std::pair<std::string, std::string> > pairs; base::SplitStringIntoKeyValuePairs(google_accounts_signin_value, '=', ',', &pairs); std::string session_index; std::string email; for (size_t i = 0; i < pairs.size(); ++i) { const std::pair<std::string, std::string>& pair = pairs[i]; const std::string& key = pair.first; const std::string& value = pair.second; if (key == "email") { TrimString(value, "\"", &email); } else if (key == "sessionindex") { session_index = value; } } if (!email.empty()) io_data->set_reverse_autologin_pending_email(email); if (!email.empty() || !session_index.empty()) { VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:" << " email=" << email << " sessionindex=" << session_index; } AutoAccept auto_accept = AUTO_ACCEPT_NONE; signin::Source source = signin::SOURCE_UNKNOWN; GURL continue_url; std::vector<std::string> tokens; base::SplitString(google_chrome_signin_value, ',', &tokens); for (size_t i = 0; i < tokens.size(); ++i) { const std::string& token = tokens[i]; if (token == "accepted") { auto_accept = AUTO_ACCEPT_ACCEPTED; } else if (token == "configure") { auto_accept = AUTO_ACCEPT_CONFIGURE; } else if (token == "rejected-for-profile") { auto_accept = AUTO_ACCEPT_REJECTED_FOR_PROFILE; } } source = GetSigninSource(request->url(), &continue_url); if (source != signin::SOURCE_UNKNOWN) auto_accept = AUTO_ACCEPT_EXPLICIT; if (auto_accept != AUTO_ACCEPT_NONE) { VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:" << " auto_accept=" << auto_accept; } if (session_index.empty() && email.empty() && auto_accept == AUTO_ACCEPT_NONE && !continue_url.is_valid()) { return; } content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&OneClickSigninHelper::ShowInfoBarUIThread, session_index, email, auto_accept, source, continue_url, child_id, route_id)); }
171,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */ { char *table_copy, *escaped, *token, *tmp; size_t len; /* schame.table should be "schame"."table" */ table_copy = estrdup(table); token = php_strtok_r(table_copy, ".", &tmp); len = strlen(token); if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) { smart_str_appendl(querystr, token, len); PGSQLfree(escaped); } if (tmp && *tmp) { len = strlen(tmp); /* "schema"."table" format */ if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) { smart_str_appendc(querystr, '.'); smart_str_appendl(querystr, tmp, len); } else { escaped = PGSQLescapeIdentifier(pg_link, tmp, len); smart_str_appendc(querystr, '.'); smart_str_appends(querystr, escaped); PGSQLfree(escaped); } } efree(table_copy); } /* }}} */ Commit Message: CWE ID:
static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */ { char *table_copy, *escaped, *token, *tmp; size_t len; /* schame.table should be "schame"."table" */ table_copy = estrdup(table); token = php_strtok_r(table_copy, ".", &tmp); if (token == NULL) { token = table; } len = strlen(token); if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) { smart_str_appendl(querystr, token, len); PGSQLfree(escaped); } if (tmp && *tmp) { len = strlen(tmp); /* "schema"."table" format */ if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) { smart_str_appendc(querystr, '.'); smart_str_appendl(querystr, tmp, len); } else { escaped = PGSQLescapeIdentifier(pg_link, tmp, len); smart_str_appendc(querystr, '.'); smart_str_appends(querystr, escaped); PGSQLfree(escaped); } } efree(table_copy); } /* }}} */
164,769
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ClipboardMessageFilter::OnReadImageReply( SkBitmap bitmap, IPC::Message* reply_msg) { base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle(); uint32 image_size = 0; std::string reply_data; if (!bitmap.isNull()) { std::vector<unsigned char> png_data; SkAutoLockPixels lock(bitmap); if (gfx::PNGCodec::EncodeWithCompressionLevel( static_cast<const unsigned char*>(bitmap.getPixels()), gfx::PNGCodec::FORMAT_BGRA, gfx::Size(bitmap.width(), bitmap.height()), bitmap.rowBytes(), false, std::vector<gfx::PNGCodec::Comment>(), Z_BEST_SPEED, &png_data)) { base::SharedMemory buffer; if (buffer.CreateAndMapAnonymous(png_data.size())) { memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size()); if (buffer.GiveToProcess(peer_handle(), &image_handle)) { image_size = png_data.size(); } } } } ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle, image_size); Send(reply_msg); } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void ClipboardMessageFilter::OnReadImageReply( const SkBitmap& bitmap, IPC::Message* reply_msg) { base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle(); uint32 image_size = 0; std::string reply_data; if (!bitmap.isNull()) { std::vector<unsigned char> png_data; SkAutoLockPixels lock(bitmap); if (gfx::PNGCodec::EncodeWithCompressionLevel( static_cast<const unsigned char*>(bitmap.getPixels()), gfx::PNGCodec::FORMAT_BGRA, gfx::Size(bitmap.width(), bitmap.height()), bitmap.rowBytes(), false, std::vector<gfx::PNGCodec::Comment>(), Z_BEST_SPEED, &png_data)) { base::SharedMemory buffer; if (buffer.CreateAndMapAnonymous(png_data.size())) { memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size()); if (buffer.GiveToProcess(peer_handle(), &image_handle)) { image_size = png_data.size(); } } } } ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle, image_size); Send(reply_msg); }
170,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BlockEntry::BlockEntry(Cluster* p, long idx) : m_pCluster(p), m_index(idx) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
BlockEntry::BlockEntry(Cluster* p, long idx) : BlockEntry::~BlockEntry() {} bool BlockEntry::EOS() const { return (GetKind() == kBlockEOS); } const Cluster* BlockEntry::GetCluster() const { return m_pCluster; } long BlockEntry::GetIndex() const { return m_index; } SimpleBlock::SimpleBlock(Cluster* pCluster, long idx, long long start, long long size) : BlockEntry(pCluster, idx), m_block(start, size, 0) {} long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); } BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; } const Block* SimpleBlock::GetBlock() const { return &m_block; } 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) {} long BlockGroup::Parse() { const long status = m_block.Parse(m_pCluster); if (status) return status; m_block.SetKey((m_prev > 0) && (m_next <= 0)); return 0; }
174,241
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_emulation_failure(struct kvm_vcpu *vcpu) { int r = EMULATE_DONE; ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); if (!is_guest_mode(vcpu)) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; r = EMULATE_FAIL; } kvm_queue_exception(vcpu, UD_VECTOR); return r; } Commit Message: KVM: x86: Don't report guest userspace emulation error to userspace Commit fc3a9157d314 ("KVM: X86: Don't report L2 emulation failures to user-space") disabled the reporting of L2 (nested guest) emulation failures to userspace due to race-condition between a vmexit and the instruction emulator. The same rational applies also to userspace applications that are permitted by the guest OS to access MMIO area or perform PIO. This patch extends the current behavior - of injecting a #UD instead of reporting it to userspace - also for guest userspace code. Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-362
static int handle_emulation_failure(struct kvm_vcpu *vcpu) { int r = EMULATE_DONE; ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; r = EMULATE_FAIL; } kvm_queue_exception(vcpu, UD_VECTOR); return r; }
166,252
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) { if (!is_hidden_) return; TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown"); is_hidden_ = false; if (new_content_rendering_timeout_ && new_content_rendering_timeout_->IsRunning()) { new_content_rendering_timeout_->Stop(); ClearDisplayedGraphics(); } SendScreenRects(); RestartHangMonitorTimeoutIfNecessary(); bool needs_repainting = true; needs_repainting_on_restore_ = false; Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info)); process_->WidgetRestored(); bool is_visible = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderWidgetHost>(this), Details<bool>(&is_visible)); WasResized(); } Commit Message: Force a flush of drawing to the widget when a dialog is shown. BUG=823353 TEST=as in bug Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260 Reviewed-on: https://chromium-review.googlesource.com/971661 Reviewed-by: Ken Buchanan <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#544518} CWE ID:
void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) { if (!is_hidden_) return; TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown"); is_hidden_ = false; ForceFirstFrameAfterNavigationTimeout(); SendScreenRects(); RestartHangMonitorTimeoutIfNecessary(); bool needs_repainting = true; needs_repainting_on_restore_ = false; Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info)); process_->WidgetRestored(); bool is_visible = true; NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, Source<RenderWidgetHost>(this), Details<bool>(&is_visible)); WasResized(); }
173,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GesturePoint::IsInSecondClickTimeWindow() const { double duration = last_touch_time_ - last_tap_time_; return duration < kMaximumSecondsBetweenDoubleClick; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool GesturePoint::IsInSecondClickTimeWindow() const { double duration = last_touch_time_ - last_tap_time_; return duration < GestureConfiguration::max_seconds_between_double_click(); }
171,043
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { FILE *infile = NULL; vpx_codec_ctx_t codec; vpx_codec_enc_cfg_t cfg; int frame_count = 0; vpx_image_t raw; vpx_codec_err_t res; VpxVideoInfo info = {0}; VpxVideoWriter *writer = NULL; const VpxInterface *encoder = NULL; const int fps = 30; // TODO(dkovalev) add command line argument const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument int keyframe_interval = 0; const char *codec_arg = NULL; const char *width_arg = NULL; const char *height_arg = NULL; const char *infile_arg = NULL; const char *outfile_arg = NULL; const char *keyframe_interval_arg = NULL; exec_name = argv[0]; if (argc < 7) die("Invalid number of arguments"); codec_arg = argv[1]; width_arg = argv[2]; height_arg = argv[3]; infile_arg = argv[4]; outfile_arg = argv[5]; keyframe_interval_arg = argv[6]; encoder = get_vpx_encoder_by_name(codec_arg); if (!encoder) die("Unsupported codec."); info.codec_fourcc = encoder->fourcc; info.frame_width = strtol(width_arg, NULL, 0); info.frame_height = strtol(height_arg, NULL, 0); info.time_base.numerator = 1; info.time_base.denominator = fps; if (info.frame_width <= 0 || info.frame_height <= 0 || (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) { die("Invalid frame size: %dx%d", info.frame_width, info.frame_height); } if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width, info.frame_height, 1)) { die("Failed to allocate image."); } keyframe_interval = strtol(keyframe_interval_arg, NULL, 0); if (keyframe_interval < 0) die("Invalid keyframe interval value."); printf("Using %s\n", vpx_codec_iface_name(encoder->interface())); res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0); if (res) die_codec(&codec, "Failed to get default codec config."); cfg.g_w = info.frame_width; cfg.g_h = info.frame_height; cfg.g_timebase.num = info.time_base.numerator; cfg.g_timebase.den = info.time_base.denominator; cfg.rc_target_bitrate = bitrate; cfg.g_error_resilient = argc > 7 ? strtol(argv[7], NULL, 0) : 0; writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing.", outfile_arg); if (!(infile = fopen(infile_arg, "rb"))) die("Failed to open %s for reading.", infile_arg); if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); while (vpx_img_read(&raw, infile)) { int flags = 0; if (keyframe_interval > 0 && frame_count % keyframe_interval == 0) flags |= VPX_EFLAG_FORCE_KF; encode_frame(&codec, &raw, frame_count++, flags, writer); } encode_frame(&codec, NULL, -1, 0, writer); // flush the encoder printf("\n"); fclose(infile); printf("Processed %d frames.\n", frame_count); vpx_img_free(&raw); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); return EXIT_SUCCESS; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int main(int argc, char **argv) { FILE *infile = NULL; vpx_codec_ctx_t codec; vpx_codec_enc_cfg_t cfg; int frame_count = 0; vpx_image_t raw; vpx_codec_err_t res; VpxVideoInfo info = {0}; VpxVideoWriter *writer = NULL; const VpxInterface *encoder = NULL; const int fps = 30; // TODO(dkovalev) add command line argument const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument int keyframe_interval = 0; const char *codec_arg = NULL; const char *width_arg = NULL; const char *height_arg = NULL; const char *infile_arg = NULL; const char *outfile_arg = NULL; const char *keyframe_interval_arg = NULL; exec_name = argv[0]; if (argc < 7) die("Invalid number of arguments"); codec_arg = argv[1]; width_arg = argv[2]; height_arg = argv[3]; infile_arg = argv[4]; outfile_arg = argv[5]; keyframe_interval_arg = argv[6]; encoder = get_vpx_encoder_by_name(codec_arg); if (!encoder) die("Unsupported codec."); info.codec_fourcc = encoder->fourcc; info.frame_width = strtol(width_arg, NULL, 0); info.frame_height = strtol(height_arg, NULL, 0); info.time_base.numerator = 1; info.time_base.denominator = fps; if (info.frame_width <= 0 || info.frame_height <= 0 || (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) { die("Invalid frame size: %dx%d", info.frame_width, info.frame_height); } if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width, info.frame_height, 1)) { die("Failed to allocate image."); } keyframe_interval = strtol(keyframe_interval_arg, NULL, 0); if (keyframe_interval < 0) die("Invalid keyframe interval value."); printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface())); res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0); if (res) die_codec(&codec, "Failed to get default codec config."); cfg.g_w = info.frame_width; cfg.g_h = info.frame_height; cfg.g_timebase.num = info.time_base.numerator; cfg.g_timebase.den = info.time_base.denominator; cfg.rc_target_bitrate = bitrate; cfg.g_error_resilient = argc > 7 ? strtol(argv[7], NULL, 0) : 0; writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing.", outfile_arg); if (!(infile = fopen(infile_arg, "rb"))) die("Failed to open %s for reading.", infile_arg); if (vpx_codec_enc_init(&codec, encoder->codec_interface(), &cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); // Encode frames. while (vpx_img_read(&raw, infile)) { int flags = 0; if (keyframe_interval > 0 && frame_count % keyframe_interval == 0) flags |= VPX_EFLAG_FORCE_KF; encode_frame(&codec, &raw, frame_count++, flags, writer); } // Flush encoder. while (encode_frame(&codec, NULL, -1, 0, writer)) {}; printf("\n"); fclose(infile); printf("Processed %d frames.\n", frame_count); vpx_img_free(&raw); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); return EXIT_SUCCESS; }
174,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: string DecodeFile(const string& filename, int num_threads) { libvpx_test::WebMVideoSource video(filename); video.Init(); vpx_codec_dec_cfg_t cfg = {0}; cfg.threads = num_threads; libvpx_test::VP9Decoder decoder(cfg, 0); libvpx_test::MD5 md5; for (video.Begin(); video.cxdata(); video.Next()) { const vpx_codec_err_t res = decoder.DecodeFrame(video.cxdata(), video.frame_size()); if (res != VPX_CODEC_OK) { EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError(); break; } libvpx_test::DxDataIterator dec_iter = decoder.GetDxData(); const vpx_image_t *img = NULL; while ((img = dec_iter.Next())) { md5.Add(img); } } return string(md5.Get()); } 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
string DecodeFile(const string& filename, int num_threads) { libvpx_test::WebMVideoSource video(filename); video.Init(); vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t(); cfg.threads = num_threads; libvpx_test::VP9Decoder decoder(cfg, 0); libvpx_test::MD5 md5; for (video.Begin(); video.cxdata(); video.Next()) { const vpx_codec_err_t res = decoder.DecodeFrame(video.cxdata(), video.frame_size()); if (res != VPX_CODEC_OK) { EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError(); break; } libvpx_test::DxDataIterator dec_iter = decoder.GetDxData(); const vpx_image_t *img = NULL; while ((img = dec_iter.Next())) { md5.Add(img); } } return string(md5.Get()); }
174,598
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ber_parse_header(STREAM s, int tagval, int *length) { int tag, len; if (tagval > 0xff) { in_uint16_be(s, tag); } else { in_uint8(s, tag); } if (tag != tagval) { logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag); return False; } in_uint8(s, len); if (len & 0x80) { len &= ~0x80; *length = 0; while (len--) next_be(s, *length); } else *length = len; return s_check(s); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
ber_parse_header(STREAM s, int tagval, int *length) ber_parse_header(STREAM s, int tagval, uint32 *length) { int tag, len; if (tagval > 0xff) { in_uint16_be(s, tag); } else { in_uint8(s, tag); } if (tag != tagval) { logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag); return False; } in_uint8(s, len); if (len & 0x80) { len &= ~0x80; *length = 0; while (len--) next_be(s, *length); } else *length = len; return s_check(s); }
169,794
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119
MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (HeapOverflowSanityCheck(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); }
168,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pimv2_addr_print(netdissect_options *ndo, const u_char *bp, enum pimv2_addrtype at, int silent) { int af; int len, hdrlen; ND_TCHECK(bp[0]); if (pimv2_addr_len == 0) { ND_TCHECK(bp[1]); switch (bp[0]) { case 1: af = AF_INET; len = sizeof(struct in_addr); break; case 2: af = AF_INET6; len = sizeof(struct in6_addr); break; default: return -1; } if (bp[1] != 0) return -1; hdrlen = 2; } else { switch (pimv2_addr_len) { case sizeof(struct in_addr): af = AF_INET; break; case sizeof(struct in6_addr): af = AF_INET6; break; default: return -1; break; } len = pimv2_addr_len; hdrlen = 0; } bp += hdrlen; switch (at) { case pimv2_unicast: ND_TCHECK2(bp[0], len); if (af == AF_INET) { if (!silent) ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp))); } else if (af == AF_INET6) { if (!silent) ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp))); } return hdrlen + len; case pimv2_group: case pimv2_source: ND_TCHECK2(bp[0], len + 2); if (af == AF_INET) { if (!silent) { ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp + 2))); if (bp[1] != 32) ND_PRINT((ndo, "/%u", bp[1])); } } else if (af == AF_INET6) { if (!silent) { ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp + 2))); if (bp[1] != 128) ND_PRINT((ndo, "/%u", bp[1])); } } if (bp[0] && !silent) { if (at == pimv2_group) { ND_PRINT((ndo, "(0x%02x)", bp[0])); } else { ND_PRINT((ndo, "(%s%s%s", bp[0] & 0x04 ? "S" : "", bp[0] & 0x02 ? "W" : "", bp[0] & 0x01 ? "R" : "")); if (bp[0] & 0xf8) { ND_PRINT((ndo, "+0x%02x", bp[0] & 0xf8)); } ND_PRINT((ndo, ")")); } } return hdrlen + 2 + len; default: return -1; } trunc: return -1; } Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks. Use ND_TCHECK macros to do bounds checking, and add length checks before the bounds checks. Add a bounds check that the review process found was missing. 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), modified so the capture file won't be rejected as an invalid capture. Update one test output file to reflect the changes. CWE ID: CWE-125
pimv2_addr_print(netdissect_options *ndo, const u_char *bp, u_int len, enum pimv2_addrtype at, u_int addr_len, int silent) { int af; int hdrlen; if (addr_len == 0) { if (len < 2) goto trunc; ND_TCHECK(bp[1]); switch (bp[0]) { case 1: af = AF_INET; addr_len = (u_int)sizeof(struct in_addr); break; case 2: af = AF_INET6; addr_len = (u_int)sizeof(struct in6_addr); break; default: return -1; } if (bp[1] != 0) return -1; hdrlen = 2; } else { switch (addr_len) { case sizeof(struct in_addr): af = AF_INET; break; case sizeof(struct in6_addr): af = AF_INET6; break; default: return -1; break; } hdrlen = 0; } bp += hdrlen; len -= hdrlen; switch (at) { case pimv2_unicast: if (len < addr_len) goto trunc; ND_TCHECK2(bp[0], addr_len); if (af == AF_INET) { if (!silent) ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp))); } else if (af == AF_INET6) { if (!silent) ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp))); } return hdrlen + addr_len; case pimv2_group: case pimv2_source: if (len < addr_len + 2) goto trunc; ND_TCHECK2(bp[0], addr_len + 2); if (af == AF_INET) { if (!silent) { ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp + 2))); if (bp[1] != 32) ND_PRINT((ndo, "/%u", bp[1])); } } else if (af == AF_INET6) { if (!silent) { ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp + 2))); if (bp[1] != 128) ND_PRINT((ndo, "/%u", bp[1])); } } if (bp[0] && !silent) { if (at == pimv2_group) { ND_PRINT((ndo, "(0x%02x)", bp[0])); } else { ND_PRINT((ndo, "(%s%s%s", bp[0] & 0x04 ? "S" : "", bp[0] & 0x02 ? "W" : "", bp[0] & 0x01 ? "R" : "")); if (bp[0] & 0xf8) { ND_PRINT((ndo, "+0x%02x", bp[0] & 0xf8)); } ND_PRINT((ndo, ")")); } } return hdrlen + 2 + addr_len; default: return -1; } trunc: return -1; }
167,857
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderThread::~RenderThread() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); if (web_database_observer_impl_.get()) web_database_observer_impl_->WaitForAllDatabasesToClose(); RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; RemoveFilter(vc_manager_->video_capture_message_filter()); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_.get()) file_thread_->Stop(); if (webkit_client_.get()) WebKit::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) PluginChannelBase::CleanupChannels(); if (RenderProcessImpl::InProcessPlugins()) CoUninitialize(); #endif } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
RenderThread::~RenderThread() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); if (web_database_observer_impl_.get()) web_database_observer_impl_->WaitForAllDatabasesToClose(); RemoveFilter(devtools_agent_message_filter_.get()); devtools_agent_message_filter_ = NULL; RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; RemoveFilter(vc_manager_->video_capture_message_filter()); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_.get()) file_thread_->Stop(); if (webkit_client_.get()) WebKit::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) PluginChannelBase::CleanupChannels(); if (RenderProcessImpl::InProcessPlugins()) CoUninitialize(); #endif }
170,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: raptor_rdfxml_parse_start(raptor_parser* rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rdfxml_parser* rdf_xml_parser; rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context; /* base URI required for RDF/XML */ if(!uri) return 1; /* Optionally normalize language to lowercase * http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE)); /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rdf_xml_parser->sax2, uri); /* Delete any existing id_set */ if(rdf_xml_parser->id_set) { raptor_free_id_set(rdf_xml_parser->id_set); rdf_xml_parser->id_set = NULL; } /* Create a new id_set if needed */ if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) { rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world); if(!rdf_xml_parser->id_set) return 1; } return 0; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_rdfxml_parse_start(raptor_parser* rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rdfxml_parser* rdf_xml_parser; rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context; /* base URI required for RDF/XML */ if(!uri) return 1; /* Optionally normalize language to lowercase * http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE)); /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rdf_xml_parser->sax2, uri); /* Delete any existing id_set */ if(rdf_xml_parser->id_set) { raptor_free_id_set(rdf_xml_parser->id_set); rdf_xml_parser->id_set = NULL; } /* Create a new id_set if needed */ if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) { rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world); if(!rdf_xml_parser->id_set) return 1; } return 0; }
165,660
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadTILEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image, *tile_image; ImageInfo *read_info; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; tile_image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) return((Image *) NULL); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (*image_info->filename == '\0') ThrowReaderException(OptionError,"MustSpecifyAnImageName"); image->colorspace=tile_image->colorspace; image->matte=tile_image->matte; if (image->matte != MagickFalse) (void) SetImageBackgroundColor(image); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); if (LocaleCompare(tile_image->magick,"PATTERN") == 0) { tile_image->tile_offset.x=0; tile_image->tile_offset.y=0; } (void) TextureImage(image,tile_image); tile_image=DestroyImage(tile_image); if (image->colorspace == GRAYColorspace) image->type=GrayscaleType; return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadTILEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image, *tile_image; ImageInfo *read_info; MagickBooleanType status; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; tile_image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) return((Image *) NULL); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (*image_info->filename == '\0') ThrowReaderException(OptionError,"MustSpecifyAnImageName"); image->colorspace=tile_image->colorspace; image->matte=tile_image->matte; if (image->matte != MagickFalse) (void) SetImageBackgroundColor(image); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); if (LocaleCompare(tile_image->magick,"PATTERN") == 0) { tile_image->tile_offset.x=0; tile_image->tile_offset.y=0; } (void) TextureImage(image,tile_image); tile_image=DestroyImage(tile_image); if (image->colorspace == GRAYColorspace) image->type=GrayscaleType; return(GetFirstImageInList(image)); }
168,610
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */ { struct fpm_worker_pool_config_s *c = wp->config; /* uninitialized */ wp->socket_uid = -1; wp->socket_gid = -1; wp->socket_mode = 0666; if (!c) { return 0; } if (c->listen_owner && *c->listen_owner) { struct passwd *pwd; pwd = getpwnam(c->listen_owner); if (!pwd) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get uid for user '%s'", wp->config->name, c->listen_owner); return -1; } wp->socket_uid = pwd->pw_uid; wp->socket_gid = pwd->pw_gid; } if (c->listen_group && *c->listen_group) { struct group *grp; grp = getgrnam(c->listen_group); if (!grp) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get gid for group '%s'", wp->config->name, c->listen_group); return -1; } wp->socket_gid = grp->gr_gid; } if (c->listen_mode && *c->listen_mode) { wp->socket_mode = strtoul(c->listen_mode, 0, 8); } return 0; } /* }}} */ Commit Message: Fix bug #67060: use default mode of 660 CWE ID: CWE-264
int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */ { struct fpm_worker_pool_config_s *c = wp->config; /* uninitialized */ wp->socket_uid = -1; wp->socket_gid = -1; wp->socket_mode = 0660; if (!c) { return 0; } if (c->listen_owner && *c->listen_owner) { struct passwd *pwd; pwd = getpwnam(c->listen_owner); if (!pwd) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get uid for user '%s'", wp->config->name, c->listen_owner); return -1; } wp->socket_uid = pwd->pw_uid; wp->socket_gid = pwd->pw_gid; } if (c->listen_group && *c->listen_group) { struct group *grp; grp = getgrnam(c->listen_group); if (!grp) { zlog(ZLOG_SYSERROR, "[pool %s] cannot get gid for group '%s'", wp->config->name, c->listen_group); return -1; } wp->socket_gid = grp->gr_gid; } if (c->listen_mode && *c->listen_mode) { wp->socket_mode = strtoul(c->listen_mode, 0, 8); } return 0; } /* }}} */
166,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AudioInputRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, const std::string& device_id, bool automatic_gain_control) { VLOG(1) << "AudioInputRendererHost::OnCreateStream(stream_id=" << stream_id << ")"; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(LookupById(stream_id) == NULL); media::AudioParameters audio_params(params); if (media_stream_manager_->audio_input_device_manager()-> ShouldUseFakeDevice()) { audio_params.Reset(media::AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } else if (WebContentsCaptureUtil::IsWebContentsDeviceId(device_id)) { audio_params.Reset(media::AudioParameters::AUDIO_VIRTUAL, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } DCHECK_GT(audio_params.frames_per_buffer(), 0); uint32 buffer_size = audio_params.GetBytesPerBuffer(); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 mem_size = sizeof(media::AudioInputBufferParameters) + buffer_size; if (!entry->shared_memory.CreateAndMapAnonymous(mem_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioInputSyncWriter> writer( new AudioInputSyncWriter(&entry->shared_memory)); if (!writer->Init()) { SendErrorMessage(stream_id); return; } entry->writer.reset(writer.release()); entry->controller = media::AudioInputController::CreateLowLatency( audio_manager_, this, audio_params, device_id, entry->writer.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } if (params.format() == media::AudioParameters::AUDIO_PCM_LOW_LATENCY) entry->controller->SetAutomaticGainControl(automatic_gain_control); entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void AudioInputRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, const std::string& device_id, bool automatic_gain_control) { VLOG(1) << "AudioInputRendererHost::OnCreateStream(stream_id=" << stream_id << ")"; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // media::AudioParameters is validated in the deserializer. if (LookupById(stream_id) != NULL) { SendErrorMessage(stream_id); return; } media::AudioParameters audio_params(params); if (media_stream_manager_->audio_input_device_manager()-> ShouldUseFakeDevice()) { audio_params.Reset(media::AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } else if (WebContentsCaptureUtil::IsWebContentsDeviceId(device_id)) { audio_params.Reset(media::AudioParameters::AUDIO_VIRTUAL, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } uint32 buffer_size = audio_params.GetBytesPerBuffer(); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 mem_size = sizeof(media::AudioInputBufferParameters) + buffer_size; if (!entry->shared_memory.CreateAndMapAnonymous(mem_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioInputSyncWriter> writer( new AudioInputSyncWriter(&entry->shared_memory)); if (!writer->Init()) { SendErrorMessage(stream_id); return; } entry->writer.reset(writer.release()); entry->controller = media::AudioInputController::CreateLowLatency( audio_manager_, this, audio_params, device_id, entry->writer.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } if (params.format() == media::AudioParameters::AUDIO_PCM_LOW_LATENCY) entry->controller->SetAutomaticGainControl(automatic_gain_control); entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); }
171,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); } Commit Message: disable loading lua bytecode CWE ID: CWE-17
static void f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = (luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); }
166,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) { if (isUserInteractionEvent(event)) return true; LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject)); if (!slider.isNull() && !slider.inDragMode()) return false; const AtomicString& type = event->type(); return type == EventTypeNames::mouseover || type == EventTypeNames::mouseout || type == EventTypeNames::mousemove; } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} CWE ID: CWE-119
bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) { if (isUserInteractionEvent(event)) return true; LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject)); if (!slider.isNull() && !slider.inDragMode()) return false; const AtomicString& type = event->type(); return type == EventTypeNames::mouseover || type == EventTypeNames::mouseout || type == EventTypeNames::mousemove || type == EventTypeNames::pointerover || type == EventTypeNames::pointerout || type == EventTypeNames::pointermove; }
171,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void btsnoop_net_write(const void *data, size_t length) { #if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE)) return; // Disable using network sockets for security reasons #endif pthread_mutex_lock(&client_socket_lock_); if (client_socket_ != -1) { if (send(client_socket_, data, length, 0) == -1 && errno == ECONNRESET) { safe_close_(&client_socket_); } } pthread_mutex_unlock(&client_socket_lock_); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void btsnoop_net_write(const void *data, size_t length) { #if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE)) return; // Disable using network sockets for security reasons #endif pthread_mutex_lock(&client_socket_lock_); if (client_socket_ != -1) { if (TEMP_FAILURE_RETRY(send(client_socket_, data, length, 0)) == -1 && errno == ECONNRESET) { safe_close_(&client_socket_); } } pthread_mutex_unlock(&client_socket_lock_); }
173,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int do_dentry_open(struct file *f, int (*open)(struct inode *, struct file *), const struct cred *cred) { static const struct file_operations empty_fops = {}; struct inode *inode; int error; f->f_mode = OPEN_FMODE(f->f_flags) | FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE; if (unlikely(f->f_flags & O_PATH)) f->f_mode = FMODE_PATH; path_get(&f->f_path); inode = f->f_inode = f->f_path.dentry->d_inode; if (f->f_mode & FMODE_WRITE) { error = __get_file_write_access(inode, f->f_path.mnt); if (error) goto cleanup_file; if (!special_file(inode->i_mode)) file_take_write(f); } f->f_mapping = inode->i_mapping; file_sb_list_add(f, inode->i_sb); if (unlikely(f->f_mode & FMODE_PATH)) { f->f_op = &empty_fops; return 0; } f->f_op = fops_get(inode->i_fop); if (unlikely(WARN_ON(!f->f_op))) { error = -ENODEV; goto cleanup_all; } error = security_file_open(f, cred); if (error) goto cleanup_all; error = break_lease(inode, f->f_flags); if (error) goto cleanup_all; if (!open) open = f->f_op->open; if (open) { error = open(inode, f); if (error) goto cleanup_all; } if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) i_readcount_inc(inode); f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC); file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping); return 0; cleanup_all: fops_put(f->f_op); file_sb_list_del(f); if (f->f_mode & FMODE_WRITE) { put_write_access(inode); if (!special_file(inode->i_mode)) { /* * We don't consider this a real * mnt_want/drop_write() pair * because it all happenend right * here, so just reset the state. */ file_reset_write(f); __mnt_drop_write(f->f_path.mnt); } } cleanup_file: path_put(&f->f_path); f->f_path.mnt = NULL; f->f_path.dentry = NULL; f->f_inode = NULL; return error; } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
static int do_dentry_open(struct file *f, int (*open)(struct inode *, struct file *), const struct cred *cred) { static const struct file_operations empty_fops = {}; struct inode *inode; int error; f->f_mode = OPEN_FMODE(f->f_flags) | FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE; if (unlikely(f->f_flags & O_PATH)) f->f_mode = FMODE_PATH; path_get(&f->f_path); inode = f->f_inode = f->f_path.dentry->d_inode; if (f->f_mode & FMODE_WRITE) { error = __get_file_write_access(inode, f->f_path.mnt); if (error) goto cleanup_file; if (!special_file(inode->i_mode)) file_take_write(f); } f->f_mapping = inode->i_mapping; if (unlikely(f->f_mode & FMODE_PATH)) { f->f_op = &empty_fops; return 0; } f->f_op = fops_get(inode->i_fop); if (unlikely(WARN_ON(!f->f_op))) { error = -ENODEV; goto cleanup_all; } error = security_file_open(f, cred); if (error) goto cleanup_all; error = break_lease(inode, f->f_flags); if (error) goto cleanup_all; if (!open) open = f->f_op->open; if (open) { error = open(inode, f); if (error) goto cleanup_all; } if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) i_readcount_inc(inode); f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC); file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping); return 0; cleanup_all: fops_put(f->f_op); if (f->f_mode & FMODE_WRITE) { put_write_access(inode); if (!special_file(inode->i_mode)) { /* * We don't consider this a real * mnt_want/drop_write() pair * because it all happenend right * here, so just reset the state. */ file_reset_write(f); __mnt_drop_write(f->f_path.mnt); } } cleanup_file: path_put(&f->f_path); f->f_path.mnt = NULL; f->f_path.dentry = NULL; f->f_inode = NULL; return error; }
166,805
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ParseRequestInfo(const struct mg_request_info* const request_info, std::string* method, std::vector<std::string>* path_segments, DictionaryValue** parameters, Response* const response) { *method = request_info->request_method; if (*method == "HEAD") *method = "GET"; else if (*method == "PUT") *method = "POST"; std::string uri(request_info->uri); SessionManager* manager = SessionManager::GetInstance(); uri = uri.substr(manager->url_base().length()); base::SplitString(uri, '/', path_segments); if (*method == "POST" && request_info->post_data_len > 0) { VLOG(1) << "...parsing request body"; std::string json(request_info->post_data, request_info->post_data_len); std::string error; if (!ParseJSONDictionary(json, parameters, &error)) { response->SetError(new Error( kBadRequest, "Failed to parse command data: " + error + "\n Data: " + json)); return false; } } VLOG(1) << "Parsed " << method << " " << uri << std::string(request_info->post_data, request_info->post_data_len); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ParseRequestInfo(const struct mg_request_info* const request_info, std::string* method, std::vector<std::string>* path_segments, DictionaryValue** parameters, Response* const response) { *method = request_info->request_method; if (*method == "HEAD") *method = "GET"; else if (*method == "PUT") *method = "POST"; std::string uri(request_info->uri); SessionManager* manager = SessionManager::GetInstance(); uri = uri.substr(manager->url_base().length()); base::SplitString(uri, '/', path_segments); if (*method == "POST" && request_info->post_data_len > 0) { std::string json(request_info->post_data, request_info->post_data_len); std::string error_msg; scoped_ptr<Value> params(base::JSONReader::ReadAndReturnError( json, true, NULL, &error_msg)); if (!params.get()) { response->SetError(new Error( kBadRequest, "Failed to parse command data: " + error_msg + "\n Data: " + json)); return false; } if (!params->IsType(Value::TYPE_DICTIONARY)) { response->SetError(new Error( kBadRequest, "Data passed in URL must be a dictionary. Data: " + json)); return false; } *parameters = static_cast<DictionaryValue*>(params.release()); } return true; }
170,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Get(const std::string& addr, int* out_value) { base::AutoLock lock(lock_); PrintPreviewRequestIdMap::const_iterator it = map_.find(addr); if (it == map_.end()) return false; *out_value = it->second; return true; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
bool Get(const std::string& addr, int* out_value) { // Gets the value for |preview_id|. // Returns true and sets |out_value| on success. bool Get(int32 preview_id, int* out_value) { base::AutoLock lock(lock_); PrintPreviewRequestIdMap::const_iterator it = map_.find(preview_id); if (it == map_.end()) return false; *out_value = it->second; return true; }
170,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } } Commit Message: Fix bug #72749: wddx_deserialize allows illegal memory access CWE ID: CWE-20
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; if (Z_TYPE_P(ent->data) == IS_STRING) { tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1); memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data)); memcpy(tmp + Z_STRLEN_P(ent->data), s, len); len += Z_STRLEN_P(ent->data); efree(Z_STRVAL_P(ent->data)); Z_TYPE_P(ent->data) = IS_LONG; } else { tmp = emalloc(len + 1); memcpy(tmp, s, len); } tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { ZVAL_STRINGL(ent->data, tmp, len, 0); } else { efree(tmp); } } break; default: break; } } }
166,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SecureProxyChecker::SecureProxyChecker( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : url_loader_factory_(std::move(url_loader_factory)) {} Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
SecureProxyChecker::SecureProxyChecker( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
172,423
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t StringSize(const uint8_t *start, uint8_t encoding) { //// return includes terminator; if unterminated, returns > limit if (encoding == 0x00 || encoding == 0x03) { return strlen((const char *)start) + 1; } size_t n = 0; while (start[n] != '\0' || start[n + 1] != '\0') { n += 2; } return n + 2; } Commit Message: DO NOT MERGE: defensive parsing of mp3 album art information several points in stagefrights mp3 album art code used strlen() to parse user-supplied strings that may be unterminated, resulting in reading beyond the end of a buffer. This changes the code to use strnlen() for 8-bit encodings and strengthens the parsing of 16-bit encodings similarly. It also reworks how we watch for the end-of-buffer to avoid all over-reads. Bug: 32377688 Test: crafted mp3's w/ good/bad cover art. See what showed in play music Change-Id: Ia9f526d71b21ef6a61acacf616b573753cd21df6 (cherry picked from commit fa0806b594e98f1aed3ebcfc6a801b4c0056f9eb) CWE ID: CWE-200
static size_t StringSize(const uint8_t *start, uint8_t encoding) { //// return includes terminator; if unterminated, returns > limit static size_t StringSize(const uint8_t *start, size_t limit, uint8_t encoding) { if (encoding == 0x00 || encoding == 0x03) { return strnlen((const char *)start, limit) + 1; } size_t n = 0; while ((n+1 < limit) && (start[n] != '\0' || start[n + 1] != '\0')) { n += 2; } n += 2; return n; }
174,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key()
167,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigationControllerImpl::Reload(ReloadType reload_type, bool check_for_repost) { DCHECK_NE(ReloadType::NONE, reload_type); if (transient_entry_index_ != -1) { NavigationEntryImpl* transient_entry = GetTransientEntry(); if (!transient_entry) return; LoadURL(transient_entry->GetURL(), Referrer(), ui::PAGE_TRANSITION_RELOAD, transient_entry->extra_headers()); return; } NavigationEntryImpl* entry = nullptr; int current_index = -1; if (IsInitialNavigation() && pending_entry_) { entry = pending_entry_; current_index = pending_entry_index_; } else { DiscardNonCommittedEntriesInternal(); current_index = GetCurrentEntryIndex(); if (current_index != -1) { entry = GetEntryAtIndex(current_index); } } if (!entry) return; if (last_committed_reload_type_ != ReloadType::NONE) { DCHECK(!last_committed_reload_time_.is_null()); base::Time now = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DCHECK_GT(now, last_committed_reload_time_); if (!last_committed_reload_time_.is_null() && now > last_committed_reload_time_) { base::TimeDelta delta = now - last_committed_reload_time_; UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration", delta); if (last_committed_reload_type_ == ReloadType::NORMAL) { UMA_HISTOGRAM_MEDIUM_TIMES( "Navigation.Reload.ReloadMainResourceToReloadDuration", delta); } } } entry->set_reload_type(reload_type); if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) { delegate_->NotifyBeforeFormRepostWarningShow(); pending_reload_ = reload_type; delegate_->ActivateAndShowRepostFormWarningDialog(); } else { if (!IsInitialNavigation()) DiscardNonCommittedEntriesInternal(); SiteInstanceImpl* site_instance = entry->site_instance(); bool is_for_guests_only = site_instance && site_instance->HasProcess() && site_instance->GetProcess()->IsForGuestsOnly(); if (!is_for_guests_only && site_instance && site_instance->HasWrongProcessForURL(entry->GetURL())) { NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry( CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(), false, entry->extra_headers(), browser_context_, nullptr /* blob_url_loader_factory */) .release()); reload_type = ReloadType::NONE; nav_entry->set_should_replace_entry(true); pending_entry_ = nav_entry; DCHECK_EQ(-1, pending_entry_index_); } else { pending_entry_ = entry; pending_entry_index_ = current_index; pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD); } NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */); } } Commit Message: Preserve renderer-initiated bit when reloading in a new process. BUG=847718 TEST=See bug for repro steps. Change-Id: I6c3461793fbb23f1a4d731dc27b4e77312f29227 Reviewed-on: https://chromium-review.googlesource.com/1080235 Commit-Queue: Charlie Reis <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#563312} CWE ID:
void NavigationControllerImpl::Reload(ReloadType reload_type, bool check_for_repost) { DCHECK_NE(ReloadType::NONE, reload_type); if (transient_entry_index_ != -1) { NavigationEntryImpl* transient_entry = GetTransientEntry(); if (!transient_entry) return; LoadURL(transient_entry->GetURL(), Referrer(), ui::PAGE_TRANSITION_RELOAD, transient_entry->extra_headers()); return; } NavigationEntryImpl* entry = nullptr; int current_index = -1; if (IsInitialNavigation() && pending_entry_) { entry = pending_entry_; current_index = pending_entry_index_; } else { DiscardNonCommittedEntriesInternal(); current_index = GetCurrentEntryIndex(); if (current_index != -1) { entry = GetEntryAtIndex(current_index); } } if (!entry) return; if (last_committed_reload_type_ != ReloadType::NONE) { DCHECK(!last_committed_reload_time_.is_null()); base::Time now = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DCHECK_GT(now, last_committed_reload_time_); if (!last_committed_reload_time_.is_null() && now > last_committed_reload_time_) { base::TimeDelta delta = now - last_committed_reload_time_; UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration", delta); if (last_committed_reload_type_ == ReloadType::NORMAL) { UMA_HISTOGRAM_MEDIUM_TIMES( "Navigation.Reload.ReloadMainResourceToReloadDuration", delta); } } } entry->set_reload_type(reload_type); if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) { delegate_->NotifyBeforeFormRepostWarningShow(); pending_reload_ = reload_type; delegate_->ActivateAndShowRepostFormWarningDialog(); } else { if (!IsInitialNavigation()) DiscardNonCommittedEntriesInternal(); SiteInstanceImpl* site_instance = entry->site_instance(); bool is_for_guests_only = site_instance && site_instance->HasProcess() && site_instance->GetProcess()->IsForGuestsOnly(); if (!is_for_guests_only && site_instance && site_instance->HasWrongProcessForURL(entry->GetURL())) { NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry( CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(), false, entry->extra_headers(), browser_context_, nullptr /* blob_url_loader_factory */) .release()); reload_type = ReloadType::NONE; nav_entry->set_should_replace_entry(true); nav_entry->set_is_renderer_initiated(entry->is_renderer_initiated()); pending_entry_ = nav_entry; DCHECK_EQ(-1, pending_entry_index_); } else { pending_entry_ = entry; pending_entry_index_ = current_index; pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD); } NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */); } }
173,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunInvAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, in, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, coeff, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); in[j] = src[j] - dst[j]; } fwd_txfm_ref(in, coeff, pitch_, tx_type_); REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; EXPECT_GE(1u, error) << "Error: 16x16 IDCT has error " << error << " at index " << j; } } } 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 RunInvAccuracyCheck() { void RunInvAccuracyCheck(int limit) { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, in[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]); #endif 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) { if (bit_depth_ == VPX_BITS_8) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); in[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { src16[j] = rnd.Rand16() & mask_; dst16[j] = rnd.Rand16() & mask_; in[j] = src16[j] - dst16[j]; #endif } } fwd_txfm_ref(in, coeff, pitch_, tx_type_); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < kNumCoeffs; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const uint32_t diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else const uint32_t diff = dst[j] - src[j]; #endif const uint32_t error = diff * diff; EXPECT_GE(static_cast<uint32_t>(limit), error) << "Error: 4x4 IDCT has error " << error << " at index " << j; } } }
174,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunCallbacksWithDisabled(LogoCallbacks callbacks) { if (callbacks.on_cached_encoded_logo_available) { std::move(callbacks.on_cached_encoded_logo_available) .Run(LogoCallbackReason::DISABLED, base::nullopt); } if (callbacks.on_cached_decoded_logo_available) { std::move(callbacks.on_cached_decoded_logo_available) .Run(LogoCallbackReason::DISABLED, base::nullopt); } if (callbacks.on_fresh_encoded_logo_available) { std::move(callbacks.on_fresh_encoded_logo_available) .Run(LogoCallbackReason::DISABLED, base::nullopt); } if (callbacks.on_fresh_decoded_logo_available) { std::move(callbacks.on_fresh_decoded_logo_available) .Run(LogoCallbackReason::DISABLED, base::nullopt); } } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void RunCallbacksWithDisabled(LogoCallbacks callbacks) {
171,958
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuVideoDecodeAccelerator::OnDecode( base::SharedMemoryHandle handle, int32 id, int32 size) { DCHECK(video_decode_accelerator_.get()); video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size)); } Commit Message: Sizes going across an IPC should be uint32. BUG=164946 Review URL: https://chromiumcodereview.appspot.com/11472038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuVideoDecodeAccelerator::OnDecode( base::SharedMemoryHandle handle, int32 id, uint32 size) { DCHECK(video_decode_accelerator_.get()); video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size)); }
171,407
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-264
check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; err = xt_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
167,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WindowOpenDisposition TestBrowserWindow::GetDispositionForPopupBounds( const gfx::Rect& bounds) { return WindowOpenDisposition::NEW_POPUP; } 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 <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20
WindowOpenDisposition TestBrowserWindow::GetDispositionForPopupBounds(
173,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tmsize_t stride = sp->stride; uint16 *wp = (uint16*) cp0; tmsize_t wc = cc/2; assert((cc%(2*stride))==0); if (wc > stride) { wc -= stride; wp += wc - 1; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--) wc -= stride; } while (wc > 0); } } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tmsize_t stride = sp->stride; uint16 *wp = (uint16*) cp0; tmsize_t wc = cc/2; if((cc%(2*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "horDiff8", "%s", "(cc%(2*stride))!=0"); return 0; } if (wc > stride) { wc -= stride; wp += wc - 1; do { REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--) wc -= stride; } while (wc > 0); } return 1; }
166,885
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_@_add(image_transform *this, PNG_CONST image_transform **that, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { this->next = *that; *that = this; *pos = safecat(name, sizeof_name, *pos, " +@"); return 1; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_@_add(image_transform *this,
173,600
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PasswordAutofillAgent::TryToShowTouchToFill( const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); if (!element || (!base::Contains(web_input_to_password_info_, *element) && !base::Contains(password_to_username_, *element))) { return false; } if (was_touch_to_fill_ui_shown_) return false; was_touch_to_fill_ui_shown_ = true; GetPasswordManagerDriver()->ShowTouchToFill(); return true; } Commit Message: [Android][TouchToFill] Use FindPasswordInfoForElement for triggering Use for TouchToFill the same triggering logic that is used for regular suggestions. Bug: 1010233 Change-Id: I111d4eac4ce94dd94b86097b6b6c98e08875e11a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1834230 Commit-Queue: Boris Sazonov <[email protected]> Reviewed-by: Vadym Doroshenko <[email protected]> Cr-Commit-Position: refs/heads/master@{#702058} CWE ID: CWE-125
bool PasswordAutofillAgent::TryToShowTouchToFill( const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); WebInputElement username_element; WebInputElement password_element; PasswordInfo* password_info = nullptr; if (!element || !FindPasswordInfoForElement(*element, &username_element, &password_element, &password_info)) { return false; } if (was_touch_to_fill_ui_shown_) return false; was_touch_to_fill_ui_shown_ = true; GetPasswordManagerDriver()->ShowTouchToFill(); return true; }
172,407
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ThreadableBlobRegistry::finalizeStream(const KURL& url) { if (isMainThread()) { blobRegistry().finalizeStream(url); } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url)); callOnMainThread(&finalizeStreamTask, 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::finalizeStream(const KURL& url) void BlobRegistry::finalizeStream(const KURL& url) { if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) registry->finalizeStream(url); } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url)); callOnMainThread(&finalizeStreamTask, context.leakPtr()); } }
170,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) { } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
174,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system, ScriptContext* context, Dispatcher* dispatcher, RequestSender* request_sender, V8SchemaRegistry* v8_schema_registry) { module_system->RegisterNativeHandler( "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context))); module_system->RegisterNativeHandler( "lazy_background_page", scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context))); module_system->RegisterNativeHandler( "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context))); module_system->RegisterNativeHandler("schema_registry", v8_schema_registry->AsNativeHandler()); module_system->RegisterNativeHandler( "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context))); module_system->RegisterNativeHandler( "test_features", scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context))); module_system->RegisterNativeHandler( "test_native_handler", scoped_ptr<NativeHandler>(new TestNativeHandler(context))); module_system->RegisterNativeHandler( "user_gestures", scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context))); module_system->RegisterNativeHandler( "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context))); module_system->RegisterNativeHandler( "v8_context", scoped_ptr<NativeHandler>(new V8ContextNativeHandler(context))); module_system->RegisterNativeHandler( "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context))); module_system->RegisterNativeHandler( "messaging_natives", scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context))); module_system->RegisterNativeHandler( "apiDefinitions", scoped_ptr<NativeHandler>( new ApiDefinitionsNatives(dispatcher, context))); module_system->RegisterNativeHandler( "sendRequest", scoped_ptr<NativeHandler>( new SendRequestNatives(request_sender, context))); module_system->RegisterNativeHandler( "setIcon", scoped_ptr<NativeHandler>(new SetIconNatives(context))); module_system->RegisterNativeHandler( "activityLogger", scoped_ptr<NativeHandler>(new APIActivityLogger(context))); module_system->RegisterNativeHandler( "renderFrameObserverNatives", scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context))); module_system->RegisterNativeHandler( "file_system_natives", scoped_ptr<NativeHandler>(new FileSystemNatives(context))); module_system->RegisterNativeHandler( "app_window_natives", scoped_ptr<NativeHandler>(new AppWindowCustomBindings(context))); module_system->RegisterNativeHandler( "blob_natives", scoped_ptr<NativeHandler>(new BlobNativeHandler(context))); module_system->RegisterNativeHandler( "context_menus", scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context))); module_system->RegisterNativeHandler( "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context))); module_system->RegisterNativeHandler( "document_natives", scoped_ptr<NativeHandler>(new DocumentCustomBindings(context))); module_system->RegisterNativeHandler( "guest_view_internal", scoped_ptr<NativeHandler>( new GuestViewInternalCustomBindings(context))); module_system->RegisterNativeHandler( "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context))); module_system->RegisterNativeHandler( "id_generator", scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context))); module_system->RegisterNativeHandler( "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context))); module_system->RegisterNativeHandler( "display_source", scoped_ptr<NativeHandler>(new DisplaySourceCustomBindings(context))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system, ScriptContext* context, Dispatcher* dispatcher, RequestSender* request_sender, V8SchemaRegistry* v8_schema_registry) { module_system->RegisterNativeHandler( "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context))); module_system->RegisterNativeHandler( "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context))); module_system->RegisterNativeHandler("schema_registry", v8_schema_registry->AsNativeHandler()); module_system->RegisterNativeHandler( "test_features", scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context))); module_system->RegisterNativeHandler( "test_native_handler", scoped_ptr<NativeHandler>(new TestNativeHandler(context))); module_system->RegisterNativeHandler( "user_gestures", scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context))); module_system->RegisterNativeHandler( "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context))); module_system->RegisterNativeHandler( "v8_context", scoped_ptr<NativeHandler>(new V8ContextNativeHandler(context))); module_system->RegisterNativeHandler( "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context))); module_system->RegisterNativeHandler( "messaging_natives", scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context))); module_system->RegisterNativeHandler( "apiDefinitions", scoped_ptr<NativeHandler>( new ApiDefinitionsNatives(dispatcher, context))); module_system->RegisterNativeHandler( "sendRequest", scoped_ptr<NativeHandler>( new SendRequestNatives(request_sender, context))); module_system->RegisterNativeHandler( "setIcon", scoped_ptr<NativeHandler>(new SetIconNatives(context))); module_system->RegisterNativeHandler( "activityLogger", scoped_ptr<NativeHandler>(new APIActivityLogger(context))); module_system->RegisterNativeHandler( "renderFrameObserverNatives", scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context))); module_system->RegisterNativeHandler( "file_system_natives", scoped_ptr<NativeHandler>(new FileSystemNatives(context))); module_system->RegisterNativeHandler( "app_window_natives", scoped_ptr<NativeHandler>(new AppWindowCustomBindings(context))); module_system->RegisterNativeHandler( "blob_natives", scoped_ptr<NativeHandler>(new BlobNativeHandler(context))); module_system->RegisterNativeHandler( "context_menus", scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context))); module_system->RegisterNativeHandler( "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context))); module_system->RegisterNativeHandler( "document_natives", scoped_ptr<NativeHandler>(new DocumentCustomBindings(context))); module_system->RegisterNativeHandler( "guest_view_internal", scoped_ptr<NativeHandler>( new GuestViewInternalCustomBindings(context))); module_system->RegisterNativeHandler( "id_generator", scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context))); module_system->RegisterNativeHandler( "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context))); module_system->RegisterNativeHandler( "display_source", scoped_ptr<NativeHandler>(new DisplaySourceCustomBindings(context))); }
172,247
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BluetoothDeviceChooserController::~BluetoothDeviceChooserController() { if (scanning_start_time_) { RecordScanningDuration(base::TimeTicks::Now() - scanning_start_time_.value()); } if (chooser_) { DCHECK(!error_callback_.is_null()); error_callback_.Run(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); } } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
BluetoothDeviceChooserController::~BluetoothDeviceChooserController() { if (scanning_start_time_) { RecordScanningDuration(base::TimeTicks::Now() - scanning_start_time_.value()); } if (chooser_) { DCHECK(!error_callback_.is_null()); error_callback_.Run(WebBluetoothResult::CHOOSER_CANCELLED); } }
172,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id, quic::QuicSession* session) : quic::QuicStream(id, session, /*is_static=*/false, quic::BIDIRECTIONAL) {} 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 <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
172,263
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void *arm_coherent_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, true, __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 <[email protected]> CWE ID: CWE-264
static void *arm_coherent_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, true, __builtin_return_address(0)); }
167,577
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels* next_image->columns,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } Commit Message: Fixed overflow. CWE ID: CWE-125
static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); }
170,118
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OmniboxPopupViewGtk::~OmniboxPopupViewGtk() { model_.reset(); g_object_unref(layout_); gtk_widget_destroy(window_); for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it) delete it->second; } Commit Message: GTK: Stop listening to gtk signals in the omnibox before destroying the model. BUG=123530 TEST=none Review URL: http://codereview.chromium.org/10103012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132498 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
OmniboxPopupViewGtk::~OmniboxPopupViewGtk() { // Stop listening to our signals before we destroy the model. I suspect that // we can race window destruction, otherwise. signal_registrar_.reset(); model_.reset(); g_object_unref(layout_); gtk_widget_destroy(window_); for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it) delete it->second; }
171,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint8_t* FAST_FUNC udhcp_get_option32(struct dhcp_packet *packet, int code) { uint8_t *r = udhcp_get_option(packet, code); if (r) { if (r[-1] != 4) r = NULL; } return r; } Commit Message: CWE ID: CWE-125
uint8_t* FAST_FUNC udhcp_get_option32(struct dhcp_packet *packet, int code) { uint8_t *r = udhcp_get_option(packet, code); if (r) { if (r[-OPT_DATA + OPT_LEN] != 4) r = NULL; } return r; }
164,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScrollAnchor::ExamineResult ScrollAnchor::Examine( const LayoutObject* candidate) const { if (candidate == ScrollerLayoutBox(scroller_)) return ExamineResult(kContinue); if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone) return ExamineResult(kSkip); if (candidate->IsLayoutInline()) return ExamineResult(kContinue); if (candidate->IsAnonymous()) return ExamineResult(kContinue); if (!candidate->IsText() && !candidate->IsBox()) return ExamineResult(kSkip); if (!CandidateMayMoveWithScroller(candidate, scroller_)) return ExamineResult(kSkip); LayoutRect candidate_rect = RelativeBounds(candidate, scroller_); LayoutRect visible_rect = ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint()); bool occupies_space = candidate_rect.Width() > 0 && candidate_rect.Height() > 0; if (occupies_space && visible_rect.Intersects(candidate_rect)) { return ExamineResult( visible_rect.Contains(candidate_rect) ? kReturn : kConstrain, CornerToAnchor(scroller_)); } else { return ExamineResult(kSkip); } } Commit Message: Consider scroll-padding when determining scroll anchor node Scroll anchoring should not anchor to a node that is behind scroll padding. Bug: 1010002 Change-Id: Icbd89fb85ea2c97a6de635930a9896f6a87b8f07 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1887745 Reviewed-by: Chris Harrelson <[email protected]> Commit-Queue: Nick Burris <[email protected]> Cr-Commit-Position: refs/heads/master@{#711020} CWE ID:
ScrollAnchor::ExamineResult ScrollAnchor::Examine( const LayoutObject* candidate) const { if (candidate == ScrollerLayoutBox(scroller_)) return ExamineResult(kContinue); if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone) return ExamineResult(kSkip); if (candidate->IsLayoutInline()) return ExamineResult(kContinue); if (candidate->IsAnonymous()) return ExamineResult(kContinue); if (!candidate->IsText() && !candidate->IsBox()) return ExamineResult(kSkip); if (!CandidateMayMoveWithScroller(candidate, scroller_)) return ExamineResult(kSkip); LayoutRect candidate_rect = RelativeBounds(candidate, scroller_); LayoutRect visible_rect = ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint()); const ComputedStyle* style = ScrollerLayoutBox(scroller_)->Style(); LayoutRectOutsets scroll_padding( MinimumValueForLength(style->ScrollPaddingTop(), visible_rect.Height()), MinimumValueForLength(style->ScrollPaddingRight(), visible_rect.Width()), MinimumValueForLength(style->ScrollPaddingBottom(), visible_rect.Height()), MinimumValueForLength(style->ScrollPaddingLeft(), visible_rect.Width())); visible_rect.Contract(scroll_padding); bool occupies_space = candidate_rect.Width() > 0 && candidate_rect.Height() > 0; if (occupies_space && visible_rect.Intersects(candidate_rect)) { return ExamineResult( visible_rect.Contains(candidate_rect) ? kReturn : kConstrain, CornerToAnchor(scroller_)); } else { return ExamineResult(kSkip); } }
172,383
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderFrameHostManager::GetSiteInstanceForNavigationRequest( const NavigationRequest& request) { SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); bool no_renderer_swap_allowed = false; bool was_server_redirect = request.navigation_handle() && request.navigation_handle()->WasServerRedirect(); if (frame_tree_node_->IsMainFrame()) { bool can_renderer_initiate_transfer = (request.state() == NavigationRequest::FAILED && SiteIsolationPolicy::IsErrorPageIsolationEnabled( true /* in_main_frame */)) || (render_frame_host_->IsRenderFrameLive() && IsURLHandledByNetworkStack(request.common_params().url) && IsRendererTransferNeededForNavigation(render_frame_host_.get(), request.common_params().url)); no_renderer_swap_allowed |= request.from_begin_navigation() && !can_renderer_initiate_transfer; } else { no_renderer_swap_allowed |= !CanSubframeSwapProcess( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), was_server_redirect); } if (no_renderer_swap_allowed) return scoped_refptr<SiteInstance>(current_site_instance); SiteInstance* candidate_site_instance = speculative_render_frame_host_ ? speculative_render_frame_host_->GetSiteInstance() : nullptr; scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), candidate_site_instance, request.common_params().transition, request.state() == NavigationRequest::FAILED, request.restore_type() != RestoreType::NONE, request.is_view_source(), was_server_redirect); return dest_site_instance; } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
RenderFrameHostManager::GetSiteInstanceForNavigationRequest( const NavigationRequest& request) { SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); bool no_renderer_swap_allowed = false; bool was_server_redirect = request.navigation_handle() && request.navigation_handle()->WasServerRedirect(); if (frame_tree_node_->IsMainFrame()) { bool can_renderer_initiate_transfer = (request.state() == NavigationRequest::FAILED && SiteIsolationPolicy::IsErrorPageIsolationEnabled( true /* in_main_frame */)) || (render_frame_host_->IsRenderFrameLive() && IsURLHandledByNetworkStack(request.common_params().url) && IsRendererTransferNeededForNavigation(render_frame_host_.get(), request.common_params().url)); no_renderer_swap_allowed |= request.from_begin_navigation() && !can_renderer_initiate_transfer; } else { no_renderer_swap_allowed |= !CanSubframeSwapProcess( request.common_params().url, request.source_site_instance(), request.dest_site_instance()); } if (no_renderer_swap_allowed) return scoped_refptr<SiteInstance>(current_site_instance); SiteInstance* candidate_site_instance = speculative_render_frame_host_ ? speculative_render_frame_host_->GetSiteInstance() : nullptr; scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), candidate_site_instance, request.common_params().transition, request.state() == NavigationRequest::FAILED, request.restore_type() != RestoreType::NONE, request.is_view_source(), was_server_redirect); return dest_site_instance; }
173,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CheckClientDownloadRequest::UploadBinary( DownloadCheckResult result, DownloadCheckResultReason reason) { saved_result_ = result; saved_reason_ = reason; bool upload_for_dlp = ShouldUploadForDlpScan(); bool upload_for_malware = ShouldUploadForMalwareScan(reason); auto request = std::make_unique<DownloadItemRequest>( item_, /*read_immediately=*/true, base::BindOnce(&CheckClientDownloadRequest::OnDeepScanningComplete, weakptr_factory_.GetWeakPtr())); Profile* profile = Profile::FromBrowserContext(GetBrowserContext()); if (upload_for_dlp) { DlpDeepScanningClientRequest dlp_request; dlp_request.set_content_source(DlpDeepScanningClientRequest::FILE_DOWNLOAD); request->set_request_dlp_scan(std::move(dlp_request)); } if (upload_for_malware) { MalwareDeepScanningClientRequest malware_request; malware_request.set_population( MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE); malware_request.set_download_token( DownloadProtectionService::GetDownloadPingToken(item_)); request->set_request_malware_scan(std::move(malware_request)); } request->set_dm_token( policy::BrowserDMTokenStorage::Get()->RetrieveDMToken()); service()->UploadForDeepScanning(profile, std::move(request)); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
void CheckClientDownloadRequest::UploadBinary( DownloadCheckResult result, DownloadCheckResultReason reason) { saved_result_ = result; saved_reason_ = reason; bool upload_for_dlp = ShouldUploadForDlpScan(); bool upload_for_malware = ShouldUploadForMalwareScan(reason); auto request = std::make_unique<DownloadItemRequest>( item_, /*read_immediately=*/true, base::BindOnce(&CheckClientDownloadRequest::OnDeepScanningComplete, weakptr_factory_.GetWeakPtr())); Profile* profile = Profile::FromBrowserContext(GetBrowserContext()); if (upload_for_dlp) { DlpDeepScanningClientRequest dlp_request; dlp_request.set_content_source(DlpDeepScanningClientRequest::FILE_DOWNLOAD); request->set_request_dlp_scan(std::move(dlp_request)); } if (upload_for_malware) { MalwareDeepScanningClientRequest malware_request; malware_request.set_population( MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE); malware_request.set_download_token( DownloadProtectionService::GetDownloadPingToken(item_)); request->set_request_malware_scan(std::move(malware_request)); } auto dm_token = BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken(); DCHECK(dm_token.is_valid()); request->set_dm_token(dm_token.value()); service()->UploadForDeepScanning(profile, std::move(request)); }
172,358
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } Commit Message: Security: update Lua struct package for security. During an auditing Apple found that the "struct" Lua package we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains a security problem. A bound-checking statement fails because of integer overflow. The bug exists since we initially integrated this package with Lua, when scripting was introduced, so every version of Redis with EVAL/EVALSHA capabilities exposed is affected. Instead of just fixing the bug, the library was updated to the latest version shipped by the author. CWE ID: CWE-190
static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } }
170,164
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SiteInstanceImpl::ShouldLockToOrigin(BrowserContext* browser_context, GURL site_url) { if (RenderProcessHost::run_renderer_in_process()) return false; if (!DoesSiteRequireDedicatedProcess(browser_context, site_url)) return false; if (site_url.SchemeIs(content::kGuestScheme)) return false; if (site_url.SchemeIs(content::kChromeUIScheme)) return false; if (!GetContentClient()->browser()->ShouldLockToOrigin(browser_context, site_url)) { return false; } return true; } Commit Message: Allow origin lock for WebUI pages. Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps to keep enforcing a SiteInstance swap during chrome://foo -> chrome://bar navigation, even after relaxing BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost (see https://crrev.com/c/783470 for that fixes process sharing in isolated(b(c),d(c)) scenario). I've manually tested this CL by visiting the following URLs: - chrome://welcome/ - chrome://settings - chrome://extensions - chrome://history - chrome://help and chrome://chrome (both redirect to chrome://settings/help) Bug: 510588, 847127 Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971 Reviewed-on: https://chromium-review.googlesource.com/1237392 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: François Doray <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#595259} CWE ID: CWE-119
bool SiteInstanceImpl::ShouldLockToOrigin(BrowserContext* browser_context, GURL site_url) { if (RenderProcessHost::run_renderer_in_process()) return false; if (!DoesSiteRequireDedicatedProcess(browser_context, site_url)) return false; if (site_url.SchemeIs(content::kGuestScheme)) return false; if (!GetContentClient()->browser()->ShouldLockToOrigin(browser_context, site_url)) { return false; } return true; }
173,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual size_t GetNumActiveInputMethods() { scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods()); return descriptors->size(); } 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 size_t GetNumActiveInputMethods() { scoped_ptr<input_method::InputMethodDescriptors> descriptors( GetActiveInputMethods()); return descriptors->size(); }
170,491
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size) { unsigned int u = 0; LineContribType *res; int overflow_error = 0; res = (LineContribType *) gdMalloc(sizeof(LineContribType)); if (!res) { return NULL; } res->WindowSize = windows_size; res->LineLength = line_length; if (overflow2(line_length, sizeof(ContributionType))) { gdFree(res); return NULL; } res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType)); if (res->ContribRow == NULL) { gdFree(res); return NULL; } for (u = 0 ; u < line_length ; u++) { if (overflow2(windows_size, sizeof(double))) { overflow_error = 1; } else { res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double)); } if (overflow_error == 1 || res->ContribRow[u].Weights == NULL) { unsigned int i; u--; for (i=0;i<=u;i++) { gdFree(res->ContribRow[i].Weights); } gdFree(res->ContribRow); gdFree(res); return NULL; } } return res; } Commit Message: Fix potential unsigned underflow No need to decrease `u`, so we don't do it. While we're at it, we also factor out the overflow check of the loop, what improves performance and readability. This issue has been reported by Stefan Esser to [email protected]. CWE ID: CWE-191
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size) { unsigned int u = 0; LineContribType *res; size_t weights_size; if (overflow2(windows_size, sizeof(double))) { return NULL; } else { weights_size = windows_size * sizeof(double); } res = (LineContribType *) gdMalloc(sizeof(LineContribType)); if (!res) { return NULL; } res->WindowSize = windows_size; res->LineLength = line_length; if (overflow2(line_length, sizeof(ContributionType))) { gdFree(res); return NULL; } res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType)); if (res->ContribRow == NULL) { gdFree(res); return NULL; } for (u = 0 ; u < line_length ; u++) { res->ContribRow[u].Weights = (double *) gdMalloc(weights_size); if (res->ContribRow[u].Weights == NULL) { unsigned int i; for (i=0;i<u;i++) { gdFree(res->ContribRow[i].Weights); } gdFree(res->ContribRow); gdFree(res); return NULL; } } return res; }
168,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Reject fonts with invalid ranges in cmap A corrupt or malicious font may have a negative size in its cmap range, which in turn could lead to memory corruption. This patch detects the case and rejects the font, and also includes an assertion in the sparse bit set implementation if we missed any such case. External issue: https://code.google.com/p/android/issues/detail?id=192618 Bug: 26413177 Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2 CWE ID: CWE-20
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { // invalid group range: size must be positive return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
174,234
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IW_IMPL(unsigned int) iw_get_ui32be(const iw_byte *b) { return (b[0]<<24) | (b[1]<<16) | (b[2]<<8) | b[3]; } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682
IW_IMPL(unsigned int) iw_get_ui32be(const iw_byte *b) { return ((unsigned int)b[0]<<24) | ((unsigned int)b[1]<<16) | ((unsigned int)b[2]<<8) | (unsigned int)b[3]; }
168,199
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void bgp_packet_mpattr_tea(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, uint8_t attrtype) { unsigned int attrlenfield = 0; unsigned int attrhdrlen = 0; struct bgp_attr_encap_subtlv *subtlvs; struct bgp_attr_encap_subtlv *st; const char *attrname; if (!attr || (attrtype == BGP_ATTR_ENCAP && (!attr->encap_tunneltype || attr->encap_tunneltype == BGP_ENCAP_TYPE_MPLS))) return; switch (attrtype) { case BGP_ATTR_ENCAP: attrname = "Tunnel Encap"; subtlvs = attr->encap_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; /* * The tunnel encap attr has an "outer" tlv. * T = tunneltype, * L = total length of subtlvs, * V = concatenated subtlvs. */ attrlenfield = 2 + 2; /* T + L */ attrhdrlen = 1 + 1; /* subTLV T + L */ break; #if ENABLE_BGP_VNC case BGP_ATTR_VNC: attrname = "VNC"; subtlvs = attr->vnc_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; attrlenfield = 0; /* no outer T + L */ attrhdrlen = 2 + 2; /* subTLV T + L */ break; #endif default: assert(0); } /* compute attr length */ for (st = subtlvs; st; st = st->next) { attrlenfield += (attrhdrlen + st->length); } if (attrlenfield > 0xffff) { zlog_info("%s attribute is too long (length=%d), can't send it", attrname, attrlenfield); return; } if (attrlenfield > 0xff) { /* 2-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, attrtype); stream_putw(s, attrlenfield & 0xffff); } else { /* 1-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, attrtype); stream_putc(s, attrlenfield & 0xff); } if (attrtype == BGP_ATTR_ENCAP) { /* write outer T+L */ stream_putw(s, attr->encap_tunneltype); stream_putw(s, attrlenfield - 4); } /* write each sub-tlv */ for (st = subtlvs; st; st = st->next) { if (attrtype == BGP_ATTR_ENCAP) { stream_putc(s, st->type); stream_putc(s, st->length); #if ENABLE_BGP_VNC } else { stream_putw(s, st->type); stream_putw(s, st->length); #endif } stream_put(s, st->value, st->length); } } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[email protected]> CWE ID:
static void bgp_packet_mpattr_tea(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, uint8_t attrtype) { unsigned int attrlenfield = 0; unsigned int attrhdrlen = 0; struct bgp_attr_encap_subtlv *subtlvs; struct bgp_attr_encap_subtlv *st; const char *attrname; if (!attr || (attrtype == BGP_ATTR_ENCAP && (!attr->encap_tunneltype || attr->encap_tunneltype == BGP_ENCAP_TYPE_MPLS))) return; switch (attrtype) { case BGP_ATTR_ENCAP: attrname = "Tunnel Encap"; subtlvs = attr->encap_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; /* * The tunnel encap attr has an "outer" tlv. * T = tunneltype, * L = total length of subtlvs, * V = concatenated subtlvs. */ attrlenfield = 2 + 2; /* T + L */ attrhdrlen = 1 + 1; /* subTLV T + L */ break; #if ENABLE_BGP_VNC_ATTR case BGP_ATTR_VNC: attrname = "VNC"; subtlvs = attr->vnc_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; attrlenfield = 0; /* no outer T + L */ attrhdrlen = 2 + 2; /* subTLV T + L */ break; #endif default: assert(0); } /* compute attr length */ for (st = subtlvs; st; st = st->next) { attrlenfield += (attrhdrlen + st->length); } if (attrlenfield > 0xffff) { zlog_info("%s attribute is too long (length=%d), can't send it", attrname, attrlenfield); return; } if (attrlenfield > 0xff) { /* 2-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, attrtype); stream_putw(s, attrlenfield & 0xffff); } else { /* 1-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, attrtype); stream_putc(s, attrlenfield & 0xff); } if (attrtype == BGP_ATTR_ENCAP) { /* write outer T+L */ stream_putw(s, attr->encap_tunneltype); stream_putw(s, attrlenfield - 4); } /* write each sub-tlv */ for (st = subtlvs; st; st = st->next) { if (attrtype == BGP_ATTR_ENCAP) { stream_putc(s, st->type); stream_putc(s, st->length); #if ENABLE_BGP_VNC } else { stream_putw(s, st->type); stream_putw(s, st->length); #endif } stream_put(s, st->value, st->length); } }
169,744
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_secondary_order(STREAM s) { /* The length isn't calculated correctly by the server. * For very compact orders the length becomes negative * so a signed integer must be used. */ uint16 length; uint16 flags; uint8 type; uint8 *next_order; in_uint16_le(s, length); in_uint16_le(s, flags); /* used by bmpcache2 */ in_uint8(s, type); next_order = s->p + (sint16) length + 7; switch (type) { case RDP_ORDER_RAW_BMPCACHE: process_raw_bmpcache(s); break; case RDP_ORDER_COLCACHE: process_colcache(s); break; case RDP_ORDER_BMPCACHE: process_bmpcache(s); break; case RDP_ORDER_FONTCACHE: process_fontcache(s); break; case RDP_ORDER_RAW_BMPCACHE2: process_bmpcache2(s, flags, False); /* uncompressed */ break; case RDP_ORDER_BMPCACHE2: process_bmpcache2(s, flags, True); /* compressed */ break; case RDP_ORDER_BRUSHCACHE: process_brushcache(s, flags); break; default: logger(Graphics, Warning, "process_secondary_order(), unhandled secondary order %d", type); } s->p = next_order; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
process_secondary_order(STREAM s) { /* The length isn't calculated correctly by the server. * For very compact orders the length becomes negative * so a signed integer must be used. */ uint16 length; uint16 flags; uint8 type; uint8 *next_order; struct stream packet = *s; in_uint16_le(s, length); in_uint16_le(s, flags); /* used by bmpcache2 */ in_uint8(s, type); if (!s_check_rem(s, length + 7)) { rdp_protocol_error("process_secondary_order(), next order pointer would overrun stream", &packet); } next_order = s->p + (sint16) length + 7; switch (type) { case RDP_ORDER_RAW_BMPCACHE: process_raw_bmpcache(s); break; case RDP_ORDER_COLCACHE: process_colcache(s); break; case RDP_ORDER_BMPCACHE: process_bmpcache(s); break; case RDP_ORDER_FONTCACHE: process_fontcache(s); break; case RDP_ORDER_RAW_BMPCACHE2: process_bmpcache2(s, flags, False); /* uncompressed */ break; case RDP_ORDER_BMPCACHE2: process_bmpcache2(s, flags, True); /* compressed */ break; case RDP_ORDER_BRUSHCACHE: process_brushcache(s, flags); break; default: logger(Graphics, Warning, "process_secondary_order(), unhandled secondary order %d", type); } s->p = next_order; }
169,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns) { int r; static const char resp[] = "<u:%sResponse " "xmlns:u=\"%s\">" "<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>" "</u:%sResponse>"; char body[512]; int bodylen; struct NameValueParserData data; char * int_ip, * int_port, * rem_host, * rem_port, * protocol; int opt=0; /*int proto=0;*/ unsigned short iport, rport; if (GETFLAG(IPV6FCFWDISABLEDMASK)) { SoapError(h, 702, "FirewallDisabled"); return; } ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); int_ip = GetValueFromNameValueList(&data, "InternalClient"); int_port = GetValueFromNameValueList(&data, "InternalPort"); rem_host = GetValueFromNameValueList(&data, "RemoteHost"); rem_port = GetValueFromNameValueList(&data, "RemotePort"); protocol = GetValueFromNameValueList(&data, "Protocol"); rport = (unsigned short)atoi(rem_port); iport = (unsigned short)atoi(int_port); /*proto = atoi(protocol);*/ syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol); /* TODO */ r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/ switch(r) { case 1: /* success */ bodylen = snprintf(body, sizeof(body), resp, action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/, opt, action); BuildSendAndCloseSoapResp(h, body, bodylen); break; case -5: /* Protocol not supported */ SoapError(h, 705, "ProtocolNotSupported"); break; default: SoapError(h, 501, "ActionFailed"); } ClearNameValueList(&data); } Commit Message: GetOutboundPinholeTimeout: check args CWE ID: CWE-476
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns) { int r; static const char resp[] = "<u:%sResponse " "xmlns:u=\"%s\">" "<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>" "</u:%sResponse>"; char body[512]; int bodylen; struct NameValueParserData data; char * int_ip, * int_port, * rem_host, * rem_port, * protocol; int opt=0; /*int proto=0;*/ unsigned short iport, rport; if (GETFLAG(IPV6FCFWDISABLEDMASK)) { SoapError(h, 702, "FirewallDisabled"); return; } ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); int_ip = GetValueFromNameValueList(&data, "InternalClient"); int_port = GetValueFromNameValueList(&data, "InternalPort"); rem_host = GetValueFromNameValueList(&data, "RemoteHost"); rem_port = GetValueFromNameValueList(&data, "RemotePort"); protocol = GetValueFromNameValueList(&data, "Protocol"); if (!int_port || !ext_port || !protocol) { ClearNameValueList(&data); SoapError(h, 402, "Invalid Args"); return; } rport = (unsigned short)atoi(rem_port); iport = (unsigned short)atoi(int_port); /*proto = atoi(protocol);*/ syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol); /* TODO */ r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/ switch(r) { case 1: /* success */ bodylen = snprintf(body, sizeof(body), resp, action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/, opt, action); BuildSendAndCloseSoapResp(h, body, bodylen); break; case -5: /* Protocol not supported */ SoapError(h, 705, "ProtocolNotSupported"); break; default: SoapError(h, 501, "ActionFailed"); } ClearNameValueList(&data); }
169,667
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t length; length=count*quantum; if ((count == 0) || (quantum != (length/count))) { errno=ENOMEM; return((MemoryInfo *) NULL); } memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); memory_info->length=length; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,length) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,length); if (memory_info->blob != NULL) memory_info->type=AlignedVirtualMemory; else RelinquishMagickResource(MemoryResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(MapResource,length) != MagickFalse)) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else RelinquishMagickResource(MapResource,length); } if (memory_info->blob == NULL) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file != -1) { if ((lseek(file,length-1,SEEK_SET) >= 0) && (write(file,"",1) == 1)) { memory_info->blob=MapBlob(file,IOMode,0,length); if (memory_info->blob != NULL) { memory_info->type=MapVirtualMemory; (void) AcquireMagickResource(MapResource,length); } } (void) close(file); } } if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(length); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); } Commit Message: CWE ID: CWE-189
MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t length; length=count*quantum; if ((count == 0) || (quantum != (length/count))) { errno=ENOMEM; return((MemoryInfo *) NULL); } memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); memory_info->length=length; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,length) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,length); if (memory_info->blob != NULL) memory_info->type=AlignedVirtualMemory; else RelinquishMagickResource(MemoryResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(MapResource,length) != MagickFalse)) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else RelinquishMagickResource(MapResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(DiskResource,length) != MagickFalse)) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file == -1) RelinquishMagickResource(DiskResource,length); else { if ((lseek(file,length-1,SEEK_SET) < 0) || (write(file,"",1) != 1)) RelinquishMagickResource(DiskResource,length); else { if (AcquireMagickResource(MapResource,length) == MagickFalse) RelinquishMagickResource(DiskResource,length); else { memory_info->blob=MapBlob(file,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else { RelinquishMagickResource(MapResource,length); RelinquishMagickResource(DiskResource,length); } } } (void) close(file); } } if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(length); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); }
168,859
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
24