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
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 coroutine_fn v9fs_xattrcreate(void *opaque) { int flags; int32_t fid; int64_t size; ssize_t err = 0; V9fsString name; size_t offset = 7; V9fsFidState *file_fidp; V9fsFidState *xattr_fidp; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags); if (err < 0) { goto out_nofid; } trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); file_fidp = get_fid(pdu, fid); if (file_fidp == NULL) { err = -EINVAL; goto out_nofid; } /* Make the file fid point to xattr */ xattr_fidp = file_fidp; xattr_fidp->fid_type = P9_FID_XATTR; xattr_fidp->fs.xattr.copied_len = 0; xattr_fidp->fs.xattr.len = size; xattr_fidp->fs.xattr.flags = flags; v9fs_string_init(&xattr_fidp->fs.xattr.name); v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); xattr_fidp->fs.xattr.value = g_malloc0(size); err = offset; put_fid(pdu, file_fidp); pdu_complete(pdu, err); v9fs_string_free(&name); } Commit Message: CWE ID: CWE-399
static void coroutine_fn v9fs_xattrcreate(void *opaque) { int flags; int32_t fid; int64_t size; ssize_t err = 0; V9fsString name; size_t offset = 7; V9fsFidState *file_fidp; V9fsFidState *xattr_fidp; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags); if (err < 0) { goto out_nofid; } trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); file_fidp = get_fid(pdu, fid); if (file_fidp == NULL) { err = -EINVAL; goto out_nofid; } /* Make the file fid point to xattr */ xattr_fidp = file_fidp; xattr_fidp->fid_type = P9_FID_XATTR; xattr_fidp->fs.xattr.copied_len = 0; xattr_fidp->fs.xattr.len = size; xattr_fidp->fs.xattr.flags = flags; v9fs_string_init(&xattr_fidp->fs.xattr.name); v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); g_free(xattr_fidp->fs.xattr.value); xattr_fidp->fs.xattr.value = g_malloc0(size); err = offset; put_fid(pdu, file_fidp); pdu_complete(pdu, err); v9fs_string_free(&name); }
164,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_ui32le(const iw_byte *b) { return b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24); } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682
IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b) { return (unsigned int)b[0] | ((unsigned int)b[1]<<8) | ((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24); }
168,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 const char *parse_array( cJSON *item, const char *value ) { cJSON *child; if ( *value != '[' ) { /* Not an array! */ ep = value; return 0; } item->type = cJSON_Array; value = skip( value + 1 ); if ( *value == ']' ) return value + 1; /* empty array. */ if ( ! ( item->child = child = cJSON_New_Item() ) ) return 0; /* memory fail */ if ( ! ( value = skip( parse_value( child, skip( value ) ) ) ) ) return 0; while ( *value == ',' ) { cJSON *new_item; if ( ! ( new_item = cJSON_New_Item() ) ) return 0; /* memory fail */ child->next = new_item; new_item->prev = child; child = new_item; if ( ! ( value = skip( parse_value( child, skip( value+1 ) ) ) ) ) return 0; /* memory fail */ } if ( *value == ']' ) return value + 1; /* end of array */ /* Malformed. */ ep = value; return 0; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static const char *parse_array( cJSON *item, const char *value ) static const char *parse_array(cJSON *item,const char *value,const char **ep) { cJSON *child; if (*value!='[') {*ep=value;return 0;} /* not an array! */ item->type=cJSON_Array; value=skip(value+1); if (*value==']') return value+1; /* empty array. */ item->child=child=cJSON_New_Item(); if (!item->child) return 0; /* memory fail */ value=skip(parse_value(child,skip(value),ep)); /* skip any spacing, get the value. */ if (!value) return 0; while (*value==',') { cJSON *new_item; if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_value(child,skip(value+1),ep)); if (!value) return 0; /* memory fail */ } if (*value==']') return value+1; /* end of array */ *ep=value;return 0; /* malformed. */ }
167,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LocalSiteCharacteristicsWebContentsObserverTest() { scoped_feature_list_.InitAndEnableFeature( features::kSiteCharacteristicsDatabase); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
LocalSiteCharacteristicsWebContentsObserverTest() {
172,217
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf) { const HashSet<Page*>& pages = page->group().pages(); HashSet<Page*>::const_iterator end = pages.end(); for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) { Page* otherPage = *it; if ((deferSelf || otherPage != page)) { if (!otherPage->defersLoading()) { m_deferredFrames.append(otherPage->mainFrame()); for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading); } } } size_t count = m_deferredFrames.size(); for (size_t i = 0; i < count; ++i) if (Page* page = m_deferredFrames[i]->page()) page->setDefersLoading(true); } Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf) { const HashSet<Page*>& pages = page->group().pages(); HashSet<Page*>::const_iterator end = pages.end(); for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) { Page* otherPage = *it; if ((deferSelf || otherPage != page)) { if (!otherPage->defersLoading()) { m_deferredFrames.append(otherPage->mainFrame()); // Ensure that we notify the client if the initial empty document is accessed before showing anything // modal, to prevent spoofs while the modal window or sheet is visible. otherPage->mainFrame()->loader()->notifyIfInitialDocumentAccessed(); for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading); } } } size_t count = m_deferredFrames.size(); for (size_t i = 0; i < count; ++i) if (Page* page = m_deferredFrames[i]->page()) page->setDefersLoading(true); }
171,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 btif_av_event_free_data(btif_sm_event_t event, void* p_data) { switch (event) { case BTA_AV_META_MSG_EVT: { tBTA_AV* av = (tBTA_AV*)p_data; osi_free_and_reset((void**)&av->meta_msg.p_data); if (av->meta_msg.p_msg) { if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) { osi_free(av->meta_msg.p_msg->vendor.p_vendor_data); } osi_free_and_reset((void**)&av->meta_msg.p_msg); } } break; default: break; } } Commit Message: DO NOT MERGE AVRC: Copy browse.p_browse_data in btif_av_event_deep_copy p_msg_src->browse.p_browse_data is not copied, but used after the original pointer is freed Bug: 109699112 Test: manual Change-Id: I1d014eb9a8911da6913173a9b11218bf1c89e16e (cherry picked from commit 1d9a58768e6573899c7e80c2b3f52e22f2d8f58b) CWE ID: CWE-416
static void btif_av_event_free_data(btif_sm_event_t event, void* p_data) { switch (event) { case BTA_AV_META_MSG_EVT: { tBTA_AV* av = (tBTA_AV*)p_data; osi_free_and_reset((void**)&av->meta_msg.p_data); if (av->meta_msg.p_msg) { if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_VENDOR) { osi_free(av->meta_msg.p_msg->vendor.p_vendor_data); } if (av->meta_msg.p_msg->hdr.opcode == AVRC_OP_BROWSE) { osi_free(av->meta_msg.p_msg->browse.p_browse_data); } osi_free_and_reset((void**)&av->meta_msg.p_msg); } } break; default: break; } }
174,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst, const xmlChar *propName, int mandatory, int *hasProp, const xmlChar **nsName, const xmlChar** localName) { const xmlChar *prop; if (nsName) *nsName = NULL; if (localName) *localName = NULL; if (hasProp) *hasProp = 0; prop = xsltGetCNsProp(style, inst, propName, XSLT_NAMESPACE); if (prop == NULL) { if (mandatory) { xsltTransformError(NULL, style, inst, "The attribute '%s' is missing.\n", propName); style->errors++; return; } } else { const xmlChar *URI; if (xmlValidateQName(prop, 0)) { xsltTransformError(NULL, style, inst, "The value '%s' of the attribute " "'%s' is not a valid QName.\n", prop, propName); style->errors++; return; } else { /* * @prop will be in the string dict afterwards, @URI not. */ URI = xsltGetQNameURI2(style, inst, &prop); if (prop == NULL) { style->errors++; } else { *localName = prop; if (hasProp) *hasProp = 1; if (URI != NULL) { /* * Fixes bug #308441: Put the ns-name in the dict * in order to pointer compare names during XPath's * variable lookup. */ if (nsName) *nsName = xmlDictLookup(style->dict, URI, -1); /* comp->has_ns = 1; */ } } } } return; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst, const xmlChar *propName, int mandatory, int *hasProp, const xmlChar **nsName, const xmlChar** localName) { const xmlChar *prop; if (nsName) *nsName = NULL; if (localName) *localName = NULL; if (hasProp) *hasProp = 0; prop = xsltGetCNsProp(style, inst, propName, XSLT_NAMESPACE); if (prop == NULL) { if (mandatory) { xsltTransformError(NULL, style, inst, "The attribute '%s' is missing.\n", propName); style->errors++; return; } } else { const xmlChar *URI; if (xmlValidateQName(prop, 0)) { xsltTransformError(NULL, style, inst, "The value '%s' of the attribute " "'%s' is not a valid QName.\n", prop, propName); style->errors++; return; } else { /* * @prop will be in the string dict afterwards, @URI not. */ URI = xsltGetQNameURI2(style, inst, &prop); if (prop == NULL) { style->errors++; } else { if (localName) *localName = prop; if (hasProp) *hasProp = 1; if (URI != NULL) { /* * Fixes bug #308441: Put the ns-name in the dict * in order to pointer compare names during XPath's * variable lookup. */ if (nsName) *nsName = xmlDictLookup(style->dict, URI, -1); /* comp->has_ns = 1; */ } } } } return; }
173,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, key_tries, sign_tries, blind_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* Make sure d is in range 1..n-1 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); sign_tries = 0; do { /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ key_tries = 0; do { MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair( grp, &k, &R, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) ); if( key_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( r, 0 ) == 0 ); /* * Step 5: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. */ blind_tries = 0; do { size_t n_size = ( grp->nbits + 7 ) / 8; MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) ); /* See mbedtls_ecp_gen_keypair() */ if( ++blind_tries > 30 ) return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); } while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 || mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); if( sign_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted CWE ID: CWE-200
int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, static int ecdsa_sign_internal( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { int ret, key_tries, sign_tries, blind_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* Make sure d is in range 1..n-1 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); sign_tries = 0; do { /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ key_tries = 0; do { MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &k, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, &R, &k, &grp->G, f_rng_blind, p_rng_blind ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) ); if( key_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( r, 0 ) == 0 ); /* * Step 5: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. * * This loop does the same job as mbedtls_ecp_gen_privkey() and it is * replaced by a call to it in the mainline. This change is not * necessary to backport the fix separating the blinding and ephemeral * key generating RNGs, therefore the original code is kept. */ blind_tries = 0; do { size_t n_size = ( grp->nbits + 7 ) / 8; MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng_blind, p_rng_blind ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) ); if( ++blind_tries > 30 ) return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); } while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 || mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); if( sign_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); return( ret ); }
170,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewGtk::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, true, 0); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewGtk::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, params.surface_handle, 0); }
171,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CheckMov(const uint8* buffer, int buffer_size) { RCHECK(buffer_size > 8); int offset = 0; while (offset + 8 < buffer_size) { int atomsize = Read32(buffer + offset); uint32 atomtype = Read32(buffer + offset + 4); switch (atomtype) { case TAG('f','t','y','p'): case TAG('p','d','i','n'): case TAG('m','o','o','v'): case TAG('m','o','o','f'): case TAG('m','f','r','a'): case TAG('m','d','a','t'): case TAG('f','r','e','e'): case TAG('s','k','i','p'): case TAG('m','e','t','a'): case TAG('m','e','c','o'): case TAG('s','t','y','p'): case TAG('s','i','d','x'): case TAG('s','s','i','x'): case TAG('p','r','f','t'): case TAG('b','l','o','c'): break; default: return false; } if (atomsize == 1) { if (offset + 16 > buffer_size) break; if (Read32(buffer + offset + 8) != 0) break; // Offset is way past buffer size. atomsize = Read32(buffer + offset + 12); } if (atomsize <= 0) break; // Indicates the last atom or length too big. offset += atomsize; } return true; } Commit Message: Add extra checks to avoid integer overflow. BUG=425980 TEST=no crash with ASAN Review URL: https://codereview.chromium.org/659743004 Cr-Commit-Position: refs/heads/master@{#301249} CWE ID: CWE-189
static bool CheckMov(const uint8* buffer, int buffer_size) { RCHECK(buffer_size > 8); int offset = 0; while (offset + 8 < buffer_size) { uint32 atomsize = Read32(buffer + offset); uint32 atomtype = Read32(buffer + offset + 4); switch (atomtype) { case TAG('f','t','y','p'): case TAG('p','d','i','n'): case TAG('m','o','o','v'): case TAG('m','o','o','f'): case TAG('m','f','r','a'): case TAG('m','d','a','t'): case TAG('f','r','e','e'): case TAG('s','k','i','p'): case TAG('m','e','t','a'): case TAG('m','e','c','o'): case TAG('s','t','y','p'): case TAG('s','i','d','x'): case TAG('s','s','i','x'): case TAG('p','r','f','t'): case TAG('b','l','o','c'): break; default: return false; } if (atomsize == 1) { if (offset + 16 > buffer_size) break; if (Read32(buffer + offset + 8) != 0) break; // Offset is way past buffer size. atomsize = Read32(buffer + offset + 12); } if (atomsize == 0 || atomsize > static_cast<size_t>(buffer_size)) break; // Indicates the last atom or length too big. offset += atomsize; } return true; }
171,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResourcePrefetchPredictor::LearnOrigins( const std::string& host, const GURL& main_frame_origin, const std::map<GURL, OriginRequestSummary>& summaries) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (host.size() > ResourcePrefetchPredictorTables::kMaxStringLength) return; OriginData data; bool exists = origin_data_->TryGetData(host, &data); if (!exists) { data.set_host(host); data.set_last_visit_time(base::Time::Now().ToInternalValue()); size_t origins_size = summaries.size(); auto ordered_origins = std::vector<const OriginRequestSummary*>(origins_size); for (const auto& kv : summaries) { size_t index = kv.second.first_occurrence; DCHECK_LT(index, origins_size); ordered_origins[index] = &kv.second; } for (const OriginRequestSummary* summary : ordered_origins) { auto* origin_to_add = data.add_origins(); InitializeOriginStatFromOriginRequestSummary(origin_to_add, *summary); } } else { data.set_last_visit_time(base::Time::Now().ToInternalValue()); std::map<GURL, int> old_index; int old_size = static_cast<int>(data.origins_size()); for (int i = 0; i < old_size; ++i) { bool is_new = old_index.insert({GURL(data.origins(i).origin()), i}).second; DCHECK(is_new); } for (int i = 0; i < old_size; ++i) { auto* old_origin = data.mutable_origins(i); GURL origin(old_origin->origin()); auto it = summaries.find(origin); if (it == summaries.end()) { old_origin->set_number_of_misses(old_origin->number_of_misses() + 1); old_origin->set_consecutive_misses(old_origin->consecutive_misses() + 1); } else { const auto& new_origin = it->second; old_origin->set_always_access_network(new_origin.always_access_network); old_origin->set_accessed_network(new_origin.accessed_network); int position = new_origin.first_occurrence + 1; int total = old_origin->number_of_hits() + old_origin->number_of_misses(); old_origin->set_average_position( ((old_origin->average_position() * total) + position) / (total + 1)); old_origin->set_number_of_hits(old_origin->number_of_hits() + 1); old_origin->set_consecutive_misses(0); } } for (const auto& kv : summaries) { if (old_index.find(kv.first) != old_index.end()) continue; auto* origin_to_add = data.add_origins(); InitializeOriginStatFromOriginRequestSummary(origin_to_add, kv.second); } } ResourcePrefetchPredictorTables::TrimOrigins(&data, config_.max_consecutive_misses); ResourcePrefetchPredictorTables::SortOrigins(&data, main_frame_origin.spec()); if (data.origins_size() > static_cast<int>(config_.max_origins_per_entry)) { data.mutable_origins()->DeleteSubrange( config_.max_origins_per_entry, data.origins_size() - config_.max_origins_per_entry); } if (data.origins_size() == 0) origin_data_->DeleteData({host}); else origin_data_->UpdateData(host, data); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void ResourcePrefetchPredictor::LearnOrigins( const std::string& host, const GURL& main_frame_origin, const std::map<url::Origin, OriginRequestSummary>& summaries) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (host.size() > ResourcePrefetchPredictorTables::kMaxStringLength) return; OriginData data; bool exists = origin_data_->TryGetData(host, &data); if (!exists) { data.set_host(host); data.set_last_visit_time(base::Time::Now().ToInternalValue()); size_t origins_size = summaries.size(); auto ordered_origins = std::vector<const OriginRequestSummary*>(origins_size); for (const auto& kv : summaries) { size_t index = kv.second.first_occurrence; DCHECK_LT(index, origins_size); ordered_origins[index] = &kv.second; } for (const OriginRequestSummary* summary : ordered_origins) { auto* origin_to_add = data.add_origins(); InitializeOriginStatFromOriginRequestSummary(origin_to_add, *summary); } } else { data.set_last_visit_time(base::Time::Now().ToInternalValue()); std::map<url::Origin, int> old_index; int old_size = static_cast<int>(data.origins_size()); for (int i = 0; i < old_size; ++i) { bool is_new = old_index .insert({url::Origin::Create(GURL(data.origins(i).origin())), i}) .second; DCHECK(is_new); } for (int i = 0; i < old_size; ++i) { auto* old_origin = data.mutable_origins(i); url::Origin origin = url::Origin::Create(GURL(old_origin->origin())); auto it = summaries.find(origin); if (it == summaries.end()) { old_origin->set_number_of_misses(old_origin->number_of_misses() + 1); old_origin->set_consecutive_misses(old_origin->consecutive_misses() + 1); } else { const auto& new_origin = it->second; old_origin->set_always_access_network(new_origin.always_access_network); old_origin->set_accessed_network(new_origin.accessed_network); int position = new_origin.first_occurrence + 1; int total = old_origin->number_of_hits() + old_origin->number_of_misses(); old_origin->set_average_position( ((old_origin->average_position() * total) + position) / (total + 1)); old_origin->set_number_of_hits(old_origin->number_of_hits() + 1); old_origin->set_consecutive_misses(0); } } for (const auto& kv : summaries) { if (old_index.find(kv.first) != old_index.end()) continue; auto* origin_to_add = data.add_origins(); InitializeOriginStatFromOriginRequestSummary(origin_to_add, kv.second); } } ResourcePrefetchPredictorTables::TrimOrigins(&data, config_.max_consecutive_misses); ResourcePrefetchPredictorTables::SortOrigins(&data, main_frame_origin.spec()); if (data.origins_size() > static_cast<int>(config_.max_origins_per_entry)) { data.mutable_origins()->DeleteSubrange( config_.max_origins_per_entry, data.origins_size() - config_.max_origins_per_entry); } if (data.origins_size() == 0) origin_data_->DeleteData({host}); else origin_data_->UpdateData(host, data); }
172,380
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); DLOG(INFO) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; current_input_method_changed_(language_library_, current_input_method); } 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
void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); VLOG(1) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; FOR_EACH_OBSERVER(Observer, observers_, OnCurrentInputMethodChanged(current_input_method)); }
170,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val - 1); } Commit Message: CWE ID: CWE-20
void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); }
165,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const { ParaNdis_CheckSumVerifyFlat(IpHeader, EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum, __FUNCTION__); } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20
void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const { ParaNdis_CheckSumVerifyFlat(IpHeader, EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum, FALSE, __FUNCTION__); }
170,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%lu: Strip out of range, max %lu",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip); stripinplane=(strip%stripsperplane); plane=(uint16)(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= stripsize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,stripsize); (*tif->tif_postdecode)(tif,buf,stripsize); return (stripsize); } if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,stripsize); return(stripsize); } Commit Message: * libtiff/tif_read.c, libtiff/tiffiop.h: fix uint32 overflow in TIFFReadEncodedStrip() that caused an integer division by zero. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2596 CWE ID: CWE-369
TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%lu: Strip out of range, max %lu",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane= TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip); stripinplane=(strip%stripsperplane); plane=(uint16)(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= stripsize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,stripsize); (*tif->tif_postdecode)(tif,buf,stripsize); return (stripsize); } if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,stripsize); return(stripsize); }
168,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } Commit Message: CVE-2017-13043/BGP: fix decoding of MVPN route types 6 and 7 RFC 6514 Section 4.6 defines the structure for Shared Tree Join (6) and Source Tree Join (7) multicast VPN route types. decode_multicast_vpn() didn't implement the Source AS field of that structure properly, adjust the offsets to put it right. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN + 4; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; }
167,832
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAgentManagerClient( scoped_ptr<BluetoothAgentManagerClient>( new FakeBluetoothAgentManagerClient)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); }
171,242
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LocalFileSystem::deleteFileSystem(ExecutionContext* context, FileSystemType type, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); ASSERT(context); ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument()); RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::deleteFileSystem(ExecutionContext* context, FileSystemType type, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); ASSERT(context); ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument()); CallbackWrapper* wrapper = new CallbackWrapper(callbacks); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); }
171,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuCommandBufferStub::OnRegisterTransferBuffer( base::SharedMemoryHandle transfer_buffer, size_t size, int32 id_request, IPC::Message* reply_message) { #if defined(OS_WIN) base::SharedMemory shared_memory(transfer_buffer, false, channel_->renderer_process()); #else #endif if (command_buffer_.get()) { int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory, size, id_request); GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuCommandBufferStub::OnRegisterTransferBuffer( base::SharedMemoryHandle transfer_buffer, size_t size, int32 id_request, IPC::Message* reply_message) { if (command_buffer_.get()) { int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory, size, id_request); GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); }
170,938
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hashtable_do_rehash(hashtable_t *hashtable) { list_t *list, *next; pair_t *pair; size_t i, index, new_size; jsonp_free(hashtable->buckets); hashtable->num_buckets++; new_size = num_buckets(hashtable); hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t)); if(!hashtable->buckets) return -1; for(i = 0; i < num_buckets(hashtable); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } list = hashtable->list.next; list_init(&hashtable->list); for(; list != &hashtable->list; list = next) { next = list->next; pair = list_to_pair(list); index = pair->hash % new_size; insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list); } return 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
static int hashtable_do_rehash(hashtable_t *hashtable) { list_t *list, *next; pair_t *pair; size_t i, index, new_size; jsonp_free(hashtable->buckets); hashtable->order++; new_size = hashsize(hashtable->order); hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t)); if(!hashtable->buckets) return -1; for(i = 0; i < hashsize(hashtable->order); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } list = hashtable->list.next; list_init(&hashtable->list); for(; list != &hashtable->list; list = next) { next = list->next; pair = list_to_pair(list); index = pair->hash % new_size; insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list); } return 0; }
166,529
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 _nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred, struct nfs4_state **res) { struct nfs4_state_owner *sp; struct nfs4_state *state = NULL; struct nfs_server *server = NFS_SERVER(dir); struct nfs4_opendata *opendata; int status; /* Protect against reboot recovery conflicts */ status = -ENOMEM; if (!(sp = nfs4_get_state_owner(server, cred))) { dprintk("nfs4_do_open: nfs4_get_state_owner failed!\n"); goto out_err; } status = nfs4_recover_expired_lease(server); if (status != 0) goto err_put_state_owner; if (path->dentry->d_inode != NULL) nfs4_return_incompatible_delegation(path->dentry->d_inode, flags & (FMODE_READ|FMODE_WRITE)); status = -ENOMEM; opendata = nfs4_opendata_alloc(path, sp, flags, sattr); if (opendata == NULL) goto err_put_state_owner; if (path->dentry->d_inode != NULL) opendata->state = nfs4_get_open_state(path->dentry->d_inode, sp); status = _nfs4_proc_open(opendata); if (status != 0) goto err_opendata_put; if (opendata->o_arg.open_flags & O_EXCL) nfs4_exclusive_attrset(opendata, sattr); state = nfs4_opendata_to_nfs4_state(opendata); status = PTR_ERR(state); if (IS_ERR(state)) goto err_opendata_put; nfs4_opendata_put(opendata); nfs4_put_state_owner(sp); *res = state; return 0; err_opendata_put: nfs4_opendata_put(opendata); err_put_state_owner: nfs4_put_state_owner(sp); out_err: *res = NULL; return status; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static int _nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred, struct nfs4_state **res) static int _nfs4_do_open(struct inode *dir, struct path *path, fmode_t fmode, int flags, struct iattr *sattr, struct rpc_cred *cred, struct nfs4_state **res) { struct nfs4_state_owner *sp; struct nfs4_state *state = NULL; struct nfs_server *server = NFS_SERVER(dir); struct nfs4_opendata *opendata; int status; /* Protect against reboot recovery conflicts */ status = -ENOMEM; if (!(sp = nfs4_get_state_owner(server, cred))) { dprintk("nfs4_do_open: nfs4_get_state_owner failed!\n"); goto out_err; } status = nfs4_recover_expired_lease(server); if (status != 0) goto err_put_state_owner; if (path->dentry->d_inode != NULL) nfs4_return_incompatible_delegation(path->dentry->d_inode, fmode); status = -ENOMEM; opendata = nfs4_opendata_alloc(path, sp, fmode, flags, sattr); if (opendata == NULL) goto err_put_state_owner; if (path->dentry->d_inode != NULL) opendata->state = nfs4_get_open_state(path->dentry->d_inode, sp); status = _nfs4_proc_open(opendata); if (status != 0) goto err_opendata_put; if (opendata->o_arg.open_flags & O_EXCL) nfs4_exclusive_attrset(opendata, sattr); state = nfs4_opendata_to_nfs4_state(opendata); status = PTR_ERR(state); if (IS_ERR(state)) goto err_opendata_put; nfs4_opendata_put(opendata); nfs4_put_state_owner(sp); *res = state; return 0; err_opendata_put: nfs4_opendata_put(opendata); err_put_state_owner: nfs4_put_state_owner(sp); out_err: *res = NULL; return status; }
165,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::RemovingFromRootWindow() { host_->ParentChanged(0); ui::Compositor* compositor = GetCompositor(); RunCompositingDidCommitCallbacks(compositor); locks_pending_commit_.clear(); if (compositor && compositor->HasObserver(this)) compositor->RemoveObserver(this); DetachFromInputMethod(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::RemovingFromRootWindow() { host_->ParentChanged(0); ui::Compositor* compositor = GetCompositor(); RunCompositingDidCommitCallbacks(); locks_pending_commit_.clear(); if (compositor && compositor->HasObserver(this)) compositor->RemoveObserver(this); DetachFromInputMethod(); }
171,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); // no emptybuffer if using input surface if (getGraphicBufferSource() != NULL) { android_errorWriteLog(0x534e4554, "29422020"); return INVALID_OPERATION; } OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); }
174,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlElementContentPtr *result) { xmlElementContentPtr tree = NULL; int inputid = ctxt->input->id; int res; *result = NULL; if (RAW != '(') { xmlFatalErrMsgStr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, "xmlParseElementContentDecl : %s '(' expected\n", name); return(-1); } NEXT; GROW; SKIP_BLANKS; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { tree = xmlParseElementMixedContentDecl(ctxt, inputid); res = XML_ELEMENT_TYPE_MIXED; } else { tree = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, 1); res = XML_ELEMENT_TYPE_ELEMENT; } SKIP_BLANKS; *result = tree; return(res); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlElementContentPtr *result) { xmlElementContentPtr tree = NULL; int inputid = ctxt->input->id; int res; *result = NULL; if (RAW != '(') { xmlFatalErrMsgStr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, "xmlParseElementContentDecl : %s '(' expected\n", name); return(-1); } NEXT; GROW; if (ctxt->instate == XML_PARSER_EOF) return(-1); SKIP_BLANKS; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { tree = xmlParseElementMixedContentDecl(ctxt, inputid); res = XML_ELEMENT_TYPE_MIXED; } else { tree = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, 1); res = XML_ELEMENT_TYPE_ELEMENT; } SKIP_BLANKS; *result = tree; return(res); }
171,285
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 update_rate_histogram(struct rate_hist *hist, const vpx_codec_enc_cfg_t *cfg, const vpx_codec_cx_pkt_t *pkt) { int i; int64_t then = 0; int64_t avg_bitrate = 0; int64_t sum_sz = 0; const int64_t now = pkt->data.frame.pts * 1000 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den; int idx = hist->frames++ % hist->samples; hist->pts[idx] = now; hist->sz[idx] = (int)pkt->data.frame.sz; if (now < cfg->rc_buf_initial_sz) return; then = now; /* Sum the size over the past rc_buf_sz ms */ for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) { const int i_idx = (i - 1) % hist->samples; then = hist->pts[i_idx]; if (now - then > cfg->rc_buf_sz) break; sum_sz += hist->sz[i_idx]; } if (now == then) return; avg_bitrate = sum_sz * 8 * 1000 / (now - then); idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000)); if (idx < 0) idx = 0; if (idx > RATE_BINS - 1) idx = RATE_BINS - 1; if (hist->bucket[idx].low > avg_bitrate) hist->bucket[idx].low = (int)avg_bitrate; if (hist->bucket[idx].high < avg_bitrate) hist->bucket[idx].high = (int)avg_bitrate; hist->bucket[idx].count++; hist->total++; } 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 update_rate_histogram(struct rate_hist *hist, const vpx_codec_enc_cfg_t *cfg, const vpx_codec_cx_pkt_t *pkt) { int i; int64_t then = 0; int64_t avg_bitrate = 0; int64_t sum_sz = 0; const int64_t now = pkt->data.frame.pts * 1000 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den; int idx = hist->frames++ % hist->samples; hist->pts[idx] = now; hist->sz[idx] = (int)pkt->data.frame.sz; if (now < cfg->rc_buf_initial_sz) return; if (!cfg->rc_target_bitrate) return; then = now; /* Sum the size over the past rc_buf_sz ms */ for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) { const int i_idx = (i - 1) % hist->samples; then = hist->pts[i_idx]; if (now - then > cfg->rc_buf_sz) break; sum_sz += hist->sz[i_idx]; } if (now == then) return; avg_bitrate = sum_sz * 8 * 1000 / (now - then); idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000)); if (idx < 0) idx = 0; if (idx > RATE_BINS - 1) idx = RATE_BINS - 1; if (hist->bucket[idx].low > avg_bitrate) hist->bucket[idx].low = (int)avg_bitrate; if (hist->bucket[idx].high < avg_bitrate) hist->bucket[idx].high = (int)avg_bitrate; hist->bucket[idx].count++; hist->total++; }
174,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppModalDialog::CompleteDialog() { AppModalDialogQueue::GetInstance()->ShowNextDialog(); } Commit Message: Fix a Windows crash bug with javascript alerts from extension popups. BUG=137707 Review URL: https://chromiumcodereview.appspot.com/10828423 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void AppModalDialog::CompleteDialog() { if (!completed_) { completed_ = true; AppModalDialogQueue::GetInstance()->ShowNextDialog(); } }
170,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DisplaySourceCustomBindings::DisplaySourceCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context), weak_factory_(this) { RouteFunction("StartSession", base::Bind(&DisplaySourceCustomBindings::StartSession, weak_factory_.GetWeakPtr())); RouteFunction("TerminateSession", base::Bind(&DisplaySourceCustomBindings::TerminateSession, weak_factory_.GetWeakPtr())); } 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
DisplaySourceCustomBindings::DisplaySourceCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context), weak_factory_(this) { RouteFunction("StartSession", "displaySource", base::Bind(&DisplaySourceCustomBindings::StartSession, weak_factory_.GetWeakPtr())); RouteFunction("TerminateSession", "displaySource", base::Bind(&DisplaySourceCustomBindings::TerminateSession, weak_factory_.GetWeakPtr())); }
172,248
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 v9fs_read(void *opaque) { int32_t fid; uint64_t off; ssize_t err = 0; int32_t count = 0; size_t offset = 7; uint32_t max_count; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count); if (err < 0) { goto out_nofid; } trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (fidp->fid_type == P9_FID_DIR) { if (off == 0) { v9fs_co_rewinddir(pdu, fidp); } count = v9fs_do_readdir_with_stat(pdu, fidp, max_count); if (count < 0) { err = count; goto out; } err = pdu_marshal(pdu, offset, "d", count); if (err < 0) { goto out; } err += offset + count; } else if (fidp->fid_type == P9_FID_FILE) { QEMUIOVector qiov_full; QEMUIOVector qiov; int32_t len; v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false); qemu_iovec_init(&qiov, qiov_full.niov); do { qemu_iovec_reset(&qiov); qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count); if (0) { print_sg(qiov.iov, qiov.niov); } /* Loop in case of EINTR */ do { len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off); if (len >= 0) { off += len; count += len; } } while (len == -EINTR && !pdu->cancelled); if (len < 0) { /* IO error return the error */ err = len; goto out; } } while (count < max_count && len > 0); err = pdu_marshal(pdu, offset, "d", count); if (err < 0) { goto out; } err += offset + count; qemu_iovec_destroy(&qiov); qemu_iovec_destroy(&qiov_full); } else if (fidp->fid_type == P9_FID_XATTR) { } else { err = -EINVAL; } trace_v9fs_read_return(pdu->tag, pdu->id, count, err); out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); } Commit Message: CWE ID: CWE-399
static void v9fs_read(void *opaque) { int32_t fid; uint64_t off; ssize_t err = 0; int32_t count = 0; size_t offset = 7; uint32_t max_count; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count); if (err < 0) { goto out_nofid; } trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (fidp->fid_type == P9_FID_DIR) { if (off == 0) { v9fs_co_rewinddir(pdu, fidp); } count = v9fs_do_readdir_with_stat(pdu, fidp, max_count); if (count < 0) { err = count; goto out; } err = pdu_marshal(pdu, offset, "d", count); if (err < 0) { goto out; } err += offset + count; } else if (fidp->fid_type == P9_FID_FILE) { QEMUIOVector qiov_full; QEMUIOVector qiov; int32_t len; v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false); qemu_iovec_init(&qiov, qiov_full.niov); do { qemu_iovec_reset(&qiov); qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count); if (0) { print_sg(qiov.iov, qiov.niov); } /* Loop in case of EINTR */ do { len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off); if (len >= 0) { off += len; count += len; } } while (len == -EINTR && !pdu->cancelled); if (len < 0) { /* IO error return the error */ err = len; goto out_free_iovec; } } while (count < max_count && len > 0); err = pdu_marshal(pdu, offset, "d", count); if (err < 0) { goto out_free_iovec; } err += offset + count; out_free_iovec: qemu_iovec_destroy(&qiov); qemu_iovec_destroy(&qiov_full); } else if (fidp->fid_type == P9_FID_XATTR) { } else { err = -EINVAL; } trace_v9fs_read_return(pdu->tag, pdu->id, count, err); out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); }
164,911
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BluetoothAdapterChromeOS::BluetoothAdapterChromeOS() : weak_ptr_factory_(this) { DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this); std::vector<dbus::ObjectPath> object_paths = DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters(); if (!object_paths.empty()) { VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available."; SetAdapter(object_paths[0]); } } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
BluetoothAdapterChromeOS::BluetoothAdapterChromeOS() : weak_ptr_factory_(this) { DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this); std::vector<dbus::ObjectPath> object_paths = DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters(); if (!object_paths.empty()) { VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available."; SetAdapter(object_paths[0]); } // Register the pairing agent. dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus(); agent_.reset(BluetoothAgentServiceProvider::Create( system_bus, dbus::ObjectPath(kAgentPath), this)); DCHECK(agent_.get()); VLOG(1) << "Registering pairing agent"; DBusThreadManager::Get()->GetBluetoothAgentManagerClient()-> RegisterAgent( dbus::ObjectPath(kAgentPath), bluetooth_agent_manager::kKeyboardDisplayCapability, base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgent, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgentError, weak_ptr_factory_.GetWeakPtr())); }
171,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 locationWithCallWithAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithCallWith()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefCallWith(callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationWithCallWithAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithCallWith()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefCallWith(callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), cppValue); }
171,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: do_ssh2_kex(void) { char *myproposal[PROPOSAL_MAX] = { KEX_SERVER }; struct kex *kex; int r; myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal( options.kex_algorithms); myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal( options.ciphers); myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal( options.ciphers); myproposal[PROPOSAL_MAC_ALGS_CTOS] = myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; if (options.compression == COMP_NONE) { myproposal[PROPOSAL_COMP_ALGS_CTOS] = myproposal[PROPOSAL_COMP_ALGS_STOC] = "none"; } else if (options.compression == COMP_DELAYED) { myproposal[PROPOSAL_COMP_ALGS_CTOS] = myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,[email protected]"; } if (options.rekey_limit || options.rekey_interval) packet_set_rekey_limits(options.rekey_limit, (time_t)options.rekey_interval); myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal( list_hostkey_types()); /* start key exchange */ if ((r = kex_setup(active_state, myproposal)) != 0) fatal("kex_setup: %s", ssh_err(r)); kex = active_state->kex; #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server; kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server; kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server; kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; kex->kex[KEX_ECDH_SHA2] = kexecdh_server; #endif kex->kex[KEX_C25519_SHA256] = kexc25519_server; kex->server = 1; kex->client_version_string=client_version_string; kex->server_version_string=server_version_string; kex->load_host_public_key=&get_hostkey_public_by_type; kex->load_host_private_key=&get_hostkey_private_by_type; kex->host_key_index=&get_hostkey_index; kex->sign = sshd_hostkey_sign; dispatch_run(DISPATCH_BLOCK, &kex->done, active_state); session_id2 = kex->session_id; session_id2_len = kex->session_id_len; #ifdef DEBUG_KEXDH /* send 1st encrypted/maced/compressed message */ packet_start(SSH2_MSG_IGNORE); packet_put_cstring("markus"); packet_send(); packet_write_wait(); #endif debug("KEX done"); } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
do_ssh2_kex(void) { char *myproposal[PROPOSAL_MAX] = { KEX_SERVER }; struct kex *kex; int r; myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal( options.kex_algorithms); myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal( options.ciphers); myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal( options.ciphers); myproposal[PROPOSAL_MAC_ALGS_CTOS] = myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; if (options.compression == COMP_NONE) { myproposal[PROPOSAL_COMP_ALGS_CTOS] = myproposal[PROPOSAL_COMP_ALGS_STOC] = "none"; } if (options.rekey_limit || options.rekey_interval) packet_set_rekey_limits(options.rekey_limit, (time_t)options.rekey_interval); myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal( list_hostkey_types()); /* start key exchange */ if ((r = kex_setup(active_state, myproposal)) != 0) fatal("kex_setup: %s", ssh_err(r)); kex = active_state->kex; #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server; kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server; kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server; kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; kex->kex[KEX_ECDH_SHA2] = kexecdh_server; #endif kex->kex[KEX_C25519_SHA256] = kexc25519_server; kex->server = 1; kex->client_version_string=client_version_string; kex->server_version_string=server_version_string; kex->load_host_public_key=&get_hostkey_public_by_type; kex->load_host_private_key=&get_hostkey_private_by_type; kex->host_key_index=&get_hostkey_index; kex->sign = sshd_hostkey_sign; dispatch_run(DISPATCH_BLOCK, &kex->done, active_state); session_id2 = kex->session_id; session_id2_len = kex->session_id_len; #ifdef DEBUG_KEXDH /* send 1st encrypted/maced/compressed message */ packet_start(SSH2_MSG_IGNORE); packet_put_cstring("markus"); packet_send(); packet_write_wait(); #endif debug("KEX done"); }
168,658
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AppControllerImpl::~AppControllerImpl() { if (apps::AppServiceProxy::Get(profile_)) app_service_proxy_->AppRegistryCache().RemoveObserver(this); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
AppControllerImpl::~AppControllerImpl() { AppControllerService::~AppControllerService() { app_service_proxy_->AppRegistryCache().RemoveObserver(this); }
172,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 _make_words(char *l,long n,ogg_uint32_t *r,long quantvals, codebook *b, oggpack_buffer *opb,int maptype){ long i,j,count=0; long top=0; ogg_uint32_t marker[MARKER_SIZE]; if (n<1) return 1; if(n<2){ r[0]=0x80000000; }else{ memset(marker,0,sizeof(marker)); for(i=0;i<n;i++){ long length=l[i]; if(length){ if (length < 0 || length >= MARKER_SIZE) { ALOGE("b/23881715"); return 1; } ogg_uint32_t entry=marker[length]; long chase=0; if(count && !entry)return -1; /* overpopulated tree! */ /* chase the tree as far as it's already populated, fill in past */ for(j=0;j<length-1;j++){ int bit=(entry>>(length-j-1))&1; if(chase>=top){ if (chase < 0 || chase >= n) return 1; top++; r[chase*2]=top; r[chase*2+1]=0; }else if (chase < 0 || chase >= n || chase*2+bit > n*2+1) return 1; if(!r[chase*2+bit]) r[chase*2+bit]=top; chase=r[chase*2+bit]; if (chase < 0 || chase >= n) return 1; } { int bit=(entry>>(length-j-1))&1; if(chase>=top){ top++; r[chase*2+1]=0; } r[chase*2+bit]= decpack(i,count++,quantvals,b,opb,maptype) | 0x80000000; } /* Look to see if the next shorter marker points to the node above. if so, update it and repeat. */ for(j=length;j>0;j--){ if(marker[j]&1){ marker[j]=marker[j-1]<<1; break; } marker[j]++; } /* prune the tree; the implicit invariant says all the longer markers were dangling from our just-taken node. Dangle them from our *new* node. */ for(j=length+1;j<MARKER_SIZE;j++) if((marker[j]>>1) == entry){ entry=marker[j]; marker[j]=marker[j-1]<<1; }else break; } } } /* sanity check the huffman tree; an underpopulated tree must be rejected. The only exception is the one-node pseudo-nil tree, which appears to be underpopulated because the tree doesn't really exist; there's only one possible 'codeword' or zero bits, but the above tree-gen code doesn't mark that. */ if(b->used_entries != 1){ for(i=1;i<MARKER_SIZE;i++) if(marker[i] & (0xffffffffUL>>(32-i))){ return 1; } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static int _make_words(char *l,long n,ogg_uint32_t *r,long quantvals, codebook *b, oggpack_buffer *opb,int maptype){ long i,j,count=0; long top=0; ogg_uint32_t marker[MARKER_SIZE]; if (n<1) return 1; if(n<2){ r[0]=0x80000000; }else{ memset(marker,0,sizeof(marker)); for(i=0;i<n;i++){ long length=l[i]; if(length){ if (length < 0 || length >= MARKER_SIZE) { ALOGE("b/23881715"); return 1; } ogg_uint32_t entry=marker[length]; long chase=0; if(count && !entry)return -1; /* overpopulated tree! */ /* chase the tree as far as it's already populated, fill in past */ for(j=0;j<length-1;j++){ int bit=(entry>>(length-j-1))&1; if(chase>=top){ if (chase < 0 || chase >= n) return 1; top++; r[chase*2]=top; r[chase*2+1]=0; }else if (chase < 0 || chase >= n || chase*2+bit > n*2+1) return 1; if(!r[chase*2+bit]) r[chase*2+bit]=top; chase=r[chase*2+bit]; if (chase < 0 || chase >= n) return 1; } { int bit=(entry>>(length-j-1))&1; if(chase>=top){ top++; r[chase*2+1]=0; } r[chase*2+bit]= decpack(i,count++,quantvals,b,opb,maptype) | 0x80000000; } /* Look to see if the next shorter marker points to the node above. if so, update it and repeat. */ for(j=length;j>0;j--){ if(marker[j]&1){ marker[j]=marker[j-1]<<1; break; } marker[j]++; } /* prune the tree; the implicit invariant says all the longer markers were dangling from our just-taken node. Dangle them from our *new* node. */ for(j=length+1;j<MARKER_SIZE;j++) if((marker[j]>>1) == entry){ entry=marker[j]; marker[j]=marker[j-1]<<1; }else break; } } } /* sanity check the huffman tree; an underpopulated tree must be rejected. The only exception is the one-node pseudo-nil tree, which appears to be underpopulated because the tree doesn't really exist; there's only one possible 'codeword' or zero bits, but the above tree-gen code doesn't mark that. */ if(b->used_entries != 1){ for(i=1;i<MARKER_SIZE;i++) if(marker[i] & (0xffffffffUL>>(32-i))){ return 1; } } return 0; }
173,982
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; } Commit Message: CWE ID: CWE-200
xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->options -= XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; }
164,728
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_le_3byte (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; } ; } /* header_put_le_3byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_le_3byte (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; } /* header_put_le_3byte */
170,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Cluster::GetPosition() const { const long long pos = m_element_start - m_pSegment->m_start; assert(pos >= 0); return pos; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Cluster::GetPosition() const long Cluster::GetIndex() const { return m_index; } long long Cluster::GetPosition() const { const long long pos = m_element_start - m_pSegment->m_start; assert(pos >= 0); return pos; }
174,350
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CreatePrintSettingsDictionary(DictionaryValue* dict) { dict->SetBoolean(printing::kSettingLandscape, false); dict->SetBoolean(printing::kSettingCollate, false); dict->SetInteger(printing::kSettingColor, printing::GRAY); dict->SetBoolean(printing::kSettingPrintToPDF, true); dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX); dict->SetInteger(printing::kSettingCopies, 1); dict->SetString(printing::kSettingDeviceName, "dummy"); dict->SetString(printing::kPreviewUIAddr, "0xb33fbeef"); dict->SetInteger(printing::kPreviewRequestID, 12345); dict->SetBoolean(printing::kIsFirstRequest, true); dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS); dict->SetBoolean(printing::kSettingPreviewModifiable, false); dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false); dict->SetBoolean(printing::kSettingGenerateDraftData, 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
void CreatePrintSettingsDictionary(DictionaryValue* dict) { dict->SetBoolean(printing::kSettingLandscape, false); dict->SetBoolean(printing::kSettingCollate, false); dict->SetInteger(printing::kSettingColor, printing::GRAY); dict->SetBoolean(printing::kSettingPrintToPDF, true); dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX); dict->SetInteger(printing::kSettingCopies, 1); dict->SetString(printing::kSettingDeviceName, "dummy"); dict->SetInteger(printing::kPreviewUIID, 4); dict->SetInteger(printing::kPreviewRequestID, 12345); dict->SetBoolean(printing::kIsFirstRequest, true); dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS); dict->SetBoolean(printing::kSettingPreviewModifiable, false); dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false); dict->SetBoolean(printing::kSettingGenerateDraftData, true); }
170,858
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print) { int i, x; u_int c; const u_char *osp, *p; #define FETCH(c, sp, length) \ do { \ if (length < 1) \ goto pktend; \ ND_TCHECK(*sp); \ c = *sp++; \ length--; \ } while (0) osp = sp; FETCH(c, sp, length); if (c != IAC) goto pktend; FETCH(c, sp, length); if (c == IAC) { /* <IAC><IAC>! */ if (print) ND_PRINT((ndo, "IAC IAC")); goto done; } i = c - TELCMD_FIRST; if (i < 0 || i > IAC - TELCMD_FIRST) goto pktend; switch (c) { case DONT: case DO: case WONT: case WILL: case SB: /* DONT/DO/WONT/WILL x */ FETCH(x, sp, length); if (x >= 0 && x < NTELOPTS) { if (print) ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x])); } else { if (print) ND_PRINT((ndo, "%s %#x", telcmds[i], x)); } if (c != SB) break; /* IAC SB .... IAC SE */ p = sp; while (length > (u_int)(p + 1 - sp)) { ND_TCHECK2(*p, 2); if (p[0] == IAC && p[1] == SE) break; p++; } if (*p != IAC) goto pktend; switch (x) { case TELOPT_AUTHENTICATION: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype))); break; case TELOPT_ENCRYPT: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype))); break; default: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds))); break; } while (p > sp) { FETCH(x, sp, length); if (print) ND_PRINT((ndo, " %#x", x)); } /* terminating IAC SE */ if (print) ND_PRINT((ndo, " SE")); sp += 2; break; default: if (print) ND_PRINT((ndo, "%s", telcmds[i])); goto done; } done: return sp - osp; trunc: ND_PRINT((ndo, "%s", tstr)); pktend: return -1; #undef FETCH } Commit Message: CVE-2017-12988/TELNET: Add a missing bounds check. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print) { int i, x; u_int c; const u_char *osp, *p; #define FETCH(c, sp, length) \ do { \ if (length < 1) \ goto pktend; \ ND_TCHECK(*sp); \ c = *sp++; \ length--; \ } while (0) osp = sp; FETCH(c, sp, length); if (c != IAC) goto pktend; FETCH(c, sp, length); if (c == IAC) { /* <IAC><IAC>! */ if (print) ND_PRINT((ndo, "IAC IAC")); goto done; } i = c - TELCMD_FIRST; if (i < 0 || i > IAC - TELCMD_FIRST) goto pktend; switch (c) { case DONT: case DO: case WONT: case WILL: case SB: /* DONT/DO/WONT/WILL x */ FETCH(x, sp, length); if (x >= 0 && x < NTELOPTS) { if (print) ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x])); } else { if (print) ND_PRINT((ndo, "%s %#x", telcmds[i], x)); } if (c != SB) break; /* IAC SB .... IAC SE */ p = sp; while (length > (u_int)(p + 1 - sp)) { ND_TCHECK2(*p, 2); if (p[0] == IAC && p[1] == SE) break; p++; } ND_TCHECK(*p); if (*p != IAC) goto pktend; switch (x) { case TELOPT_AUTHENTICATION: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype))); break; case TELOPT_ENCRYPT: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype))); break; default: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds))); break; } while (p > sp) { FETCH(x, sp, length); if (print) ND_PRINT((ndo, " %#x", x)); } /* terminating IAC SE */ if (print) ND_PRINT((ndo, " SE")); sp += 2; break; default: if (print) ND_PRINT((ndo, "%s", telcmds[i])); goto done; } done: return sp - osp; trunc: ND_PRINT((ndo, "%s", tstr)); pktend: return -1; #undef FETCH }
167,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h) { uint32_t *buf32; uint32_t pix32; int shift[3]; int *prev; int here[3], upper[3], left[3], upperleft[3]; int prediction; int x, y, c; buf32 = (uint32_t *)buf; memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int)); if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) == (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) { shift[0] = vs->clientds.pf.rshift; shift[1] = vs->clientds.pf.gshift; shift[2] = vs->clientds.pf.bshift; } else { shift[0] = 24 - vs->clientds.pf.rshift; shift[1] = 24 - vs->clientds.pf.gshift; shift[2] = 24 - vs->clientds.pf.bshift; } for (y = 0; y < h; y++) { for (c = 0; c < 3; c++) { upper[c] = 0; here[c] = 0; } prev = (int *)vs->tight.gradient.buffer; for (x = 0; x < w; x++) { pix32 = *buf32++; for (c = 0; c < 3; c++) { upperleft[c] = upper[c]; left[c] = here[c]; upper[c] = *prev; here[c] = (int)(pix32 >> shift[c] & 0xFF); *prev++ = here[c]; prediction = left[c] + upper[c] - upperleft[c]; if (prediction < 0) { prediction = 0; } else if (prediction > 0xFF) { prediction = 0xFF; } *buf++ = (char)(here[c] - prediction); } } } } Commit Message: CWE ID: CWE-125
tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h) { uint32_t *buf32; uint32_t pix32; int shift[3]; int *prev; int here[3], upper[3], left[3], upperleft[3]; int prediction; int x, y, c; buf32 = (uint32_t *)buf; memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int)); if (1 /* FIXME: (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) == (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) */) { shift[0] = vs->client_pf.rshift; shift[1] = vs->client_pf.gshift; shift[2] = vs->client_pf.bshift; } else { shift[0] = 24 - vs->client_pf.rshift; shift[1] = 24 - vs->client_pf.gshift; shift[2] = 24 - vs->client_pf.bshift; } for (y = 0; y < h; y++) { for (c = 0; c < 3; c++) { upper[c] = 0; here[c] = 0; } prev = (int *)vs->tight.gradient.buffer; for (x = 0; x < w; x++) { pix32 = *buf32++; for (c = 0; c < 3; c++) { upperleft[c] = upper[c]; left[c] = here[c]; upper[c] = *prev; here[c] = (int)(pix32 >> shift[c] & 0xFF); *prev++ = here[c]; prediction = left[c] + upper[c] - upperleft[c]; if (prediction < 0) { prediction = 0; } else if (prediction > 0xFF) { prediction = 0xFF; } *buf++ = (char)(here[c] - prediction); } } } }
165,467