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: int main( int /*argc*/, char ** argv) { InitializeMagick(*argv); int failures=0; try { string srcdir(""); if(getenv("SRCDIR") != 0) srcdir = getenv("SRCDIR"); list<Image> imageList; readImages( &imageList, srcdir + "test_image_anim.miff" ); Image appended; appendImages( &appended, imageList.begin(), imageList.end() ); if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) && ( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) && ( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) && ( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" )) { ++failures; cout << "Line: " << __LINE__ << " Horizontal append failed, signature = " << appended.signature() << endl; appended.write("appendImages_horizontal_out.miff"); } appendImages( &appended, imageList.begin(), imageList.end(), true ); if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) && ( appended.signature() != "0909f7ffa7c6ea410fb2ebfdbcb19d61b19c4bd271851ce3bd51662519dc2b58" ) && ( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) && ( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" )) { ++failures; cout << "Line: " << __LINE__ << " Vertical append failed, signature = " << appended.signature() << endl; appended.write("appendImages_vertical_out.miff"); } } catch( Exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } catch( exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } if ( failures ) { cout << failures << " failures" << endl; return 1; } return 0; } Commit Message: Fix signature mismatch CWE ID: CWE-369
int main( int /*argc*/, char ** argv) { InitializeMagick(*argv); int failures=0; try { string srcdir(""); if(getenv("SRCDIR") != 0) srcdir = getenv("SRCDIR"); list<Image> imageList; readImages( &imageList, srcdir + "test_image_anim.miff" ); Image appended; appendImages( &appended, imageList.begin(), imageList.end() ); if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) && ( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) && ( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) && ( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" )) { ++failures; cout << "Line: " << __LINE__ << " Horizontal append failed, signature = " << appended.signature() << endl; appended.write("appendImages_horizontal_out.miff"); } appendImages( &appended, imageList.begin(), imageList.end(), true ); if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) && ( appended.signature() != "f3590c183018757da798613a23505ab9600b35935988eee12f096cb6219f2bc3" ) && ( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) && ( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" )) { ++failures; cout << "Line: " << __LINE__ << " Vertical append failed, signature = " << appended.signature() << endl; appended.write("appendImages_vertical_out.miff"); } } catch( Exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } catch( exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } if ( failures ) { cout << failures << " failures" << endl; return 1; } return 0; }
170,112
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_pixel_add_alpha(image_pixel *this, PNG_CONST standard_display *display) { if (this->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(this); if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0) { if (this->colour_type == PNG_COLOR_TYPE_GRAY) { if (this->bit_depth < 8) this->bit_depth = 8; if (this->have_tRNS) { this->have_tRNS = 0; /* Check the input, original, channel value here against the * original tRNS gray chunk valie. */ if (this->red == display->transparent.red) this->alphaf = 0; else this->alphaf = 1; } else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } else if (this->colour_type == PNG_COLOR_TYPE_RGB) { if (this->have_tRNS) { this->have_tRNS = 0; /* Again, check the exact input values, not the current transformed * value! */ if (this->red == display->transparent.red && this->green == display->transparent.green && this->blue == display->transparent.blue) this->alphaf = 0; else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; } } /* The error in the alpha is zero and the sBIT value comes from the * original sBIT data (actually it will always be the original bit depth). */ this->alphae = 0; this->alpha_sBIT = display->alpha_sBIT; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_pixel_add_alpha(image_pixel *this, PNG_CONST standard_display *display) image_pixel_add_alpha(image_pixel *this, const standard_display *display, int for_background) { if (this->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(this); if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0) { if (this->colour_type == PNG_COLOR_TYPE_GRAY) { # if PNG_LIBPNG_VER < 10700 if (!for_background && this->bit_depth < 8) this->bit_depth = this->sample_depth = 8; # endif if (this->have_tRNS) { /* After 1.7 the expansion of bit depth only happens if there is a * tRNS chunk to expand at this point. */ # if PNG_LIBPNG_VER >= 10700 if (!for_background && this->bit_depth < 8) this->bit_depth = this->sample_depth = 8; # endif this->have_tRNS = 0; /* Check the input, original, channel value here against the * original tRNS gray chunk valie. */ if (this->red == display->transparent.red) this->alphaf = 0; else this->alphaf = 1; } else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } else if (this->colour_type == PNG_COLOR_TYPE_RGB) { if (this->have_tRNS) { this->have_tRNS = 0; /* Again, check the exact input values, not the current transformed * value! */ if (this->red == display->transparent.red && this->green == display->transparent.green && this->blue == display->transparent.blue) this->alphaf = 0; else this->alphaf = 1; } else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; } /* The error in the alpha is zero and the sBIT value comes from the * original sBIT data (actually it will always be the original bit depth). */ this->alphae = 0; this->alpha_sBIT = display->alpha_sBIT; } }
173,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void impeg2d_dec_user_data(dec_state_t *ps_dec) { UWORD32 u4_start_code; stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while(u4_start_code == USER_DATA_START_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) { impeg2d_bit_stream_flush(ps_stream,8); } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
void impeg2d_dec_user_data(dec_state_t *ps_dec) { UWORD32 u4_start_code; stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while(u4_start_code == USER_DATA_START_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); while((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_stream->u4_offset < ps_stream->u4_max_offset)) { impeg2d_bit_stream_flush(ps_stream,8); } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } }
173,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : saml2md::DynamicMetadataProvider(e), m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)), m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)), m_encoded(true), m_trust(nullptr) { const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst); if (child && child->hasChildNodes()) { auto_ptr_char s(child->getFirstChild()->getNodeValue()); if (s.get() && *s.get()) { m_subst = s.get(); m_encoded = XMLHelper::getAttrBool(child, true, encoded); m_hashed = XMLHelper::getAttrString(child, nullptr, hashed); } } if (m_subst.empty()) { child = XMLHelper::getFirstChildElement(e, Regex); if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) { m_match = XMLHelper::getAttrString(child, nullptr, match); auto_ptr_char repl(child->getFirstChild()->getNodeValue()); if (repl.get() && *repl.get()) m_regex = repl.get(); } } if (!m_ignoreTransport) { child = XMLHelper::getFirstChildElement(e, _TrustEngine); string t = XMLHelper::getAttrString(child, nullptr, _type); if (!t.empty()) { TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child); if (!dynamic_cast<X509TrustEngine*>(trust)) { delete trust; throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin."); } m_trust.reset(dynamic_cast<X509TrustEngine*>(trust)); m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr)); } if (!m_trust.get() || !m_dummyCR.get()) throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true."); } } Commit Message: CWE ID: CWE-347
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : saml2md::DynamicMetadataProvider(e), MetadataProvider(e), m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)), m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)), m_encoded(true), m_trust(nullptr) { const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst); if (child && child->hasChildNodes()) { auto_ptr_char s(child->getFirstChild()->getNodeValue()); if (s.get() && *s.get()) { m_subst = s.get(); m_encoded = XMLHelper::getAttrBool(child, true, encoded); m_hashed = XMLHelper::getAttrString(child, nullptr, hashed); } } if (m_subst.empty()) { child = XMLHelper::getFirstChildElement(e, Regex); if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) { m_match = XMLHelper::getAttrString(child, nullptr, match); auto_ptr_char repl(child->getFirstChild()->getNodeValue()); if (repl.get() && *repl.get()) m_regex = repl.get(); } } if (!m_ignoreTransport) { child = XMLHelper::getFirstChildElement(e, _TrustEngine); string t = XMLHelper::getAttrString(child, nullptr, _type); if (!t.empty()) { TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child); if (!dynamic_cast<X509TrustEngine*>(trust)) { delete trust; throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin."); } m_trust.reset(dynamic_cast<X509TrustEngine*>(trust)); m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr)); } if (!m_trust.get() || !m_dummyCR.get()) throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true."); } }
164,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 addArgumentToVtab(Parse *pParse){ if( pParse->sArg.z && pParse->pNewTable ){ const char *z = (const char*)pParse->sArg.z; int n = pParse->sArg.n; sqlite3 *db = pParse->db; addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); } } Commit Message: sqlite: backport bugfixes for dbfuzz2 Bug: 952406 Change-Id: Icbec429742048d6674828726c96d8e265c41b595 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1568152 Reviewed-by: Chris Mumford <cmumford@google.com> Commit-Queue: Darwin Huang <huangdarwin@chromium.org> Cr-Commit-Position: refs/heads/master@{#651030} CWE ID: CWE-190
static void addArgumentToVtab(Parse *pParse){ if( pParse->sArg.z && pParse->pNewTable ){ const char *z = (const char*)pParse->sArg.z; int n = pParse->sArg.n; sqlite3 *db = pParse->db; addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); } }
173,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SerializeNotificationDatabaseData(const NotificationDatabaseData& input, std::string* output) { DCHECK(output); scoped_ptr<NotificationDatabaseDataProto::NotificationData> payload( new NotificationDatabaseDataProto::NotificationData()); const PlatformNotificationData& notification_data = input.notification_data; payload->set_title(base::UTF16ToUTF8(notification_data.title)); switch (notification_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT); break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT); break; case PlatformNotificationData::DIRECTION_AUTO: payload->set_direction( NotificationDatabaseDataProto::NotificationData::AUTO); break; } payload->set_lang(notification_data.lang); payload->set_body(base::UTF16ToUTF8(notification_data.body)); payload->set_tag(notification_data.tag); payload->set_icon(notification_data.icon.spec()); for (size_t i = 0; i < notification_data.vibration_pattern.size(); ++i) payload->add_vibration_pattern(notification_data.vibration_pattern[i]); payload->set_timestamp(notification_data.timestamp.ToInternalValue()); payload->set_silent(notification_data.silent); payload->set_require_interaction(notification_data.require_interaction); if (notification_data.data.size()) { payload->set_data(&notification_data.data.front(), notification_data.data.size()); } for (const PlatformNotificationAction& action : notification_data.actions) { NotificationDatabaseDataProto::NotificationAction* payload_action = payload->add_actions(); payload_action->set_action(action.action); payload_action->set_title(base::UTF16ToUTF8(action.title)); } NotificationDatabaseDataProto message; message.set_notification_id(input.notification_id); message.set_origin(input.origin.spec()); message.set_service_worker_registration_id( input.service_worker_registration_id); message.set_allocated_notification_data(payload.release()); return message.SerializeToString(output); } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
bool SerializeNotificationDatabaseData(const NotificationDatabaseData& input, std::string* output) { DCHECK(output); scoped_ptr<NotificationDatabaseDataProto::NotificationData> payload( new NotificationDatabaseDataProto::NotificationData()); const PlatformNotificationData& notification_data = input.notification_data; payload->set_title(base::UTF16ToUTF8(notification_data.title)); switch (notification_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT); break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT); break; case PlatformNotificationData::DIRECTION_AUTO: payload->set_direction( NotificationDatabaseDataProto::NotificationData::AUTO); break; } payload->set_lang(notification_data.lang); payload->set_body(base::UTF16ToUTF8(notification_data.body)); payload->set_tag(notification_data.tag); payload->set_icon(notification_data.icon.spec()); for (size_t i = 0; i < notification_data.vibration_pattern.size(); ++i) payload->add_vibration_pattern(notification_data.vibration_pattern[i]); payload->set_timestamp(notification_data.timestamp.ToInternalValue()); payload->set_silent(notification_data.silent); payload->set_require_interaction(notification_data.require_interaction); if (notification_data.data.size()) { payload->set_data(&notification_data.data.front(), notification_data.data.size()); } for (const PlatformNotificationAction& action : notification_data.actions) { NotificationDatabaseDataProto::NotificationAction* payload_action = payload->add_actions(); payload_action->set_action(action.action); payload_action->set_title(base::UTF16ToUTF8(action.title)); payload_action->set_icon(action.icon.spec()); } NotificationDatabaseDataProto message; message.set_notification_id(input.notification_id); message.set_origin(input.origin.spec()); message.set_service_worker_registration_id( input.service_worker_registration_id); message.set_allocated_notification_data(payload.release()); return message.SerializeToString(output); }
171,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AudioOutputDevice::OnStreamCreated( base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle, int length) { DCHECK(message_loop()->BelongsToCurrentThread()); #if defined(OS_WIN) DCHECK(handle); DCHECK(socket_handle); #else DCHECK_GE(handle.fd, 0); DCHECK_GE(socket_handle, 0); #endif DCHECK(stream_id_); if (!audio_thread_.get()) return; DCHECK(audio_thread_->IsStopped()); audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback( audio_parameters_, input_channels_, handle, length, callback_)); audio_thread_->Start( audio_callback_.get(), socket_handle, "AudioOutputDevice"); is_started_ = true; if (play_on_start_) PlayOnIOThread(); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void AudioOutputDevice::OnStreamCreated( base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle, int length) { DCHECK(message_loop()->BelongsToCurrentThread()); #if defined(OS_WIN) DCHECK(handle); DCHECK(socket_handle); #else DCHECK_GE(handle.fd, 0); DCHECK_GE(socket_handle, 0); #endif DCHECK(stream_id_); DCHECK(audio_thread_.IsStopped()); audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback( audio_parameters_, input_channels_, handle, length, callback_)); audio_thread_.Start(audio_callback_.get(), socket_handle, "AudioOutputDevice"); is_started_ = true; if (play_on_start_) PlayOnIOThread(); }
170,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false) { InitView(); } Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period. BUG=394518 Review-Url: https://codereview.chromium.org/2716353003 Cr-Commit-Position: refs/heads/master@{#461933} CWE ID: CWE-20
ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false), install_button_enabled_(false) { InitView(); }
173,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bootp_print(netdissect_options *ndo, register const u_char *cp, u_int length) { register const struct bootp *bp; static const u_char vm_cmu[4] = VM_CMU; static const u_char vm_rfc1048[4] = VM_RFC1048; bp = (const struct bootp *)cp; ND_TCHECK(bp->bp_op); ND_PRINT((ndo, "BOOTP/DHCP, %s", tok2str(bootp_op_values, "unknown (0x%02x)", bp->bp_op))); ND_TCHECK(bp->bp_hlen); if (bp->bp_htype == 1 && bp->bp_hlen == 6 && bp->bp_op == BOOTPREQUEST) { ND_TCHECK2(bp->bp_chaddr[0], 6); ND_PRINT((ndo, " from %s", etheraddr_string(ndo, bp->bp_chaddr))); } ND_PRINT((ndo, ", length %u", length)); if (!ndo->ndo_vflag) return; ND_TCHECK(bp->bp_secs); /* The usual hardware address type is 1 (10Mb Ethernet) */ if (bp->bp_htype != 1) ND_PRINT((ndo, ", htype %d", bp->bp_htype)); /* The usual length for 10Mb Ethernet address is 6 bytes */ if (bp->bp_htype != 1 || bp->bp_hlen != 6) ND_PRINT((ndo, ", hlen %d", bp->bp_hlen)); /* Only print interesting fields */ if (bp->bp_hops) ND_PRINT((ndo, ", hops %d", bp->bp_hops)); if (EXTRACT_32BITS(&bp->bp_xid)) ND_PRINT((ndo, ", xid 0x%x", EXTRACT_32BITS(&bp->bp_xid))); if (EXTRACT_16BITS(&bp->bp_secs)) ND_PRINT((ndo, ", secs %d", EXTRACT_16BITS(&bp->bp_secs))); ND_PRINT((ndo, ", Flags [%s]", bittok2str(bootp_flag_values, "none", EXTRACT_16BITS(&bp->bp_flags)))); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, " (0x%04x)", EXTRACT_16BITS(&bp->bp_flags))); /* Client's ip address */ ND_TCHECK(bp->bp_ciaddr); if (EXTRACT_32BITS(&bp->bp_ciaddr.s_addr)) ND_PRINT((ndo, "\n\t Client-IP %s", ipaddr_string(ndo, &bp->bp_ciaddr))); /* 'your' ip address (bootp client) */ ND_TCHECK(bp->bp_yiaddr); if (EXTRACT_32BITS(&bp->bp_yiaddr.s_addr)) ND_PRINT((ndo, "\n\t Your-IP %s", ipaddr_string(ndo, &bp->bp_yiaddr))); /* Server's ip address */ ND_TCHECK(bp->bp_siaddr); if (EXTRACT_32BITS(&bp->bp_siaddr.s_addr)) ND_PRINT((ndo, "\n\t Server-IP %s", ipaddr_string(ndo, &bp->bp_siaddr))); /* Gateway's ip address */ ND_TCHECK(bp->bp_giaddr); if (EXTRACT_32BITS(&bp->bp_giaddr.s_addr)) ND_PRINT((ndo, "\n\t Gateway-IP %s", ipaddr_string(ndo, &bp->bp_giaddr))); /* Client's Ethernet address */ if (bp->bp_htype == 1 && bp->bp_hlen == 6) { ND_TCHECK2(bp->bp_chaddr[0], 6); ND_PRINT((ndo, "\n\t Client-Ethernet-Address %s", etheraddr_string(ndo, bp->bp_chaddr))); } ND_TCHECK2(bp->bp_sname[0], 1); /* check first char only */ if (*bp->bp_sname) { ND_PRINT((ndo, "\n\t sname \"")); if (fn_printztn(ndo, bp->bp_sname, (u_int)sizeof bp->bp_sname, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); ND_PRINT((ndo, "%s", tstr + 1)); return; } ND_PRINT((ndo, "\"")); } ND_TCHECK2(bp->bp_file[0], 1); /* check first char only */ if (*bp->bp_file) { ND_PRINT((ndo, "\n\t file \"")); if (fn_printztn(ndo, bp->bp_file, (u_int)sizeof bp->bp_file, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); ND_PRINT((ndo, "%s", tstr + 1)); return; } ND_PRINT((ndo, "\"")); } /* Decode the vendor buffer */ ND_TCHECK(bp->bp_vend[0]); if (memcmp((const char *)bp->bp_vend, vm_rfc1048, sizeof(uint32_t)) == 0) rfc1048_print(ndo, bp->bp_vend); else if (memcmp((const char *)bp->bp_vend, vm_cmu, sizeof(uint32_t)) == 0) cmu_print(ndo, bp->bp_vend); else { uint32_t ul; ul = EXTRACT_32BITS(&bp->bp_vend); if (ul != 0) ND_PRINT((ndo, "\n\t Vendor-#0x%x", ul)); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: CVE-2017-13028/BOOTP: Add a bounds check before fetching data 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 cause 'tcpdump: pcap_loop: truncated dump file' CWE ID: CWE-125
bootp_print(netdissect_options *ndo, register const u_char *cp, u_int length) { register const struct bootp *bp; static const u_char vm_cmu[4] = VM_CMU; static const u_char vm_rfc1048[4] = VM_RFC1048; bp = (const struct bootp *)cp; ND_TCHECK(bp->bp_op); ND_PRINT((ndo, "BOOTP/DHCP, %s", tok2str(bootp_op_values, "unknown (0x%02x)", bp->bp_op))); ND_TCHECK(bp->bp_hlen); if (bp->bp_htype == 1 && bp->bp_hlen == 6 && bp->bp_op == BOOTPREQUEST) { ND_TCHECK2(bp->bp_chaddr[0], 6); ND_PRINT((ndo, " from %s", etheraddr_string(ndo, bp->bp_chaddr))); } ND_PRINT((ndo, ", length %u", length)); if (!ndo->ndo_vflag) return; ND_TCHECK(bp->bp_secs); /* The usual hardware address type is 1 (10Mb Ethernet) */ if (bp->bp_htype != 1) ND_PRINT((ndo, ", htype %d", bp->bp_htype)); /* The usual length for 10Mb Ethernet address is 6 bytes */ if (bp->bp_htype != 1 || bp->bp_hlen != 6) ND_PRINT((ndo, ", hlen %d", bp->bp_hlen)); /* Only print interesting fields */ if (bp->bp_hops) ND_PRINT((ndo, ", hops %d", bp->bp_hops)); if (EXTRACT_32BITS(&bp->bp_xid)) ND_PRINT((ndo, ", xid 0x%x", EXTRACT_32BITS(&bp->bp_xid))); if (EXTRACT_16BITS(&bp->bp_secs)) ND_PRINT((ndo, ", secs %d", EXTRACT_16BITS(&bp->bp_secs))); ND_TCHECK(bp->bp_flags); ND_PRINT((ndo, ", Flags [%s]", bittok2str(bootp_flag_values, "none", EXTRACT_16BITS(&bp->bp_flags)))); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, " (0x%04x)", EXTRACT_16BITS(&bp->bp_flags))); /* Client's ip address */ ND_TCHECK(bp->bp_ciaddr); if (EXTRACT_32BITS(&bp->bp_ciaddr.s_addr)) ND_PRINT((ndo, "\n\t Client-IP %s", ipaddr_string(ndo, &bp->bp_ciaddr))); /* 'your' ip address (bootp client) */ ND_TCHECK(bp->bp_yiaddr); if (EXTRACT_32BITS(&bp->bp_yiaddr.s_addr)) ND_PRINT((ndo, "\n\t Your-IP %s", ipaddr_string(ndo, &bp->bp_yiaddr))); /* Server's ip address */ ND_TCHECK(bp->bp_siaddr); if (EXTRACT_32BITS(&bp->bp_siaddr.s_addr)) ND_PRINT((ndo, "\n\t Server-IP %s", ipaddr_string(ndo, &bp->bp_siaddr))); /* Gateway's ip address */ ND_TCHECK(bp->bp_giaddr); if (EXTRACT_32BITS(&bp->bp_giaddr.s_addr)) ND_PRINT((ndo, "\n\t Gateway-IP %s", ipaddr_string(ndo, &bp->bp_giaddr))); /* Client's Ethernet address */ if (bp->bp_htype == 1 && bp->bp_hlen == 6) { ND_TCHECK2(bp->bp_chaddr[0], 6); ND_PRINT((ndo, "\n\t Client-Ethernet-Address %s", etheraddr_string(ndo, bp->bp_chaddr))); } ND_TCHECK2(bp->bp_sname[0], 1); /* check first char only */ if (*bp->bp_sname) { ND_PRINT((ndo, "\n\t sname \"")); if (fn_printztn(ndo, bp->bp_sname, (u_int)sizeof bp->bp_sname, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); ND_PRINT((ndo, "%s", tstr + 1)); return; } ND_PRINT((ndo, "\"")); } ND_TCHECK2(bp->bp_file[0], 1); /* check first char only */ if (*bp->bp_file) { ND_PRINT((ndo, "\n\t file \"")); if (fn_printztn(ndo, bp->bp_file, (u_int)sizeof bp->bp_file, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); ND_PRINT((ndo, "%s", tstr + 1)); return; } ND_PRINT((ndo, "\"")); } /* Decode the vendor buffer */ ND_TCHECK(bp->bp_vend[0]); if (memcmp((const char *)bp->bp_vend, vm_rfc1048, sizeof(uint32_t)) == 0) rfc1048_print(ndo, bp->bp_vend); else if (memcmp((const char *)bp->bp_vend, vm_cmu, sizeof(uint32_t)) == 0) cmu_print(ndo, bp->bp_vend); else { uint32_t ul; ul = EXTRACT_32BITS(&bp->bp_vend); if (ul != 0) ND_PRINT((ndo, "\n\t Vendor-#0x%x", ul)); } return; trunc: ND_PRINT((ndo, "%s", tstr)); }
170,027
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UserSelectionScreen::FillUserMojoStruct( const user_manager::User* user, bool is_owner, bool is_signin_to_add, proximity_auth::mojom::AuthType auth_type, const std::vector<std::string>* public_session_recommended_locales, ash::mojom::LoginUserInfo* user_info) { user_info->basic_user_info = ash::mojom::UserInfo::New(); user_info->basic_user_info->type = user->GetType(); user_info->basic_user_info->account_id = user->GetAccountId(); user_info->basic_user_info->display_name = base::UTF16ToUTF8(user->GetDisplayName()); user_info->basic_user_info->display_email = user->display_email(); user_info->basic_user_info->avatar = BuildMojoUserAvatarForUser(user); user_info->auth_type = auth_type; user_info->is_signed_in = user->is_logged_in(); user_info->is_device_owner = is_owner; user_info->can_remove = CanRemoveUser(user); user_info->allow_fingerprint_unlock = AllowFingerprintForUser(user); if (!is_signin_to_add) { user_info->is_multiprofile_allowed = true; } else { GetMultiProfilePolicy(user, &user_info->is_multiprofile_allowed, &user_info->multiprofile_policy); } if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) { user_info->public_account_info = ash::mojom::PublicAccountInfo::New(); std::string domain; if (GetEnterpriseDomain(&domain)) user_info->public_account_info->enterprise_domain = domain; std::string selected_locale; bool has_multiple_locales; std::unique_ptr<base::ListValue> available_locales = GetPublicSessionLocales(public_session_recommended_locales, &selected_locale, &has_multiple_locales); DCHECK(available_locales); user_info->public_account_info->available_locales = lock_screen_utils::FromListValueToLocaleItem( std::move(available_locales)); user_info->public_account_info->default_locale = selected_locale; user_info->public_account_info->show_advanced_view = has_multiple_locales; } } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void UserSelectionScreen::FillUserMojoStruct(
172,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssize_t v9fs_list_xattr(FsContext *ctx, const char *path, void *value, size_t vsize) { ssize_t size = 0; void *ovalue = value; XattrOperations *xops; char *orig_value, *orig_value_start; ssize_t xattr_len, parsed_len = 0, attr_len; char *dirpath, *name; int dirfd; /* Get the actual len */ dirpath = g_path_get_dirname(path); dirfd = local_opendir_nofollow(ctx, dirpath); g_free(dirpath); if (dirfd == -1) { return -1; } name = g_path_get_basename(path); xattr_len = flistxattrat_nofollow(dirfd, name, value, 0); if (xattr_len <= 0) { g_free(name); close_preserve_errno(dirfd); return xattr_len; } /* Now fetch the xattr and find the actual size */ orig_value = g_malloc(xattr_len); xattr_len = flistxattrat_nofollow(dirfd, name, orig_value, xattr_len); g_free(name); close_preserve_errno(dirfd); if (xattr_len < 0) { return -1; } orig_value_start = orig_value; while (xattr_len > parsed_len) { xops = get_xattr_operations(ctx->xops, orig_value); if (!xops) { goto next_entry; } if (!value) { size += xops->listxattr(ctx, path, orig_value, value, vsize); } else { size = xops->listxattr(ctx, path, orig_value, value, vsize); if (size < 0) { goto err_out; } value += size; vsize -= size; } next_entry: /* Got the next entry */ attr_len = strlen(orig_value) + 1; parsed_len += attr_len; orig_value += attr_len; } if (value) { size = value - ovalue; } err_out: g_free(orig_value_start); return size; } Commit Message: CWE ID: CWE-772
ssize_t v9fs_list_xattr(FsContext *ctx, const char *path, void *value, size_t vsize) { ssize_t size = 0; void *ovalue = value; XattrOperations *xops; char *orig_value, *orig_value_start; ssize_t xattr_len, parsed_len = 0, attr_len; char *dirpath, *name; int dirfd; /* Get the actual len */ dirpath = g_path_get_dirname(path); dirfd = local_opendir_nofollow(ctx, dirpath); g_free(dirpath); if (dirfd == -1) { return -1; } name = g_path_get_basename(path); xattr_len = flistxattrat_nofollow(dirfd, name, value, 0); if (xattr_len <= 0) { g_free(name); close_preserve_errno(dirfd); return xattr_len; } /* Now fetch the xattr and find the actual size */ orig_value = g_malloc(xattr_len); xattr_len = flistxattrat_nofollow(dirfd, name, orig_value, xattr_len); g_free(name); close_preserve_errno(dirfd); if (xattr_len < 0) { g_free(orig_value); return -1; } orig_value_start = orig_value; while (xattr_len > parsed_len) { xops = get_xattr_operations(ctx->xops, orig_value); if (!xops) { goto next_entry; } if (!value) { size += xops->listxattr(ctx, path, orig_value, value, vsize); } else { size = xops->listxattr(ctx, path, orig_value, value, vsize); if (size < 0) { goto err_out; } value += size; vsize -= size; } next_entry: /* Got the next entry */ attr_len = strlen(orig_value) + 1; parsed_len += attr_len; orig_value += attr_len; } if (value) { size = value - ovalue; } err_out: g_free(orig_value_start); return size; }
164,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: chunk_grow(chunk_t *chunk, size_t sz) { off_t offset; size_t memlen_orig = chunk->memlen; tor_assert(sz > chunk->memlen); offset = chunk->data - chunk->mem; chunk = tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz)); chunk->memlen = sz; chunk->data = chunk->mem + offset; #ifdef DEBUG_CHUNK_ALLOC tor_assert(chunk->DBG_alloc == CHUNK_ALLOC_SIZE(memlen_orig)); chunk->DBG_alloc = CHUNK_ALLOC_SIZE(sz); #endif total_bytes_allocated_in_chunks += CHUNK_ALLOC_SIZE(sz) - CHUNK_ALLOC_SIZE(memlen_orig); return chunk; } Commit Message: Add a one-word sentinel value of 0x0 at the end of each buf_t chunk This helps protect against bugs where any part of a buf_t's memory is passed to a function that expects a NUL-terminated input. It also closes TROVE-2016-10-001 (aka bug 20384). CWE ID: CWE-119
chunk_grow(chunk_t *chunk, size_t sz) { off_t offset; const size_t memlen_orig = chunk->memlen; const size_t orig_alloc = CHUNK_ALLOC_SIZE(memlen_orig); const size_t new_alloc = CHUNK_ALLOC_SIZE(sz); tor_assert(sz > chunk->memlen); offset = chunk->data - chunk->mem; chunk = tor_realloc(chunk, new_alloc); chunk->memlen = sz; chunk->data = chunk->mem + offset; #ifdef DEBUG_CHUNK_ALLOC tor_assert(chunk->DBG_alloc == orig_alloc); chunk->DBG_alloc = new_alloc; #endif total_bytes_allocated_in_chunks += new_alloc - orig_alloc; CHUNK_SET_SENTINEL(chunk, new_alloc); return chunk; }
168,757
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); } 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 bool SetImeConfig(const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == input_method::ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); }
170,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bpf_map_inc(struct bpf_map *map, bool uref) { atomic_inc(&map->refcnt); if (uref) atomic_inc(&map->usercnt); } Commit Message: bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Alexei Starovoitov <ast@kernel.org> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
void bpf_map_inc(struct bpf_map *map, bool uref) /* prog's and map's refcnt limit */ #define BPF_MAX_REFCNT 32768 struct bpf_map *bpf_map_inc(struct bpf_map *map, bool uref) { if (atomic_inc_return(&map->refcnt) > BPF_MAX_REFCNT) { atomic_dec(&map->refcnt); return ERR_PTR(-EBUSY); } if (uref) atomic_inc(&map->usercnt); return map; }
167,253
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) return code; code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; } Commit Message: Prevent KDC unset status assertion failures Assign status values if S4U2Self padata fails to decode, if an S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request uses an evidence ticket which does not match the canonicalized request server principal name. Reported by Samuel Cabrero. If a status value is not assigned during KDC processing, default to "UNKNOWN_REASON" rather than failing an assertion. This change will prevent future denial of service bugs due to similar mistakes, and will allow us to omit assigning status values for unlikely errors such as small memory allocation failures. CVE-2017-11368: In MIT krb5 1.7 and later, an authenticated attacker can cause an assertion failure in krb5kdc by sending an invalid S4U2Self or S4U2Proxy request. CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C ticket: 8599 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-617
kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) { *status = "DECODE_PA_FOR_USER"; return code; } code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; }
168,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LogoService::GetLogo(LogoCallbacks callbacks) { if (!template_url_service_) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider(); if (!template_url) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); GURL logo_url; if (command_line->HasSwitch(switches::kSearchProviderLogoURL)) { logo_url = GURL( command_line->GetSwitchValueASCII(switches::kSearchProviderLogoURL)); } else { #if defined(OS_ANDROID) logo_url = template_url->logo_url(); #endif } GURL base_url; GURL doodle_url; const bool is_google = template_url->url_ref().HasGoogleBaseURLs( template_url_service_->search_terms_data()); if (is_google) { base_url = GURL(template_url_service_->search_terms_data().GoogleBaseURLValue()); doodle_url = search_provider_logos::GetGoogleDoodleURL(base_url); } else if (base::FeatureList::IsEnabled(features::kThirdPartyDoodles)) { if (command_line->HasSwitch(switches::kThirdPartyDoodleURL)) { doodle_url = GURL( command_line->GetSwitchValueASCII(switches::kThirdPartyDoodleURL)); } else { std::string override_url = base::GetFieldTrialParamValueByFeature( features::kThirdPartyDoodles, features::kThirdPartyDoodlesOverrideUrlParam); if (!override_url.empty()) { doodle_url = GURL(override_url); } else { doodle_url = template_url->doodle_url(); } } base_url = doodle_url.GetOrigin(); } if (!logo_url.is_valid() && !doodle_url.is_valid()) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const bool use_fixed_logo = !doodle_url.is_valid(); if (!logo_tracker_) { std::unique_ptr<LogoCache> logo_cache = std::move(logo_cache_for_test_); if (!logo_cache) { logo_cache = std::make_unique<LogoCache>(cache_directory_); } std::unique_ptr<base::Clock> clock = std::move(clock_for_test_); if (!clock) { clock = std::make_unique<base::DefaultClock>(); } logo_tracker_ = std::make_unique<LogoTracker>( request_context_getter_, std::make_unique<LogoDelegateImpl>(std::move(image_decoder_)), std::move(logo_cache), std::move(clock)); } if (use_fixed_logo) { logo_tracker_->SetServerAPI( logo_url, base::Bind(&search_provider_logos::ParseFixedLogoResponse), base::Bind(&search_provider_logos::UseFixedLogoUrl)); } else if (is_google) { logo_tracker_->SetServerAPI( doodle_url, search_provider_logos::GetGoogleParseLogoResponseCallback(base_url), search_provider_logos::GetGoogleAppendQueryparamsCallback( use_gray_background_)); } else { logo_tracker_->SetServerAPI( doodle_url, base::Bind(&search_provider_logos::GoogleNewParseLogoResponse, base_url), base::Bind(&search_provider_logos::GoogleNewAppendQueryparamsToLogoURL, use_gray_background_)); } logo_tracker_->GetLogo(std::move(callbacks)); } 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 <sdefresne@chromium.org> Reviewed-by: Marc Treib <treib@chromium.org> Commit-Queue: Chris Pickel <sfiera@chromium.org> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void LogoService::GetLogo(LogoCallbacks callbacks) {
171,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 unsigned int variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int diff = ref[w * y + x] - src[w * y + x]; se += diff; sse += diff * diff; } //// Truncate high bit depth results by downshifting (with rounding) by: //// 2 * (bit_depth - 8) for sse //// (bit_depth - 8) for se } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static unsigned int variance_ref(const uint8_t *ref, const uint8_t *src, //// Truncate high bit depth results by downshifting (with rounding) by: //// 2 * (bit_depth - 8) for sse //// (bit_depth - 8) for se static void RoundHighBitDepth(int bit_depth, int64_t *se, uint64_t *sse) { switch (bit_depth) { case VPX_BITS_12: *sse = (*sse + 128) >> 8; *se = (*se + 8) >> 4; break; case VPX_BITS_10: *sse = (*sse + 8) >> 4; *se = (*se + 2) >> 2; break; case VPX_BITS_8: default: break; } }
174,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: z2grestore(i_ctx_t *i_ctx_p) { if (!restore_page_device(igs, gs_gstate_saved(igs))) return gs_grestore(igs); return push_callout(i_ctx_p, "%grestorepagedevice"); } Commit Message: CWE ID:
z2grestore(i_ctx_t *i_ctx_p) { int code = restore_page_device(i_ctx_p, igs, gs_gstate_saved(igs)); if (code < 0) return code; if (code == 0) return gs_grestore(igs); return push_callout(i_ctx_p, "%grestorepagedevice"); }
164,691
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InputMethodStatusConnection* GetInstance() { return Singleton<InputMethodStatusConnection, LeakySingletonTraits<InputMethodStatusConnection> >::get(); } 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
static InputMethodStatusConnection* GetInstance() { virtual void Connect() { MaybeRestoreConnections(); }
170,535
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType composition, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); if (!text.isEmpty()) document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing( isSpaceOrNewline(text[0])); insertText(document, text, frame->selection().computeVisibleSelectionInDOMTreeDeprecated(), options, composition, isIncrementalInsertion); } Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree| instead of |VisibleSelection| to reduce usage of |VisibleSelection| for improving code health. BUG=657237 TEST=n/a Review-Url: https://codereview.chromium.org/2733183002 Cr-Commit-Position: refs/heads/master@{#455368} CWE ID:
void TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType composition, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); if (!text.isEmpty()) document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing( isSpaceOrNewline(text[0])); insertText(document, text, frame->selection().selectionInDOMTree(), options, composition, isIncrementalInsertion); }
172,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_ofb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_ofb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); }
167,110
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void btif_config_save(void) { assert(alarm_timer != NULL); assert(config != NULL); alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save, NULL); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 CWE ID: CWE-119
void btif_config_save(void) { assert(alarm_timer != NULL); assert(config != NULL); alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save_cb, NULL); }
173,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: virtual void TearDown() { vpx_svc_release(&svc_); delete(decoder_); if (codec_initialized_) vpx_codec_destroy(&codec_); } 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 TearDown() { ReleaseEncoder(); delete(decoder_); } void InitializeEncoder() { const vpx_codec_err_t res = vpx_svc_init(&svc_, &codec_, vpx_codec_vp9_cx(), &codec_enc_); EXPECT_EQ(VPX_CODEC_OK, res); vpx_codec_control(&codec_, VP8E_SET_CPUUSED, 4); // Make the test faster vpx_codec_control(&codec_, VP9E_SET_TILE_COLUMNS, tile_columns_); vpx_codec_control(&codec_, VP9E_SET_TILE_ROWS, tile_rows_); codec_initialized_ = true; } void ReleaseEncoder() { vpx_svc_release(&svc_); if (codec_initialized_) vpx_codec_destroy(&codec_); codec_initialized_ = false; } void GetStatsData(std::string *const stats_buf) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *cx_pkt; while ((cx_pkt = vpx_codec_get_cx_data(&codec_, &iter)) != NULL) { if (cx_pkt->kind == VPX_CODEC_STATS_PKT) { EXPECT_GT(cx_pkt->data.twopass_stats.sz, 0U); ASSERT_TRUE(cx_pkt->data.twopass_stats.buf != NULL); stats_buf->append(static_cast<char*>(cx_pkt->data.twopass_stats.buf), cx_pkt->data.twopass_stats.sz); } } } void Pass1EncodeNFrames(const int n, const int layers, std::string *const stats_buf) { vpx_codec_err_t res; ASSERT_GT(n, 0); ASSERT_GT(layers, 0); svc_.spatial_layers = layers; codec_enc_.g_pass = VPX_RC_FIRST_PASS; InitializeEncoder(); libvpx_test::I420VideoSource video(test_file_name_, codec_enc_.g_w, codec_enc_.g_h, codec_enc_.g_timebase.den, codec_enc_.g_timebase.num, 0, 30); video.Begin(); for (int i = 0; i < n; ++i) { res = vpx_svc_encode(&svc_, &codec_, video.img(), video.pts(), video.duration(), VPX_DL_GOOD_QUALITY); ASSERT_EQ(VPX_CODEC_OK, res); GetStatsData(stats_buf); video.Next(); } // Flush encoder and test EOS packet. res = vpx_svc_encode(&svc_, &codec_, NULL, video.pts(), video.duration(), VPX_DL_GOOD_QUALITY); ASSERT_EQ(VPX_CODEC_OK, res); GetStatsData(stats_buf); ReleaseEncoder(); } void StoreFrames(const size_t max_frame_received, struct vpx_fixed_buf *const outputs, size_t *const frame_received) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *cx_pkt; while ((cx_pkt = vpx_codec_get_cx_data(&codec_, &iter)) != NULL) { if (cx_pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const size_t frame_size = cx_pkt->data.frame.sz; EXPECT_GT(frame_size, 0U); ASSERT_TRUE(cx_pkt->data.frame.buf != NULL); ASSERT_LT(*frame_received, max_frame_received); if (*frame_received == 0) EXPECT_EQ(1, !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY)); outputs[*frame_received].buf = malloc(frame_size + 16); ASSERT_TRUE(outputs[*frame_received].buf != NULL); memcpy(outputs[*frame_received].buf, cx_pkt->data.frame.buf, frame_size); outputs[*frame_received].sz = frame_size; ++(*frame_received); } } } void Pass2EncodeNFrames(std::string *const stats_buf, const int n, const int layers, struct vpx_fixed_buf *const outputs) { vpx_codec_err_t res; size_t frame_received = 0; ASSERT_TRUE(outputs != NULL); ASSERT_GT(n, 0); ASSERT_GT(layers, 0); svc_.spatial_layers = layers; codec_enc_.rc_target_bitrate = 500; if (codec_enc_.g_pass == VPX_RC_LAST_PASS) { ASSERT_TRUE(stats_buf != NULL); ASSERT_GT(stats_buf->size(), 0U); codec_enc_.rc_twopass_stats_in.buf = &(*stats_buf)[0]; codec_enc_.rc_twopass_stats_in.sz = stats_buf->size(); } InitializeEncoder(); libvpx_test::I420VideoSource video(test_file_name_, codec_enc_.g_w, codec_enc_.g_h, codec_enc_.g_timebase.den, codec_enc_.g_timebase.num, 0, 30); video.Begin(); for (int i = 0; i < n; ++i) { res = vpx_svc_encode(&svc_, &codec_, video.img(), video.pts(), video.duration(), VPX_DL_GOOD_QUALITY); ASSERT_EQ(VPX_CODEC_OK, res); StoreFrames(n, outputs, &frame_received); video.Next(); } // Flush encoder. res = vpx_svc_encode(&svc_, &codec_, NULL, 0, video.duration(), VPX_DL_GOOD_QUALITY); EXPECT_EQ(VPX_CODEC_OK, res); StoreFrames(n, outputs, &frame_received); EXPECT_EQ(frame_received, static_cast<size_t>(n)); ReleaseEncoder(); } void DecodeNFrames(const struct vpx_fixed_buf *const inputs, const int n) { int decoded_frames = 0; int received_frames = 0; ASSERT_TRUE(inputs != NULL); ASSERT_GT(n, 0); for (int i = 0; i < n; ++i) { ASSERT_TRUE(inputs[i].buf != NULL); ASSERT_GT(inputs[i].sz, 0U); const vpx_codec_err_t res_dec = decoder_->DecodeFrame(static_cast<const uint8_t *>(inputs[i].buf), inputs[i].sz); ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder_->DecodeError(); ++decoded_frames; DxDataIterator dec_iter = decoder_->GetDxData(); while (dec_iter.Next() != NULL) { ++received_frames; } } EXPECT_EQ(decoded_frames, n); EXPECT_EQ(received_frames, n); } void DropEnhancementLayers(struct vpx_fixed_buf *const inputs, const int num_super_frames, const int remained_spatial_layers) { ASSERT_TRUE(inputs != NULL); ASSERT_GT(num_super_frames, 0); ASSERT_GT(remained_spatial_layers, 0); for (int i = 0; i < num_super_frames; ++i) { uint32_t frame_sizes[8] = {0}; int frame_count = 0; int frames_found = 0; int frame; ASSERT_TRUE(inputs[i].buf != NULL); ASSERT_GT(inputs[i].sz, 0U); vpx_codec_err_t res = vp9_parse_superframe_index(static_cast<const uint8_t*>(inputs[i].buf), inputs[i].sz, frame_sizes, &frame_count, NULL, NULL); ASSERT_EQ(VPX_CODEC_OK, res); if (frame_count == 0) { // There's no super frame but only a single frame. ASSERT_EQ(1, remained_spatial_layers); } else { // Found a super frame. uint8_t *frame_data = static_cast<uint8_t*>(inputs[i].buf); uint8_t *frame_start = frame_data; for (frame = 0; frame < frame_count; ++frame) { // Looking for a visible frame. if (frame_data[0] & 0x02) { ++frames_found; if (frames_found == remained_spatial_layers) break; } frame_data += frame_sizes[frame]; } ASSERT_LT(frame, frame_count) << "Couldn't find a visible frame. " << "remained_spatial_layers: " << remained_spatial_layers << " super_frame: " << i; if (frame == frame_count - 1) continue; frame_data += frame_sizes[frame]; // We need to add one more frame for multiple frame contexts. uint8_t marker = static_cast<const uint8_t*>(inputs[i].buf)[inputs[i].sz - 1]; const uint32_t mag = ((marker >> 3) & 0x3) + 1; const size_t index_sz = 2 + mag * frame_count; const size_t new_index_sz = 2 + mag * (frame + 1); marker &= 0x0f8; marker |= frame; // Copy existing frame sizes. memmove(frame_data + 1, frame_start + inputs[i].sz - index_sz + 1, new_index_sz - 2); // New marker. frame_data[0] = marker; frame_data += (mag * (frame + 1) + 1); *frame_data++ = marker; inputs[i].sz = frame_data - frame_start; } } } void FreeBitstreamBuffers(struct vpx_fixed_buf *const inputs, const int n) { ASSERT_TRUE(inputs != NULL); ASSERT_GT(n, 0); for (int i = 0; i < n; ++i) { free(inputs[i].buf); inputs[i].buf = NULL; inputs[i].sz = 0; } }
174,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcXFixesCopyRegion(ClientPtr client) { RegionPtr pSource, pDestination; REQUEST(xXFixesCopyRegionReq); VERIFY_REGION(pSource, stuff->source, client, DixReadAccess); VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess); if (!RegionCopy(pDestination, pSource)) return BadAlloc; return Success; } Commit Message: CWE ID: CWE-20
ProcXFixesCopyRegion(ClientPtr client) { RegionPtr pSource, pDestination; REQUEST(xXFixesCopyRegionReq); REQUEST_SIZE_MATCH(xXFixesCopyRegionReq); VERIFY_REGION(pSource, stuff->source, client, DixReadAccess); VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess); if (!RegionCopy(pDestination, pSource)) return BadAlloc; return Success; }
165,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionTtsController::SpeakNextUtterance() { while (!utterance_queue_.empty() && !current_utterance_) { Utterance* utterance = utterance_queue_.front(); utterance_queue_.pop(); SpeakNow(utterance); } } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::SpeakNextUtterance() {
170,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cmsBool CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList, const char* Name, cmsUInt16Number PCS[3], cmsUInt16Number Colorant[cmsMAXCHANNELS]) { cmsUInt32Number i; if (NamedColorList == NULL) return FALSE; if (NamedColorList ->nColors + 1 > NamedColorList ->Allocated) { if (!GrowNamedColorList(NamedColorList)) return FALSE; } for (i=0; i < NamedColorList ->ColorantCount; i++) NamedColorList ->List[NamedColorList ->nColors].DeviceColorant[i] = Colorant == NULL? 0 : Colorant[i]; for (i=0; i < 3; i++) NamedColorList ->List[NamedColorList ->nColors].PCS[i] = PCS == NULL ? 0 : PCS[i]; if (Name != NULL) { strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name, sizeof(NamedColorList ->List[NamedColorList ->nColors].Name)); NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0; } else NamedColorList ->List[NamedColorList ->nColors].Name[0] = 0; NamedColorList ->nColors++; return TRUE; } Commit Message: Non happy-path fixes CWE ID:
cmsBool CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList, const char* Name, cmsUInt16Number PCS[3], cmsUInt16Number Colorant[cmsMAXCHANNELS]) { cmsUInt32Number i; if (NamedColorList == NULL) return FALSE; if (NamedColorList ->nColors + 1 > NamedColorList ->Allocated) { if (!GrowNamedColorList(NamedColorList)) return FALSE; } for (i=0; i < NamedColorList ->ColorantCount; i++) NamedColorList ->List[NamedColorList ->nColors].DeviceColorant[i] = Colorant == NULL? 0 : Colorant[i]; for (i=0; i < 3; i++) NamedColorList ->List[NamedColorList ->nColors].PCS[i] = PCS == NULL ? 0 : PCS[i]; if (Name != NULL) { strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name, cmsMAX_PATH-1); NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0; } else NamedColorList ->List[NamedColorList ->nColors].Name[0] = 0; NamedColorList ->nColors++; return TRUE; }
166,543
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 filter_frame(AVFilterLink *inlink, AVFrame *in) { PadContext *s = inlink->dst->priv; AVFrame *out; int needs_copy = frame_needs_copy(s, in); if (needs_copy) { av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n"); out = ff_get_video_buffer(inlink->dst->outputs[0], FFMAX(inlink->w, s->w), FFMAX(inlink->h, s->h)); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } else { int i; out = in; for (i = 0; i < 4 && out->data[i]; i++) { int hsub = s->draw.hsub[i]; int vsub = s->draw.vsub[i]; out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] + (s->y >> vsub) * out->linesize[i]; } } /* top bar */ if (s->y) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, 0, s->w, s->y); } /* bottom bar */ if (s->h > s->y + s->in_h) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y + s->in_h, s->w, s->h - s->y - s->in_h); } /* left border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y, s->x, in->height); if (needs_copy) { ff_copy_rectangle2(&s->draw, out->data, out->linesize, in->data, in->linesize, s->x, s->y, 0, 0, in->width, in->height); } /* right border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, s->x + s->in_w, s->y, s->w - s->x - s->in_w, in->height); out->width = s->w; out->height = s->h; if (in != out) av_frame_free(&in); return ff_filter_frame(inlink->dst->outputs[0], out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { PadContext *s = inlink->dst->priv; AVFrame *out; int needs_copy = frame_needs_copy(s, in); if (needs_copy) { av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n"); out = ff_get_video_buffer(inlink->dst->outputs[0], FFMAX(inlink->w, s->w), FFMAX(inlink->h, s->h)); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } else { int i; out = in; for (i = 0; i < 4 && out->data[i] && out->linesize[i]; i++) { int hsub = s->draw.hsub[i]; int vsub = s->draw.vsub[i]; out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] + (s->y >> vsub) * out->linesize[i]; } } /* top bar */ if (s->y) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, 0, s->w, s->y); } /* bottom bar */ if (s->h > s->y + s->in_h) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y + s->in_h, s->w, s->h - s->y - s->in_h); } /* left border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y, s->x, in->height); if (needs_copy) { ff_copy_rectangle2(&s->draw, out->data, out->linesize, in->data, in->linesize, s->x, s->y, 0, 0, in->width, in->height); } /* right border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, s->x + s->in_w, s->y, s->w - s->x - s->in_w, in->height); out->width = s->w; out->height = s->h; if (in != out) av_frame_free(&in); return ff_filter_frame(inlink->dst->outputs[0], out); }
166,005
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Maybe<int64_t> IndexOfValueImpl(Isolate* isolate, Handle<JSObject> receiver, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver)); Handle<SeededNumberDictionary> dictionary( SeededNumberDictionary::cast(receiver->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { int entry = dictionary->FindEntry(isolate, k); if (entry == SeededNumberDictionary::kNotFound) { continue; } PropertyDetails details = GetDetailsImpl(*dictionary, entry); switch (details.kind()) { case kData: { Object* element_k = dictionary->ValueAt(entry); if (value->StrictEquals(element_k)) { return Just<int64_t>(k); } break; } case kAccessor: { LookupIterator it(isolate, receiver, k, LookupIterator::OWN_SKIP_INTERCEPTOR); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); Handle<Object> element_k; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element_k, JSObject::GetPropertyWithAccessor(&it), Nothing<int64_t>()); if (value->StrictEquals(*element_k)) return Just<int64_t>(k); if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } if (*dictionary == receiver->elements()) continue; if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } dictionary = handle( SeededNumberDictionary::cast(receiver->elements()), isolate); break; } } } return Just<int64_t>(-1); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704
static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate, Handle<JSObject> receiver, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver)); Handle<Map> original_map(receiver->map(), isolate); Handle<SeededNumberDictionary> dictionary( SeededNumberDictionary::cast(receiver->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { DCHECK_EQ(receiver->map(), *original_map); int entry = dictionary->FindEntry(isolate, k); if (entry == SeededNumberDictionary::kNotFound) { continue; } PropertyDetails details = GetDetailsImpl(*dictionary, entry); switch (details.kind()) { case kData: { Object* element_k = dictionary->ValueAt(entry); if (value->StrictEquals(element_k)) { return Just<int64_t>(k); } break; } case kAccessor: { LookupIterator it(isolate, receiver, k, LookupIterator::OWN_SKIP_INTERCEPTOR); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); Handle<Object> element_k; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element_k, JSObject::GetPropertyWithAccessor(&it), Nothing<int64_t>()); if (value->StrictEquals(*element_k)) return Just<int64_t>(k); if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } if (*dictionary == receiver->elements()) continue; if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } dictionary = handle( SeededNumberDictionary::cast(receiver->elements()), isolate); break; } } } return Just<int64_t>(-1); }
174,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXTableCell::isRowHeaderCell() const { const AtomicString& scope = getAttribute(scopeAttr); return equalIgnoringCase(scope, "row") || equalIgnoringCase(scope, "rowgroup"); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXTableCell::isRowHeaderCell() const { const AtomicString& scope = getAttribute(scopeAttr); return equalIgnoringASCIICase(scope, "row") || equalIgnoringASCIICase(scope, "rowgroup"); }
171,933
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Atom::ShallowCopy(Atom& rhs) const { rhs.m_string_uid = m_string_uid; rhs.m_uid = m_uid; rhs.m_start_timecode = m_start_timecode; rhs.m_stop_timecode = m_stop_timecode; rhs.m_displays = m_displays; rhs.m_displays_size = m_displays_size; rhs.m_displays_count = m_displays_count; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Atom::ShallowCopy(Atom& rhs) const
174,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : AbstractMetadataProvider(e), m_validate(XMLHelper::getAttrBool(e, false, validate)), m_id(XMLHelper::getAttrString(e, "Dynamic", id)), m_lock(RWLock::create()), m_refreshDelayFactor(0.75), m_minCacheDuration(XMLHelper::getAttrInt(e, 600, minCacheDuration)), m_maxCacheDuration(XMLHelper::getAttrInt(e, 28800, maxCacheDuration)), m_shutdown(false), m_cleanupInterval(XMLHelper::getAttrInt(e, 1800, cleanupInterval)), m_cleanupTimeout(XMLHelper::getAttrInt(e, 1800, cleanupTimeout)), m_cleanup_wait(nullptr), m_cleanup_thread(nullptr) { if (m_minCacheDuration > m_maxCacheDuration) { Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error( "minCacheDuration setting exceeds maxCacheDuration setting, lowering to match it" ); m_minCacheDuration = m_maxCacheDuration; } const XMLCh* delay = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : nullptr; if (delay && *delay) { auto_ptr_char temp(delay); m_refreshDelayFactor = atof(temp.get()); if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) { Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error( "invalid refreshDelayFactor setting, using default" ); m_refreshDelayFactor = 0.75; } } if (m_cleanupInterval > 0) { if (m_cleanupTimeout < 0) m_cleanupTimeout = 0; m_cleanup_wait = CondWait::create(); m_cleanup_thread = Thread::create(&cleanup_fn, this); } } Commit Message: CWE ID: CWE-347
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : AbstractMetadataProvider(e), MetadataProvider(e), m_validate(XMLHelper::getAttrBool(e, false, validate)), m_id(XMLHelper::getAttrString(e, "Dynamic", id)), m_lock(RWLock::create()), m_refreshDelayFactor(0.75), m_minCacheDuration(XMLHelper::getAttrInt(e, 600, minCacheDuration)), m_maxCacheDuration(XMLHelper::getAttrInt(e, 28800, maxCacheDuration)), m_shutdown(false), m_cleanupInterval(XMLHelper::getAttrInt(e, 1800, cleanupInterval)), m_cleanupTimeout(XMLHelper::getAttrInt(e, 1800, cleanupTimeout)), m_cleanup_wait(nullptr), m_cleanup_thread(nullptr) { if (m_minCacheDuration > m_maxCacheDuration) { Category::getInstance(SAML_LOGCAT ".Metadata.Dynamic").error( "minCacheDuration setting exceeds maxCacheDuration setting, lowering to match it" ); m_minCacheDuration = m_maxCacheDuration; } const XMLCh* delay = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : nullptr; if (delay && *delay) { auto_ptr_char temp(delay); m_refreshDelayFactor = atof(temp.get()); if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) { Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error( "invalid refreshDelayFactor setting, using default" ); m_refreshDelayFactor = 0.75; } } if (m_cleanupInterval > 0) { if (m_cleanupTimeout < 0) m_cleanupTimeout = 0; m_cleanup_wait = CondWait::create(); m_cleanup_thread = Thread::create(&cleanup_fn, this); } }
164,622
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PlatformFontSkia::InitDefaultFont() { if (g_default_font.Get()) return true; bool success = false; std::string family = kFallbackFontFamilyName; int size_pixels = 12; int style = Font::NORMAL; Font::Weight weight = Font::Weight::NORMAL; FontRenderParams params; const SkiaFontDelegate* delegate = SkiaFontDelegate::instance(); if (delegate) { delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight, &params); } else if (default_font_description_) { #if defined(OS_CHROMEOS) FontRenderParamsQuery query; CHECK(FontList::ParseDescription(*default_font_description_, &query.families, &query.style, &query.pixel_size, &query.weight)) << "Failed to parse font description " << *default_font_description_; params = gfx::GetFontRenderParams(query, &family); size_pixels = query.pixel_size; style = query.style; weight = query.weight; #else NOTREACHED(); #endif } sk_sp<SkTypeface> typeface = CreateSkTypeface(style & Font::ITALIC, weight, &family, &success); if (!success) return false; g_default_font.Get() = new PlatformFontSkia( std::move(typeface), family, size_pixels, style, weight, params); return true; } Commit Message: Take default system font size from PlatformFont The default font returned by Skia should take the initial size from the default value kDefaultBaseFontSize specified in PlatformFont. R=robliao@chromium.org, asvitkine@chromium.org CC=benck@google.com Bug: 944227 Change-Id: I6b230b80c349abbe5968edb3cebdd6e89db4c4a6 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1642738 Reviewed-by: Robert Liao <robliao@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Commit-Queue: Etienne Bergeron <etienneb@chromium.org> Cr-Commit-Position: refs/heads/master@{#666299} CWE ID: CWE-862
bool PlatformFontSkia::InitDefaultFont() { if (g_default_font.Get()) return true; bool success = false; std::string family = kFallbackFontFamilyName; int size_pixels = PlatformFont::kDefaultBaseFontSize; int style = Font::NORMAL; Font::Weight weight = Font::Weight::NORMAL; FontRenderParams params; const SkiaFontDelegate* delegate = SkiaFontDelegate::instance(); if (delegate) { delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight, &params); } else if (default_font_description_) { #if defined(OS_CHROMEOS) FontRenderParamsQuery query; CHECK(FontList::ParseDescription(*default_font_description_, &query.families, &query.style, &query.pixel_size, &query.weight)) << "Failed to parse font description " << *default_font_description_; params = gfx::GetFontRenderParams(query, &family); size_pixels = query.pixel_size; style = query.style; weight = query.weight; #else NOTREACHED(); #endif } sk_sp<SkTypeface> typeface = CreateSkTypeface(style & Font::ITALIC, weight, &family, &success); if (!success) return false; g_default_font.Get() = new PlatformFontSkia( std::move(typeface), family, size_pixels, style, weight, params); return true; }
173,209
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_init_video_state(dec_state_t *ps_dec, e_video_type_t e_video_type) { /*-----------------------------------------------------------------------*/ /* Bit Stream that conforms to MPEG-1 <ISO/IEC 11172-2> standard */ /*-----------------------------------------------------------------------*/ if(e_video_type == MPEG_1_VIDEO) { ps_dec->u2_is_mpeg2 = 0; /*-------------------------------------------------------------------*/ /* force MPEG-1 parameters for proper decoder behavior */ /* see ISO/IEC 13818-2 section D.9.14 */ /*-------------------------------------------------------------------*/ ps_dec->u2_progressive_sequence = 1; ps_dec->u2_intra_dc_precision = 0; ps_dec->u2_picture_structure = FRAME_PICTURE; ps_dec->u2_frame_pred_frame_dct = 1; ps_dec->u2_concealment_motion_vectors = 0; ps_dec->u2_q_scale_type = 0; ps_dec->u2_intra_vlc_format = 0; ps_dec->u2_alternate_scan = 0; ps_dec->u2_repeat_first_field = 0; ps_dec->u2_progressive_frame = 1; ps_dec->u2_frame_rate_extension_n = 0; ps_dec->u2_frame_rate_extension_d = 0; ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg1; /*-------------------------------------------------------------------*/ /* Setting of parameters other than those mentioned in MPEG2 standard*/ /* but used in decoding process. */ /*-------------------------------------------------------------------*/ } /*-----------------------------------------------------------------------*/ /* Bit Stream that conforms to MPEG-2 */ /*-----------------------------------------------------------------------*/ else { ps_dec->u2_is_mpeg2 = 1; ps_dec->u2_full_pel_forw_vector = 0; ps_dec->u2_forw_f_code = 7; ps_dec->u2_full_pel_back_vector = 0; ps_dec->u2_back_f_code = 7; ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg2; } impeg2d_init_function_ptr(ps_dec); /* Set the frame Width and frame Height */ ps_dec->u2_frame_height = ALIGN16(ps_dec->u2_vertical_size); ps_dec->u2_frame_width = ALIGN16(ps_dec->u2_horizontal_size); ps_dec->u2_num_horiz_mb = (ps_dec->u2_horizontal_size + 15) >> 4; if (ps_dec->u2_frame_height > ps_dec->u2_create_max_height || ps_dec->u2_frame_width > ps_dec->u2_create_max_width) { return IMPEG2D_PIC_SIZE_NOT_SUPPORTED; } ps_dec->u2_num_flds_decoded = 0; /* Calculate the frame period */ { UWORD32 numer; UWORD32 denom; numer = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][1] * (UWORD32)(ps_dec->u2_frame_rate_extension_d + 1); denom = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][0] * (UWORD32)(ps_dec->u2_frame_rate_extension_n + 1); ps_dec->u2_framePeriod = (numer * 1000 * 100) / denom; } if(VERTICAL_SCAN == ps_dec->u2_alternate_scan) { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_vertical; } else { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_zig_zag; } return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Adding Error Check for f_code Parameters In MPEG1, the valid range for the forward and backward f_code parameters is [1, 7]. Adding a check to enforce this. Without the check, the value could be 0. We read (f_code - 1) bits from the stream and reading a negative number of bits from the stream is undefined. Bug: 64550583 Test: monitored temp ALOGD() output Change-Id: Ia452cd43a28e9d566401f515947164635361782f (cherry picked from commit 71d734b83d72e8a59f73f1230982da97615d2689) CWE ID: CWE-200
IMPEG2D_ERROR_CODES_T impeg2d_init_video_state(dec_state_t *ps_dec, e_video_type_t e_video_type) { /*-----------------------------------------------------------------------*/ /* Bit Stream that conforms to MPEG-1 <ISO/IEC 11172-2> standard */ /*-----------------------------------------------------------------------*/ if(e_video_type == MPEG_1_VIDEO) { ps_dec->u2_is_mpeg2 = 0; /*-------------------------------------------------------------------*/ /* force MPEG-1 parameters for proper decoder behavior */ /* see ISO/IEC 13818-2 section D.9.14 */ /*-------------------------------------------------------------------*/ ps_dec->u2_progressive_sequence = 1; ps_dec->u2_intra_dc_precision = 0; ps_dec->u2_picture_structure = FRAME_PICTURE; ps_dec->u2_frame_pred_frame_dct = 1; ps_dec->u2_concealment_motion_vectors = 0; ps_dec->u2_q_scale_type = 0; ps_dec->u2_intra_vlc_format = 0; ps_dec->u2_alternate_scan = 0; ps_dec->u2_repeat_first_field = 0; ps_dec->u2_progressive_frame = 1; ps_dec->u2_frame_rate_extension_n = 0; ps_dec->u2_frame_rate_extension_d = 0; ps_dec->u2_forw_f_code = 7; ps_dec->u2_back_f_code = 7; ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg1; /*-------------------------------------------------------------------*/ /* Setting of parameters other than those mentioned in MPEG2 standard*/ /* but used in decoding process. */ /*-------------------------------------------------------------------*/ } /*-----------------------------------------------------------------------*/ /* Bit Stream that conforms to MPEG-2 */ /*-----------------------------------------------------------------------*/ else { ps_dec->u2_is_mpeg2 = 1; ps_dec->u2_full_pel_forw_vector = 0; ps_dec->u2_forw_f_code = 7; ps_dec->u2_full_pel_back_vector = 0; ps_dec->u2_back_f_code = 7; ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg2; } impeg2d_init_function_ptr(ps_dec); /* Set the frame Width and frame Height */ ps_dec->u2_frame_height = ALIGN16(ps_dec->u2_vertical_size); ps_dec->u2_frame_width = ALIGN16(ps_dec->u2_horizontal_size); ps_dec->u2_num_horiz_mb = (ps_dec->u2_horizontal_size + 15) >> 4; if (ps_dec->u2_frame_height > ps_dec->u2_create_max_height || ps_dec->u2_frame_width > ps_dec->u2_create_max_width) { return IMPEG2D_PIC_SIZE_NOT_SUPPORTED; } ps_dec->u2_num_flds_decoded = 0; /* Calculate the frame period */ { UWORD32 numer; UWORD32 denom; numer = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][1] * (UWORD32)(ps_dec->u2_frame_rate_extension_d + 1); denom = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][0] * (UWORD32)(ps_dec->u2_frame_rate_extension_n + 1); ps_dec->u2_framePeriod = (numer * 1000 * 100) / denom; } if(VERTICAL_SCAN == ps_dec->u2_alternate_scan) { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_vertical; } else { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_zig_zag; } return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }
174,104
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebRequestPermissions::CanExtensionAccessURL( const extensions::InfoMap* extension_info_map, const std::string& extension_id, const GURL& url, bool crosses_incognito, HostPermissionsCheck host_permissions_check) { if (!extension_info_map) return true; const extensions::Extension* extension = extension_info_map->extensions().GetByID(extension_id); if (!extension) return false; if (crosses_incognito && !extension_info_map->CanCrossIncognito(extension)) return false; switch (host_permissions_check) { case DO_NOT_CHECK_HOST: break; case REQUIRE_HOST_PERMISSION: if (!((url.SchemeIs(url::kAboutScheme) || extension->permissions_data()->HasHostPermission(url) || url.GetOrigin() == extension->url()))) { return false; } break; case REQUIRE_ALL_URLS: if (!extension->permissions_data()->HasEffectiveAccessToAllHosts()) return false; break; } return true; } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} CWE ID: CWE-284
bool WebRequestPermissions::CanExtensionAccessURL( const extensions::InfoMap* extension_info_map, const std::string& extension_id, const GURL& url, bool crosses_incognito, HostPermissionsCheck host_permissions_check) { if (!extension_info_map) return true; const extensions::Extension* extension = extension_info_map->extensions().GetByID(extension_id); if (!extension) return false; if (crosses_incognito && !extension_info_map->CanCrossIncognito(extension)) return false; switch (host_permissions_check) { case DO_NOT_CHECK_HOST: break; case REQUIRE_HOST_PERMISSION: if (!url.SchemeIs(url::kAboutScheme) && !extension->permissions_data()->HasHostPermission(url) && !url::IsSameOriginWith(url, extension->url())) { return false; } break; case REQUIRE_ALL_URLS: if (!extension->permissions_data()->HasEffectiveAccessToAllHosts()) return false; break; } return true; }
172,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName) { char nameBuf[512]; char absoluteFile[sizeof(nameBuf)]; const size_t kBufLen = sizeof(nameBuf) - 1; const char* dataRoot; char* cp; /* * Get the absolute path of the Jar or DEX file. */ absoluteFile[0] = '\0'; if (fileName[0] != '/') { /* * Generate the absolute path. This doesn't do everything it * should, e.g. if filename is "./out/whatever" it doesn't crunch * the leading "./" out, but it'll do. */ if (getcwd(absoluteFile, kBufLen) == NULL) { ALOGE("Can't get CWD while opening jar file"); return NULL; } strncat(absoluteFile, "/", kBufLen); } strncat(absoluteFile, fileName, kBufLen); /* * Append the name of the Jar file entry, if any. This is not currently * required, but will be if we start putting more than one DEX file * in a Jar. */ if (subFileName != NULL) { strncat(absoluteFile, "/", kBufLen); strncat(absoluteFile, subFileName, kBufLen); } /* Turn the path into a flat filename by replacing * any slashes after the first one with '@' characters. */ cp = absoluteFile + 1; while (*cp != '\0') { if (*cp == '/') { *cp = '@'; } cp++; } /* Build the name of the cache directory. */ dataRoot = getenv("ANDROID_DATA"); if (dataRoot == NULL) dataRoot = "/data"; snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName); if (strcmp(dataRoot, "/data") != 0) { int result = dexOptMkdir(nameBuf, 0700); if (result != 0 && errno != EEXIST) { ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno)); return NULL; } } snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet); if (strcmp(dataRoot, "/data") != 0) { int result = dexOptMkdir(nameBuf, 0700); if (result != 0 && errno != EEXIST) { ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno)); return NULL; } } /* Tack on the file name for the actual cache file path. */ strncat(nameBuf, absoluteFile, kBufLen); ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf); return strdup(nameBuf); } Commit Message: Fix potential buffer overrun. BUG=27840771 Change-Id: I240f188b2e8f4b45d90138cfb3b14869cf506452 CWE ID: CWE-119
char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName) { char nameBuf[512]; char absoluteFile[sizeof(nameBuf)]; const size_t kBufLen = sizeof(nameBuf) - 1; const char* dataRoot; char* cp; /* * Get the absolute path of the Jar or DEX file. */ absoluteFile[0] = '\0'; if (fileName[0] != '/') { /* * Generate the absolute path. This doesn't do everything it * should, e.g. if filename is "./out/whatever" it doesn't crunch * the leading "./" out, but it'll do. */ if (getcwd(absoluteFile, kBufLen) == NULL) { ALOGE("Can't get CWD while opening jar file"); return NULL; } strncat(absoluteFile, "/", kBufLen - strlen(absoluteFile)); } strncat(absoluteFile, fileName, kBufLen - strlen(absoluteFile)); /* * Append the name of the Jar file entry, if any. This is not currently * required, but will be if we start putting more than one DEX file * in a Jar. */ if (subFileName != NULL) { strncat(absoluteFile, "/", kBufLen - strlen(absoluteFile)); strncat(absoluteFile, subFileName, kBufLen - strlen(absoluteFile)); } /* Turn the path into a flat filename by replacing * any slashes after the first one with '@' characters. */ cp = absoluteFile + 1; while (*cp != '\0') { if (*cp == '/') { *cp = '@'; } cp++; } /* Build the name of the cache directory. */ dataRoot = getenv("ANDROID_DATA"); if (dataRoot == NULL) dataRoot = "/data"; snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName); if (strcmp(dataRoot, "/data") != 0) { int result = dexOptMkdir(nameBuf, 0700); if (result != 0 && errno != EEXIST) { ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno)); return NULL; } } snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet); if (strcmp(dataRoot, "/data") != 0) { int result = dexOptMkdir(nameBuf, 0700); if (result != 0 && errno != EEXIST) { ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno)); return NULL; } } /* Tack on the file name for the actual cache file path. */ strncat(nameBuf, absoluteFile, kBufLen - strlen(nameBuf)); ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf); return strdup(nameBuf); }
173,559
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->pos + count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; } Commit Message: CWE ID: CWE-20
FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->size - stream->pos < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; }
164,986
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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) { ::testing::InitGoogleTest(&argc, argv); #if ARCH_X86 || ARCH_X86_64 const int simd_caps = x86_simd_caps(); if (!(simd_caps & HAS_MMX)) append_negative_gtest_filter(":MMX/*"); if (!(simd_caps & HAS_SSE)) append_negative_gtest_filter(":SSE/*"); if (!(simd_caps & HAS_SSE2)) append_negative_gtest_filter(":SSE2/*"); if (!(simd_caps & HAS_SSE3)) append_negative_gtest_filter(":SSE3/*"); if (!(simd_caps & HAS_SSSE3)) append_negative_gtest_filter(":SSSE3/*"); if (!(simd_caps & HAS_SSE4_1)) append_negative_gtest_filter(":SSE4_1/*"); if (!(simd_caps & HAS_AVX)) append_negative_gtest_filter(":AVX/*"); if (!(simd_caps & HAS_AVX2)) append_negative_gtest_filter(":AVX2/*"); #endif #if !CONFIG_SHARED #if CONFIG_VP8 vp8_rtcd(); #endif #if CONFIG_VP9 vp9_rtcd(); #endif #endif return RUN_ALL_TESTS(); } 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) { ::testing::InitGoogleTest(&argc, argv); #if ARCH_X86 || ARCH_X86_64 const int simd_caps = x86_simd_caps(); if (!(simd_caps & HAS_MMX)) append_negative_gtest_filter(":MMX.*:MMX/*"); if (!(simd_caps & HAS_SSE)) append_negative_gtest_filter(":SSE.*:SSE/*"); if (!(simd_caps & HAS_SSE2)) append_negative_gtest_filter(":SSE2.*:SSE2/*"); if (!(simd_caps & HAS_SSE3)) append_negative_gtest_filter(":SSE3.*:SSE3/*"); if (!(simd_caps & HAS_SSSE3)) append_negative_gtest_filter(":SSSE3.*:SSSE3/*"); if (!(simd_caps & HAS_SSE4_1)) append_negative_gtest_filter(":SSE4_1.*:SSE4_1/*"); if (!(simd_caps & HAS_AVX)) append_negative_gtest_filter(":AVX.*:AVX/*"); if (!(simd_caps & HAS_AVX2)) append_negative_gtest_filter(":AVX2.*:AVX2/*"); #endif #if !CONFIG_SHARED #if CONFIG_VP8 vp8_rtcd(); #endif // CONFIG_VP8 #if CONFIG_VP9 vp9_rtcd(); #endif // CONFIG_VP9 vpx_dsp_rtcd(); vpx_scale_rtcd(); #endif // !CONFIG_SHARED return RUN_ALL_TESTS(); }
174,583
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header, struct mb_cache_entry **pce) { __u32 hash = le32_to_cpu(header->h_hash); struct mb_cache_entry *ce; struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode); if (!header->h_hash) return NULL; /* never share */ ea_idebug(inode, "looking for cached blocks [%x]", (int)hash); again: ce = mb_cache_entry_find_first(ext4_mb_cache, inode->i_sb->s_bdev, hash); while (ce) { struct buffer_head *bh; if (IS_ERR(ce)) { if (PTR_ERR(ce) == -EAGAIN) goto again; break; } bh = sb_bread(inode->i_sb, ce->e_block); if (!bh) { EXT4_ERROR_INODE(inode, "block %lu read error", (unsigned long) ce->e_block); } else if (le32_to_cpu(BHDR(bh)->h_refcount) >= EXT4_XATTR_REFCOUNT_MAX) { ea_idebug(inode, "block %lu refcount %d>=%d", (unsigned long) ce->e_block, le32_to_cpu(BHDR(bh)->h_refcount), EXT4_XATTR_REFCOUNT_MAX); } else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) { *pce = ce; return bh; } brelse(bh); ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash); } return NULL; } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header, struct mb2_cache_entry **pce) { __u32 hash = le32_to_cpu(header->h_hash); struct mb2_cache_entry *ce; struct mb2_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode); if (!header->h_hash) return NULL; /* never share */ ea_idebug(inode, "looking for cached blocks [%x]", (int)hash); ce = mb2_cache_entry_find_first(ext4_mb_cache, hash); while (ce) { struct buffer_head *bh; bh = sb_bread(inode->i_sb, ce->e_block); if (!bh) { EXT4_ERROR_INODE(inode, "block %lu read error", (unsigned long) ce->e_block); } else if (le32_to_cpu(BHDR(bh)->h_refcount) >= EXT4_XATTR_REFCOUNT_MAX) { ea_idebug(inode, "block %lu refcount %d>=%d", (unsigned long) ce->e_block, le32_to_cpu(BHDR(bh)->h_refcount), EXT4_XATTR_REFCOUNT_MAX); } else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) { *pce = ce; return bh; } brelse(bh); ce = mb2_cache_entry_find_next(ext4_mb_cache, ce); } return NULL; }
169,991
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: validate_T(void) /* Validate the above table - this just builds the above values */ { unsigned int i; for (i=0; i<TTABLE_SIZE; ++i) { if (transform_info[i].when & TRANSFORM_R) read_transforms |= transform_info[i].transform; if (transform_info[i].when & TRANSFORM_W) write_transforms |= transform_info[i].transform; } /* Reversible transforms are those which are supported on both read and * write. */ rw_transforms = read_transforms & write_transforms; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
validate_T(void) /* Validate the above table - this just builds the above values */ { unsigned int i; for (i=0; i<TTABLE_SIZE; ++i) if (transform_info[i].name != NULL) { if (transform_info[i].when & TRANSFORM_R) read_transforms |= transform_info[i].transform; if (transform_info[i].when & TRANSFORM_W) write_transforms |= transform_info[i].transform; } /* Reversible transforms are those which are supported on both read and * write. */ rw_transforms = read_transforms & write_transforms; }
173,592
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionTtsController::CheckSpeechStatus() { if (!current_utterance_) return; if (!current_utterance_->extension_id().empty()) return; if (GetPlatformImpl()->IsSpeaking() == false) { FinishCurrentUtterance(); SpeakNextUtterance(); } if (current_utterance_ && current_utterance_->extension_id().empty()) { MessageLoop::current()->PostDelayedTask( FROM_HERE, method_factory_.NewRunnableMethod( &ExtensionTtsController::CheckSpeechStatus), kSpeechCheckDelayIntervalMs); } } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::CheckSpeechStatus() { std::set<std::string> desired_event_types; if (options->HasKey(constants::kDesiredEventTypesKey)) { ListValue* list; EXTENSION_FUNCTION_VALIDATE( options->GetList(constants::kDesiredEventTypesKey, &list)); for (size_t i = 0; i < list->GetSize(); i++) { std::string event_type; if (!list->GetString(i, &event_type)) desired_event_types.insert(event_type); } } std::string voice_extension_id; if (options->HasKey(constants::kExtensionIdKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetString(constants::kExtensionIdKey, &voice_extension_id)); }
170,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov, unsigned int max_num_sg, bool is_write, hwaddr pa, size_t sz) { unsigned num_sg = *p_num_sg; assert(num_sg <= max_num_sg); while (sz) { hwaddr len = sz; iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write); iov[num_sg].iov_len = len; addr[num_sg] = pa; sz -= len; pa += len; num_sg++; } *p_num_sg = num_sg; } Commit Message: CWE ID: CWE-20
static void virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov, unsigned int max_num_sg, bool is_write, hwaddr pa, size_t sz) { unsigned num_sg = *p_num_sg; assert(num_sg <= max_num_sg); if (!sz) { error_report("virtio: zero sized buffers are not allowed"); exit(1); } while (sz) { hwaddr len = sz; iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write); iov[num_sg].iov_len = len; addr[num_sg] = pa; sz -= len; pa += len; num_sg++; } *p_num_sg = num_sg; }
164,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *DetachBlob(BlobInfo *blob_info) { void *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; blob_info->custom_stream=(CustomStreamInfo *) NULL; return(data); } Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43 CWE ID: CWE-416
MagickExport void *DetachBlob(BlobInfo *blob_info) { void *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); blob_info->data=NULL; RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; blob_info->custom_stream=(CustomStreamInfo *) NULL; return(data); }
170,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: QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag) { QString ret; QString tag; int i = data->openHtmlTags.count() - 1; for ( ; i >= 0 ; --i) { tag = data->openHtmlTags.at(i); ret += QLatin1String("</") + tag + QLatin1Char('>'); if (tag == _tag) { data->openHtmlTags.removeAt(i); break; } } ret += openTags(data, i); return ret; } Commit Message: CWE ID:
QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag) { QString ret; QString tag; int i = data->openHtmlTags.count() - 1; for ( ; i >= 0 ; --i) { tag = data->openHtmlTags.at(i); ret += QLatin1String("</") + tag + QLatin1Char('>'); if (tag == _tag) { data->openHtmlTags.removeAt(i); break; } } if (i > -1) ret += openTags(data, i); return ret; }
164,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 5000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = rnd.Rand8() - rnd.Rand8(); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[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 RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 5000; DECLARE_ALIGNED(16, int16_t, input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = (rnd.Rand16() & mask_) - (rnd.Rand16() & mask_); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } }
174,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "sr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "pr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); }
165,067
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk, int window_bits, png_uint_32 offset) /* Initialize a zlib_control; the result is true/false */ { CLEAR(*zlib); zlib->idat = idat; zlib->chunk = chunk; zlib->file = chunk->file; zlib->global = chunk->global; zlib->rewrite_offset = offset; /* never changed for this zlib */ /* *_out does not need to be set: */ zlib->z.next_in = Z_NULL; zlib->z.avail_in = 0; zlib->z.zalloc = Z_NULL; zlib->z.zfree = Z_NULL; zlib->z.opaque = Z_NULL; zlib->state = -1; zlib->window_bits = window_bits; zlib->compressed_digits = 0; zlib->uncompressed_digits = 0; /* These values are sticky across reset (in addition to the stuff in the * first block, which is actually constant.) */ zlib->file_bits = 16; zlib->ok_bits = 16; /* unset */ zlib->cksum = 0; /* set when a checksum error is detected */ /* '0' means use the header; inflateInit2 should always succeed because it * does nothing apart from allocating the internal zstate. */ zlib->rc = inflateInit2(&zlib->z, 0); if (zlib->rc != Z_OK) { zlib_message(zlib, 1/*unexpected*/); return 0; } else { zlib->state = 0; /* initialized */ 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:
zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk, int window_bits, png_uint_32 offset) /* Initialize a zlib_control; the result is true/false */ { CLEAR(*zlib); zlib->idat = idat; zlib->chunk = chunk; zlib->file = chunk->file; zlib->global = chunk->global; zlib->rewrite_offset = offset; /* never changed for this zlib */ /* *_out does not need to be set: */ zlib->z.next_in = Z_NULL; zlib->z.avail_in = 0; zlib->z.zalloc = Z_NULL; zlib->z.zfree = Z_NULL; zlib->z.opaque = Z_NULL; zlib->state = -1; zlib->window_bits = window_bits; zlib->compressed_digits = 0; zlib->uncompressed_digits = 0; /* These values are sticky across reset (in addition to the stuff in the * first block, which is actually constant.) */ zlib->file_bits = 24; zlib->ok_bits = 16; /* unset */ zlib->cksum = 0; /* set when a checksum error is detected */ /* '0' means use the header; inflateInit2 should always succeed because it * does nothing apart from allocating the internal zstate. */ zlib->rc = inflateInit2(&zlib->z, 0); if (zlib->rc != Z_OK) { zlib_message(zlib, 1/*unexpected*/); return 0; } else { zlib->state = 0; /* initialized */ return 1; } }
173,742
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DownloadUIAdapterDelegate::OpenItem(const OfflineItem& item, int64_t offline_id) { JNIEnv* env = AttachCurrentThread(); Java_OfflinePageDownloadBridge_openItem( env, ConvertUTF8ToJavaString(env, item.page_url.spec()), offline_id); } Commit Message: Open Offline Pages in CCT from Downloads Home. When the respective feature flag is enabled, offline pages opened from the Downloads Home will use CCT instead of normal tabs. Bug: 824807 Change-Id: I6d968b8b0c51aaeb7f26332c7ada9f927e151a65 Reviewed-on: https://chromium-review.googlesource.com/977321 Commit-Queue: Carlos Knippschild <carlosk@chromium.org> Reviewed-by: Ted Choc <tedchoc@chromium.org> Reviewed-by: Bernhard Bauer <bauerb@chromium.org> Reviewed-by: Jian Li <jianli@chromium.org> Cr-Commit-Position: refs/heads/master@{#546545} CWE ID: CWE-264
void DownloadUIAdapterDelegate::OpenItem(const OfflineItem& item, int64_t offline_id) { JNIEnv* env = AttachCurrentThread(); Java_OfflinePageDownloadBridge_openItem( env, ConvertUTF8ToJavaString(env, item.page_url.spec()), offline_id, offline_pages::ShouldOfflinePagesInDownloadHomeOpenInCct()); }
171,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sysMapBlockFile(FILE* mapf, MemMapping* pMap) { char block_dev[PATH_MAX+1]; size_t size; unsigned int blksize; unsigned int blocks; unsigned int range_count; unsigned int i; if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) { LOGW("failed to read block device from header\n"); return -1; } for (i = 0; i < sizeof(block_dev); ++i) { if (block_dev[i] == '\n') { block_dev[i] = 0; break; } } if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) { LOGW("failed to parse block map header\n"); return -1; } blocks = ((size-1) / blksize) + 1; pMap->range_count = range_count; pMap->ranges = malloc(range_count * sizeof(MappedRange)); memset(pMap->ranges, 0, range_count * sizeof(MappedRange)); unsigned char* reserve; reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); if (reserve == MAP_FAILED) { LOGW("failed to reserve address space: %s\n", strerror(errno)); return -1; } pMap->ranges[range_count-1].addr = reserve; pMap->ranges[range_count-1].length = blocks * blksize; int fd = open(block_dev, O_RDONLY); if (fd < 0) { LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno)); return -1; } unsigned char* next = reserve; for (i = 0; i < range_count; ++i) { int start, end; if (fscanf(mapf, "%d %d\n", &start, &end) != 2) { LOGW("failed to parse range %d in block map\n", i); return -1; } void* addr = mmap64(next, (end-start)*blksize, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize); if (addr == MAP_FAILED) { LOGW("failed to map block %d: %s\n", i, strerror(errno)); return -1; } pMap->ranges[i].addr = addr; pMap->ranges[i].length = (end-start)*blksize; next += pMap->ranges[i].length; } pMap->addr = reserve; pMap->length = size; LOGI("mmapped %d ranges\n", range_count); return 0; } Commit Message: Fix integer overflows in recovery procedure. Bug: 26960931 Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf (cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b) CWE ID: CWE-189
static int sysMapBlockFile(FILE* mapf, MemMapping* pMap) { char block_dev[PATH_MAX+1]; size_t size; unsigned int blksize; size_t blocks; unsigned int range_count; unsigned int i; if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) { LOGW("failed to read block device from header\n"); return -1; } for (i = 0; i < sizeof(block_dev); ++i) { if (block_dev[i] == '\n') { block_dev[i] = 0; break; } } if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) { LOGW("failed to parse block map header\n"); return -1; } if (blksize != 0) { blocks = ((size-1) / blksize) + 1; } if (size == 0 || blksize == 0 || blocks > SIZE_MAX / blksize || range_count == 0) { LOGE("invalid data in block map file: size %zu, blksize %u, range_count %u\n", size, blksize, range_count); return -1; } pMap->range_count = range_count; pMap->ranges = calloc(range_count, sizeof(MappedRange)); if (pMap->ranges == NULL) { LOGE("calloc(%u, %zu) failed: %s\n", range_count, sizeof(MappedRange), strerror(errno)); return -1; } unsigned char* reserve; reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); if (reserve == MAP_FAILED) { LOGW("failed to reserve address space: %s\n", strerror(errno)); free(pMap->ranges); return -1; } int fd = open(block_dev, O_RDONLY); if (fd < 0) { LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno)); munmap(reserve, blocks * blksize); free(pMap->ranges); return -1; } unsigned char* next = reserve; size_t remaining_size = blocks * blksize; bool success = true; for (i = 0; i < range_count; ++i) { size_t start, end; if (fscanf(mapf, "%zu %zu\n", &start, &end) != 2) { LOGW("failed to parse range %d in block map\n", i); success = false; break; } size_t length = (end - start) * blksize; if (end <= start || (end - start) > SIZE_MAX / blksize || length > remaining_size) { LOGE("unexpected range in block map: %zu %zu\n", start, end); success = false; break; } void* addr = mmap64(next, length, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize); if (addr == MAP_FAILED) { LOGW("failed to map block %d: %s\n", i, strerror(errno)); success = false; break; } pMap->ranges[i].addr = addr; pMap->ranges[i].length = length; next += length; remaining_size -= length; } if (success && remaining_size != 0) { LOGE("ranges in block map are invalid: remaining_size = %zu\n", remaining_size); success = false; } if (!success) { close(fd); munmap(reserve, blocks * blksize); free(pMap->ranges); return -1; } close(fd); pMap->addr = reserve; pMap->length = size; LOGI("mmapped %d ranges\n", range_count); return 0; }
173,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf("found! %d\n", (int)(t - p->t));*/ syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, "updateDevice() : memory allocation error"); free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, "new device discovered : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, "updateDevice(): cannot allocate memory"); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; } Commit Message: updateDevice() remove element from the list when realloc fails CWE ID: CWE-416
updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf("found! %d\n", (int)(t - p->t));*/ syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, "updateDevice() : memory allocation error"); *pp = p->next; /* remove "p" from the list */ free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, "new device discovered : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, "updateDevice(): cannot allocate memory"); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; }
169,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SchedulerObject::setAttribute(std::string key, std::string name, std::string value, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (isSubmissionChange(name.c_str())) { text = "Changes to submission name not allowed"; return false; } if (isKeyword(name.c_str())) { text = "Attribute name is reserved: " + name; return false; } if (!isValidAttributeName(name,text)) { return false; } if (::SetAttribute(id.cluster, id.proc, name.c_str(), value.c_str())) { text = "Failed to set attribute " + name + " to " + value; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::setAttribute(std::string key, std::string name, std::string value, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (isSubmissionChange(name.c_str())) { text = "Changes to submission name not allowed"; return false; } if (isKeyword(name.c_str())) { text = "Attribute name is reserved: " + name; return false; } if (!isValidAttributeName(name,text)) { return false; } if (::SetAttribute(id.cluster, id.proc, name.c_str(), value.c_str())) { text = "Failed to set attribute " + name + " to " + value; return false; } return true; }
164,835
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 find_source_vc(char **ret_path, unsigned *ret_idx) { _cleanup_free_ char *path = NULL; int r, err = 0; unsigned i; path = new(char, sizeof("/dev/tty63")); if (!path) return log_oom(); for (i = 1; i <= 63; i++) { _cleanup_close_ int fd = -1; r = verify_vc_allocation(i); if (r < 0) { if (!err) err = -r; continue; } sprintf(path, "/dev/tty%u", i); fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (!err) err = -fd; continue; } r = verify_vc_kbmode(fd); if (r < 0) { if (!err) err = -r; continue; } /* all checks passed, return this one as a source console */ *ret_idx = i; *ret_path = TAKE_PTR(path); return TAKE_FD(fd); } return log_error_errno(err, "No usable source console found: %m"); } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int find_source_vc(char **ret_path, unsigned *ret_idx) { _cleanup_free_ char *path = NULL; int r, err = 0; unsigned i; path = new(char, sizeof("/dev/tty63")); if (!path) return log_oom(); for (i = 1; i <= 63; i++) { _cleanup_close_ int fd = -1; r = verify_vc_allocation(i); if (r < 0) { if (!err) err = -r; continue; } sprintf(path, "/dev/tty%u", i); fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (!err) err = -fd; continue; } r = vt_verify_kbmode(fd); if (r < 0) { if (!err) err = -r; continue; } /* all checks passed, return this one as a source console */ *ret_idx = i; *ret_path = TAKE_PTR(path); return TAKE_FD(fd); } return log_error_errno(err, "No usable source console found: %m"); }
169,777
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Initialize(bool can_respond_to_crypto_handshake = true) { clock_.AdvanceTime(quic::QuicTime::Delta::FromMilliseconds(1000)); runner_ = new net::test::TestTaskRunner(&clock_); net::QuicChromiumAlarmFactory* alarm_factory = new net::QuicChromiumAlarmFactory(runner_.get(), &clock_); quic_transport_factory_ = std::make_unique<P2PQuicTransportFactoryImpl>( &clock_, std::unique_ptr<net::QuicChromiumAlarmFactory>(alarm_factory)); auto client_packet_transport = std::make_unique<FakePacketTransport>(alarm_factory, &clock_); auto server_packet_transport = std::make_unique<FakePacketTransport>(alarm_factory, &clock_); client_packet_transport->ConnectPeerTransport( server_packet_transport.get()); server_packet_transport->ConnectPeerTransport( client_packet_transport.get()); rtc::scoped_refptr<rtc::RTCCertificate> client_cert = CreateTestCertificate(); auto client_quic_transport_delegate = std::make_unique<MockP2PQuicTransportDelegate>(); std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> client_certificates; client_certificates.push_back(client_cert); P2PQuicTransportConfig client_config(client_quic_transport_delegate.get(), client_packet_transport.get(), client_certificates); client_config.is_server = false; client_config.can_respond_to_crypto_handshake = can_respond_to_crypto_handshake; P2PQuicTransportImpl* client_quic_transport_ptr = static_cast<P2PQuicTransportImpl*>( quic_transport_factory_ ->CreateQuicTransport(std::move(client_config)) .release()); std::unique_ptr<P2PQuicTransportImpl> client_quic_transport = std::unique_ptr<P2PQuicTransportImpl>(client_quic_transport_ptr); client_peer_ = std::make_unique<QuicPeerForTest>( std::move(client_packet_transport), std::move(client_quic_transport_delegate), std::move(client_quic_transport), client_cert); auto server_quic_transport_delegate = std::make_unique<MockP2PQuicTransportDelegate>(); rtc::scoped_refptr<rtc::RTCCertificate> server_cert = CreateTestCertificate(); std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> server_certificates; server_certificates.push_back(server_cert); P2PQuicTransportConfig server_config(server_quic_transport_delegate.get(), server_packet_transport.get(), server_certificates); server_config.is_server = true; server_config.can_respond_to_crypto_handshake = can_respond_to_crypto_handshake; P2PQuicTransportImpl* server_quic_transport_ptr = static_cast<P2PQuicTransportImpl*>( quic_transport_factory_ ->CreateQuicTransport(std::move(server_config)) .release()); std::unique_ptr<P2PQuicTransportImpl> server_quic_transport = std::unique_ptr<P2PQuicTransportImpl>(server_quic_transport_ptr); server_peer_ = std::make_unique<QuicPeerForTest>( std::move(server_packet_transport), std::move(server_quic_transport_delegate), std::move(server_quic_transport), server_cert); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <shampson@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void Initialize(bool can_respond_to_crypto_handshake = true) { clock_.AdvanceTime(quic::QuicTime::Delta::FromMilliseconds(1000)); runner_ = new net::test::TestTaskRunner(&clock_); net::QuicChromiumAlarmFactory* alarm_factory = new net::QuicChromiumAlarmFactory(runner_.get(), &clock_); quic_transport_factory_ = std::make_unique<P2PQuicTransportFactoryImpl>( &clock_, std::unique_ptr<net::QuicChromiumAlarmFactory>(alarm_factory)); auto client_packet_transport = std::make_unique<FakePacketTransport>(alarm_factory, &clock_); auto server_packet_transport = std::make_unique<FakePacketTransport>(alarm_factory, &clock_); client_packet_transport->ConnectPeerTransport( server_packet_transport.get()); server_packet_transport->ConnectPeerTransport( client_packet_transport.get()); rtc::scoped_refptr<rtc::RTCCertificate> client_cert = CreateTestCertificate(); auto client_quic_transport_delegate = std::make_unique<MockP2PQuicTransportDelegate>(); std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> client_certificates; client_certificates.push_back(client_cert); P2PQuicTransportConfig client_config(client_quic_transport_delegate.get(), client_packet_transport.get(), client_certificates, kWriteBufferSize); client_config.is_server = false; client_config.can_respond_to_crypto_handshake = can_respond_to_crypto_handshake; P2PQuicTransportImpl* client_quic_transport_ptr = static_cast<P2PQuicTransportImpl*>( quic_transport_factory_ ->CreateQuicTransport(std::move(client_config)) .release()); std::unique_ptr<P2PQuicTransportImpl> client_quic_transport = std::unique_ptr<P2PQuicTransportImpl>(client_quic_transport_ptr); client_peer_ = std::make_unique<QuicPeerForTest>( std::move(client_packet_transport), std::move(client_quic_transport_delegate), std::move(client_quic_transport), client_cert); auto server_quic_transport_delegate = std::make_unique<MockP2PQuicTransportDelegate>(); rtc::scoped_refptr<rtc::RTCCertificate> server_cert = CreateTestCertificate(); std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> server_certificates; server_certificates.push_back(server_cert); P2PQuicTransportConfig server_config(server_quic_transport_delegate.get(), server_packet_transport.get(), server_certificates, kWriteBufferSize); server_config.is_server = true; server_config.can_respond_to_crypto_handshake = can_respond_to_crypto_handshake; P2PQuicTransportImpl* server_quic_transport_ptr = static_cast<P2PQuicTransportImpl*>( quic_transport_factory_ ->CreateQuicTransport(std::move(server_config)) .release()); std::unique_ptr<P2PQuicTransportImpl> server_quic_transport = std::unique_ptr<P2PQuicTransportImpl>(server_quic_transport_ptr); server_peer_ = std::make_unique<QuicPeerForTest>( std::move(server_packet_transport), std::move(server_quic_transport_delegate), std::move(server_quic_transport), server_cert); }
172,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s) { asn1_write(data, s->data, s->length); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s) { return asn1_write(data, s->data, s->length); }
164,588
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProxyChannelDelegate::~ProxyChannelDelegate() { } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ProxyChannelDelegate::~ProxyChannelDelegate() {
170,740
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CaptivePortalDetector::DetectCaptivePortal( const GURL& url, const DetectionCallback& detection_callback) { DCHECK(CalledOnValidThread()); DCHECK(!FetchingURL()); DCHECK(detection_callback_.is_null()); detection_callback_ = detection_callback; url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); url_fetcher_->SetAutomaticallyRetryOn5xx(false); url_fetcher_->SetRequestContext(request_context_.get()); url_fetcher_->SetLoadFlags( net::LOAD_BYPASS_CACHE | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA); url_fetcher_->Start(); } Commit Message: Add data usage tracking for chrome services Add data usage tracking for captive portal, web resource and signin services BUG=655749 Review-Url: https://codereview.chromium.org/2643013004 Cr-Commit-Position: refs/heads/master@{#445810} CWE ID: CWE-190
void CaptivePortalDetector::DetectCaptivePortal( const GURL& url, const DetectionCallback& detection_callback) { DCHECK(CalledOnValidThread()); DCHECK(!FetchingURL()); DCHECK(detection_callback_.is_null()); detection_callback_ = detection_callback; url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); url_fetcher_->SetAutomaticallyRetryOn5xx(false); url_fetcher_->SetRequestContext(request_context_.get()); data_use_measurement::DataUseUserData::AttachToFetcher( url_fetcher_.get(), data_use_measurement::DataUseUserData::CAPTIVE_PORTAL); url_fetcher_->SetLoadFlags( net::LOAD_BYPASS_CACHE | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA); url_fetcher_->Start(); }
172,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LocalFrame::ShouldReuseDefaultView(const KURL& url) const { if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument()) return false; return GetDocument()->IsSecureTransitionTo(url); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const { bool LocalFrame::ShouldReuseDefaultView( const KURL& url, const ContentSecurityPolicy* csp) const { if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument()) return false; // The Window object should only be re-used if it is same-origin. // Since sandboxing turns the origin into an opaque origin it needs to also // be considered when deciding whether to reuse it. // Spec: // https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object if (csp && SecurityContext::IsSandboxed(kSandboxOrigin, csp->GetSandboxMask())) { return false; } return GetDocument()->IsSecureTransitionTo(url); }
173,196
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = calloc(1, sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = malloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = malloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = safe_calloc(sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = safe_calloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = safe_calloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; }
169,573
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int dlen) { return crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen); } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-476
static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,
167,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); } if(rctx->topdown) { iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); } rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; } Commit Message: Fixed a bug that could cause invalid memory to be accessed The bug could happen when transparency is removed from an image. Also fixed a semi-related BMP error handling logic bug. Fixes issue #21 CWE ID: CWE-787
static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); goto done; } if(rctx->topdown) { iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); goto done; } rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; }
168,117
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const { PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength)); tTcpIpPacketParsingResult packetReview; packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum, __FUNCTION__); if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) { auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset; auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader); auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0; VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen); VHeader->gso_size = (USHORT)m_ParentNBL->MSS(); VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen); VHeader->csum_offset = TCP_CHECKSUM_OFFSET; } } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <yhindin@rehat.com> CWE ID: CWE-20
void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const { PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength)); tTcpIpPacketParsingResult packetReview; packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum, FALSE, __FUNCTION__); if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) { auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset; auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader); auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0; VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen); VHeader->gso_size = (USHORT)m_ParentNBL->MSS(); VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen); VHeader->csum_offset = TCP_CHECKSUM_OFFSET; } }
170,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 future_t *init(void) { pthread_mutex_init(&lock, NULL); config = config_new(CONFIG_FILE_PATH); if (!config) { LOG_WARN(LOG_TAG, "%s unable to load config file; attempting to transcode legacy file.", __func__); config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH); if (!config) { LOG_WARN(LOG_TAG, "%s unable to transcode legacy file, starting unconfigured.", __func__); config = config_new_empty(); if (!config) { LOG_ERROR(LOG_TAG, "%s unable to allocate a config object.", __func__); goto error; } } if (config_save(config, CONFIG_FILE_PATH)) unlink(LEGACY_CONFIG_FILE_PATH); } alarm_timer = alarm_new(); if (!alarm_timer) { LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__); goto error; } return future_new_immediate(FUTURE_SUCCESS); error:; alarm_free(alarm_timer); config_free(config); pthread_mutex_destroy(&lock); alarm_timer = NULL; config = NULL; return future_new_immediate(FUTURE_FAIL); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 CWE ID: CWE-119
static future_t *init(void) { pthread_mutex_init(&lock, NULL); config = config_new(CONFIG_FILE_PATH); if (!config) { LOG_WARN(LOG_TAG, "%s unable to load config file; attempting to transcode legacy file.", __func__); config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH); if (!config) { LOG_WARN(LOG_TAG, "%s unable to transcode legacy file, starting unconfigured.", __func__); config = config_new_empty(); if (!config) { LOG_ERROR(LOG_TAG, "%s unable to allocate a config object.", __func__); goto error; } } if (config_save(config, CONFIG_FILE_PATH)) unlink(LEGACY_CONFIG_FILE_PATH); } btif_config_devcache_cleanup(); alarm_timer = alarm_new(); if (!alarm_timer) { LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__); goto error; } return future_new_immediate(FUTURE_SUCCESS); error:; alarm_free(alarm_timer); config_free(config); pthread_mutex_destroy(&lock); alarm_timer = NULL; config = NULL; return future_new_immediate(FUTURE_FAIL); }
173,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; size_t length; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Convert HRZ raster image to pixel packets. */ image->columns=256; image->rows=240; image->depth=8; pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) (3*image->columns); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(4**p++)); SetPixelGreen(q,ScaleCharToQuantum(4**p++)); SetPixelBlue(q,ScaleCharToQuantum(4**p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; size_t length; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Convert HRZ raster image to pixel packets. */ image->columns=256; image->rows=240; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) (3*image->columns); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(4**p++)); SetPixelGreen(q,ScaleCharToQuantum(4**p++)); SetPixelBlue(q,ScaleCharToQuantum(4**p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MountLibrary* CrosLibrary::GetMountLibrary() { return mount_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
MountLibrary* CrosLibrary::GetMountLibrary() {
170,626
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc) { uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; horDiff16(tif, cp0, cc); TIFFSwabArrayOfShort(wp, wc); } 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
swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc) { uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; if( !horDiff16(tif, cp0, cc) ) return 0; TIFFSwabArrayOfShort(wp, wc); return 1; }
166,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FaviconSource::StartDataRequest(const std::string& path, bool is_incognito, int request_id) { FaviconService* favicon_service = profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); if (favicon_service) { FaviconService::Handle handle; if (path.empty()) { SendDefaultResponse(request_id); return; } if (path.size() > 8 && path.substr(0, 8) == "iconurl/") { handle = favicon_service->GetFavicon( GURL(path.substr(8)), history::FAVICON, &cancelable_consumer_, NewCallback(this, &FaviconSource::OnFaviconDataAvailable)); } else { handle = favicon_service->GetFaviconForURL( GURL(path), icon_types_, &cancelable_consumer_, NewCallback(this, &FaviconSource::OnFaviconDataAvailable)); } cancelable_consumer_.SetClientData(favicon_service, handle, request_id); } else { SendResponse(request_id, NULL); } } Commit Message: ntp4: show larger favicons in most visited page extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe). BUG=none TEST=manual Review URL: http://codereview.chromium.org/7300017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void FaviconSource::StartDataRequest(const std::string& path, bool is_incognito, int request_id) { FaviconService* favicon_service = profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); if (favicon_service) { if (path.empty()) { SendDefaultResponse(request_id); return; } FaviconService::Handle handle; if (path.size() > 8 && path.substr(0, 8) == "iconurl/") { handle = favicon_service->GetFavicon( GURL(path.substr(8)), history::FAVICON, &cancelable_consumer_, NewCallback(this, &FaviconSource::OnFaviconDataAvailable)); } else { GURL url; if (path.size() > 5 && path.substr(0, 5) == "size/") { size_t slash = path.find("/", 5); std::string size = path.substr(5, slash - 5); int pixel_size = atoi(size.c_str()); CHECK(pixel_size == 32 || pixel_size == 16) << "only 32x32 and 16x16 icons are supported"; request_size_map_[request_id] = pixel_size; url = GURL(path.substr(slash + 1)); } else { request_size_map_[request_id] = 16; url = GURL(path); } // TODO(estade): fetch the requested size. handle = favicon_service->GetFaviconForURL( url, icon_types_, &cancelable_consumer_, NewCallback(this, &FaviconSource::OnFaviconDataAvailable)); } cancelable_consumer_.SetClientData(favicon_service, handle, request_id); } else { SendResponse(request_id, NULL); } }
170,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register z_crc_t c; register const z_crc_t FAR *buf4; c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const z_crc_t FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf4++; buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(ZSWAP32(c)); } Commit Message: Avoid pre-decrement of pointer in big-endian CRC calculation. There was a small optimization for PowerPCs to pre-increment a pointer when accessing a word, instead of post-incrementing. This required prefacing the loop with a decrement of the pointer, possibly pointing before the object passed. This is not compliant with the C standard, for which decrementing a pointer before its allocated memory is undefined. When tested on a modern PowerPC with a modern compiler, the optimization no longer has any effect. Due to all that, and per the recommendation of a security audit of the zlib code by Trail of Bits and TrustInSoft, in support of the Mozilla Foundation, this "optimization" was removed, in order to avoid the possibility of undefined behavior. CWE ID: CWE-189
local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register z_crc_t c; register const z_crc_t FAR *buf4; c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const z_crc_t FAR *)(const void FAR *)buf; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(ZSWAP32(c)); }
168,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy) { mrb_value orig; mrb_value buf; struct mrb_io *fptr_copy; struct mrb_io *fptr_orig; mrb_bool failed = TRUE; mrb_get_args(mrb, "o", &orig); fptr_copy = (struct mrb_io *)DATA_PTR(copy); if (fptr_copy != NULL) { fptr_finalize(mrb, fptr_copy, FALSE); mrb_free(mrb, fptr_copy); } fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb); fptr_orig = io_get_open_fptr(mrb, orig); DATA_TYPE(copy) = &mrb_io_type; DATA_PTR(copy) = fptr_copy; buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf")); mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf); fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed); if (failed) { mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd); if (fptr_orig->fd2 != -1) { fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed); if (failed) { close(fptr_copy->fd); mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd2); } fptr_copy->pid = fptr_orig->pid; fptr_copy->readable = fptr_orig->readable; fptr_copy->writable = fptr_orig->writable; fptr_copy->sync = fptr_orig->sync; fptr_copy->is_socket = fptr_orig->is_socket; return copy; } Commit Message: Fix `use after free in File#initilialize_copy`; fix #4001 The bug and the fix were reported by https://hackerone.com/pnoltof CWE ID: CWE-416
mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy) { mrb_value orig; mrb_value buf; struct mrb_io *fptr_copy; struct mrb_io *fptr_orig; mrb_bool failed = TRUE; mrb_get_args(mrb, "o", &orig); fptr_orig = io_get_open_fptr(mrb, orig); fptr_copy = (struct mrb_io *)DATA_PTR(copy); if (fptr_copy != NULL) { fptr_finalize(mrb, fptr_copy, FALSE); mrb_free(mrb, fptr_copy); } fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb); DATA_TYPE(copy) = &mrb_io_type; DATA_PTR(copy) = fptr_copy; buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf")); mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf); fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed); if (failed) { mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd); if (fptr_orig->fd2 != -1) { fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed); if (failed) { close(fptr_copy->fd); mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd2); } fptr_copy->pid = fptr_orig->pid; fptr_copy->readable = fptr_orig->readable; fptr_copy->writable = fptr_orig->writable; fptr_copy->sync = fptr_orig->sync; fptr_copy->is_socket = fptr_orig->is_socket; return copy; }
169,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void fslib_copy_libs(const char *full_path) { assert(full_path); if (arg_debug || arg_debug_private_lib) printf(" fslib_copy_libs %s\n", full_path); if (access(full_path, R_OK)) { if (arg_debug || arg_debug_private_lib) printf("cannot find %s for private-lib, skipping...\n", full_path); return; } unlink(RUN_LIB_FILE); // in case is there create_empty_file_as_root(RUN_LIB_FILE, 0644); if (chown(RUN_LIB_FILE, getuid(), getgid())) errExit("chown"); if (arg_debug || arg_debug_private_lib) printf(" running fldd %s\n", full_path); sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE); FILE *fp = fopen(RUN_LIB_FILE, "r"); if (!fp) errExit("fopen"); char buf[MAXBUF]; while (fgets(buf, MAXBUF, fp)) { char *ptr = strchr(buf, '\n'); if (ptr) *ptr = '\0'; fslib_duplicate(buf); } fclose(fp); } Commit Message: mount runtime seccomp files read-only (#2602) avoid creating locations in the file system that are both writable and executable (in this case for processes with euid of the user). for the same reason also remove user owned libfiles when it is not needed any more CWE ID: CWE-284
void fslib_copy_libs(const char *full_path) { assert(full_path); if (arg_debug || arg_debug_private_lib) printf(" fslib_copy_libs %s\n", full_path); if (access(full_path, R_OK)) { if (arg_debug || arg_debug_private_lib) printf("cannot find %s for private-lib, skipping...\n", full_path); return; } unlink(RUN_LIB_FILE); // in case is there create_empty_file_as_root(RUN_LIB_FILE, 0644); if (chown(RUN_LIB_FILE, getuid(), getgid())) errExit("chown"); if (arg_debug || arg_debug_private_lib) printf(" running fldd %s\n", full_path); sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE); FILE *fp = fopen(RUN_LIB_FILE, "r"); if (!fp) errExit("fopen"); char buf[MAXBUF]; while (fgets(buf, MAXBUF, fp)) { char *ptr = strchr(buf, '\n'); if (ptr) *ptr = '\0'; fslib_duplicate(buf); } fclose(fp); unlink(RUN_LIB_FILE); }
169,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Block::~Block() { delete[] m_frames; } 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
Block::~Block()
174,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 array_cleanup( char* arr[] , int arr_size) { int i=0; for( i=0; i< arr_size; i++ ){ if( arr[i*2] ){ efree( arr[i*2]); } } efree(arr); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static void array_cleanup( char* arr[] , int arr_size) { int i=0; for( i=0; i< arr_size; i++ ){ if( arr[i*2] ){ efree( arr[i*2]); } } efree(arr); }
167,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 void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } Commit Message: [OPENJP2] change the way to compute *p_tx0, *p_tx1, *p_ty0, *p_ty1 in function opj_get_encoding_parameters Signed-off-by: Young_X <YangX92@hotmail.com> CWE ID: CWE-190
static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* non-corrected (in regard to image offset) tile offset */ OPJ_UINT32 l_tx0, l_ty0; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ l_tx0 = p_cp->tx0 + p * p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */ *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0); *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1); l_ty0 = p_cp->ty0 + q * p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */ *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0); *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } }
169,766
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: setup_server_realm(krb5_principal sprinc) { krb5_error_code kret; kdc_realm_t *newrealm; kret = 0; if (kdc_numrealms > 1) { if (!(newrealm = find_realm_data(sprinc->realm.data, (krb5_ui_4) sprinc->realm.length))) kret = ENOENT; else kdc_active_realm = newrealm; } else kdc_active_realm = kdc_realmlist[0]; return(kret); } Commit Message: Multi-realm KDC null deref [CVE-2013-1418] If a KDC serves multiple realms, certain requests can cause setup_server_realm() to dereference a null pointer, crashing the KDC. CVSSv2: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C A related but more minor vulnerability requires authentication to exploit, and is only present if a third-party KDC database module can dereference a null pointer under certain conditions. (back ported from commit 5d2d9a1abe46a2c1a8614d4672d08d9d30a5f8bf) ticket: 7757 (new) version_fixed: 1.10.7 status: resolved CWE ID:
setup_server_realm(krb5_principal sprinc) { krb5_error_code kret; kdc_realm_t *newrealm; kret = 0; if (sprinc == NULL) return NULL; if (kdc_numrealms > 1) { if (!(newrealm = find_realm_data(sprinc->realm.data, (krb5_ui_4) sprinc->realm.length))) kret = ENOENT; else kdc_active_realm = newrealm; } else kdc_active_realm = kdc_realmlist[0]; return(kret); }
165,933
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|truncated]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; }
169,830
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: iperf_json_printf(const char *format, ...) { cJSON* o; va_list argp; const char *cp; char name[100]; char* np; cJSON* j; o = cJSON_CreateObject(); if (o == NULL) return NULL; va_start(argp, format); np = name; for (cp = format; *cp != '\0'; ++cp) { switch (*cp) { case ' ': break; case ':': *np = '\0'; break; case '%': ++cp; switch (*cp) { case 'b': j = cJSON_CreateBool(va_arg(argp, int)); break; case 'd': j = cJSON_CreateInt(va_arg(argp, int64_t)); break; case 'f': j = cJSON_CreateFloat(va_arg(argp, double)); break; case 's': j = cJSON_CreateString(va_arg(argp, char *)); break; default: return NULL; } if (j == NULL) return NULL; cJSON_AddItemToObject(o, name, j); np = name; break; default: *np++ = *cp; break; } } va_end(argp); return o; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
iperf_json_printf(const char *format, ...) { cJSON* o; va_list argp; const char *cp; char name[100]; char* np; cJSON* j; o = cJSON_CreateObject(); if (o == NULL) return NULL; va_start(argp, format); np = name; for (cp = format; *cp != '\0'; ++cp) { switch (*cp) { case ' ': break; case ':': *np = '\0'; break; case '%': ++cp; switch (*cp) { case 'b': j = cJSON_CreateBool(va_arg(argp, int)); break; case 'd': j = cJSON_CreateNumber(va_arg(argp, int64_t)); break; case 'f': j = cJSON_CreateNumber(va_arg(argp, double)); break; case 's': j = cJSON_CreateString(va_arg(argp, char *)); break; default: return NULL; } if (j == NULL) return NULL; cJSON_AddItemToObject(o, name, j); np = name; break; default: *np++ = *cp; break; } } va_end(argp); return o; }
167,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfs3svc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readargs *args) { unsigned int len; int v; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); len = min(args->count, max_blocksize); /* set up the kvec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfs3svc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readargs *args) { unsigned int len; int v; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); if (!xdr_argsize_check(rqstp, p)) return 0; len = min(args->count, max_blocksize); /* set up the kvec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return 1; }
168,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: isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; for (i = 1; i <= SYSTEM_ID_LEN; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } Commit Message: CVE-2017-13035/Properly handle IS-IS IDs shorter than a system ID (MAC address). Some of them are variable-length, with a field giving the total length, and therefore they can be shorter than 6 octets. If one is, don't run past the end. 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. CWE ID: CWE-125
isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; int sysid_len; sysid_len = SYSTEM_ID_LEN; if (sysid_len > id_len) sysid_len = id_len; for (i = 1; i <= sysid_len; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); }
167,848
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: externalParEntProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { const char *next = s; int tok; tok = XmlPrologTok(parser->m_encoding, s, end, &next); if (tok <= 0) { if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case XML_TOK_NONE: /* start == end */ default: break; } } /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. However, when parsing an external subset, doProlog will not accept a BOM as valid, and report a syntax error, so we have to skip the BOM */ else if (tok == XML_TOK_BOM) { s = next; tok = XmlPrologTok(parser->m_encoding, s, end, &next); } parser->m_processor = prologProcessor; return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611
externalParEntProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { const char *next = s; int tok; tok = XmlPrologTok(parser->m_encoding, s, end, &next); if (tok <= 0) { if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case XML_TOK_NONE: /* start == end */ default: break; } } /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. However, when parsing an external subset, doProlog will not accept a BOM as valid, and report a syntax error, so we have to skip the BOM */ else if (tok == XML_TOK_BOM) { s = next; tok = XmlPrologTok(parser->m_encoding, s, end, &next); } parser->m_processor = prologProcessor; return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE); }
169,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 utf32_to_utf8(const char32_t* src, size_t src_len, char* dst) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char32_t *cur_utf32 = src; const char32_t *end_utf32 = src + src_len; char *cur = dst; while (cur_utf32 < end_utf32) { size_t len = utf32_codepoint_utf8_length(*cur_utf32); utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len); cur += len; } *cur = '\0'; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst) void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char32_t *cur_utf32 = src; const char32_t *end_utf32 = src + src_len; char *cur = dst; while (cur_utf32 < end_utf32) { size_t len = utf32_codepoint_utf8_length(*cur_utf32); LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len); utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len); cur += len; dst_len -= len; } LOG_ALWAYS_FATAL_IF(dst_len < 1, "dst_len < 1: %zu < 1", dst_len); *cur = '\0'; }
173,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *skcipher_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_skcipher(name, type, mask); } Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: stable@vger.kernel.org Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Tested-by: Dmitry Vyukov <dvyukov@google.com> CWE ID: CWE-476
static void *skcipher_bind(const char *name, u32 type, u32 mask) { struct skcipher_tfm *tfm; struct crypto_skcipher *skcipher; tfm = kzalloc(sizeof(*tfm), GFP_KERNEL); if (!tfm) return ERR_PTR(-ENOMEM); skcipher = crypto_alloc_skcipher(name, type, mask); if (IS_ERR(skcipher)) { kfree(tfm); return ERR_CAST(skcipher); } tfm->skcipher = skcipher; return tfm; }
167,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SyncManager::SyncInternal::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* model_safe_worker_registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, bool enable_sync_tabs_for_other_clients, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { CHECK(!initialized_); DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "Starting SyncInternal initialization."; weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()); blocking_task_runner_ = blocking_task_runner; registrar_ = model_safe_worker_registrar; change_delegate_ = change_delegate; testing_mode_ = testing_mode; enable_sync_tabs_for_other_clients_ = enable_sync_tabs_for_other_clients; sync_notifier_.reset(sync_notifier); AddObserver(&js_sync_manager_observer_); SetJsEventHandler(event_handler); AddObserver(&debug_info_event_listener_); database_path_ = database_location.Append( syncable::Directory::kSyncDatabaseFilename); encryptor_ = encryptor; unrecoverable_error_handler_ = unrecoverable_error_handler; report_unrecoverable_error_function_ = report_unrecoverable_error_function; share_.directory.reset( new syncable::Directory(encryptor_, unrecoverable_error_handler_, report_unrecoverable_error_function_)); connection_manager_.reset(new SyncAPIServerConnectionManager( sync_server_and_path, port, use_ssl, user_agent, post_factory)); net::NetworkChangeNotifier::AddIPAddressObserver(this); observing_ip_address_changes_ = true; connection_manager()->AddListener(this); if (testing_mode_ == NON_TEST) { DVLOG(1) << "Sync is bringing up SyncSessionContext."; std::vector<SyncEngineEventListener*> listeners; listeners.push_back(&allstatus_); listeners.push_back(this); SyncSessionContext* context = new SyncSessionContext( connection_manager_.get(), directory(), model_safe_worker_registrar, extensions_activity_monitor, listeners, &debug_info_event_listener_, &traffic_recorder_); context->set_account_name(credentials.email); scheduler_.reset(new SyncScheduler(name_, context, new Syncer())); } bool signed_in = SignIn(credentials); if (signed_in) { if (scheduler()) { scheduler()->Start( browser_sync::SyncScheduler::CONFIGURATION_MODE, base::Closure()); } initialized_ = true; ReadTransaction trans(FROM_HERE, GetUserShare()); trans.GetCryptographer()->Bootstrap(restored_key_for_bootstrapping); trans.GetCryptographer()->AddObserver(this); } FOR_EACH_OBSERVER(SyncManager::Observer, observers_, OnInitializationComplete( MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()), signed_in)); if (!signed_in && testing_mode_ == NON_TEST) return false; sync_notifier_->AddObserver(this); return signed_in; } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
bool SyncManager::SyncInternal::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* model_safe_worker_registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { CHECK(!initialized_); DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "Starting SyncInternal initialization."; weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()); blocking_task_runner_ = blocking_task_runner; registrar_ = model_safe_worker_registrar; change_delegate_ = change_delegate; testing_mode_ = testing_mode; sync_notifier_.reset(sync_notifier); AddObserver(&js_sync_manager_observer_); SetJsEventHandler(event_handler); AddObserver(&debug_info_event_listener_); database_path_ = database_location.Append( syncable::Directory::kSyncDatabaseFilename); encryptor_ = encryptor; unrecoverable_error_handler_ = unrecoverable_error_handler; report_unrecoverable_error_function_ = report_unrecoverable_error_function; share_.directory.reset( new syncable::Directory(encryptor_, unrecoverable_error_handler_, report_unrecoverable_error_function_)); connection_manager_.reset(new SyncAPIServerConnectionManager( sync_server_and_path, port, use_ssl, user_agent, post_factory)); net::NetworkChangeNotifier::AddIPAddressObserver(this); observing_ip_address_changes_ = true; connection_manager()->AddListener(this); if (testing_mode_ == NON_TEST) { DVLOG(1) << "Sync is bringing up SyncSessionContext."; std::vector<SyncEngineEventListener*> listeners; listeners.push_back(&allstatus_); listeners.push_back(this); SyncSessionContext* context = new SyncSessionContext( connection_manager_.get(), directory(), model_safe_worker_registrar, extensions_activity_monitor, listeners, &debug_info_event_listener_, &traffic_recorder_); context->set_account_name(credentials.email); scheduler_.reset(new SyncScheduler(name_, context, new Syncer())); } bool signed_in = SignIn(credentials); if (signed_in) { if (scheduler()) { scheduler()->Start( browser_sync::SyncScheduler::CONFIGURATION_MODE, base::Closure()); } initialized_ = true; ReadTransaction trans(FROM_HERE, GetUserShare()); trans.GetCryptographer()->Bootstrap(restored_key_for_bootstrapping); trans.GetCryptographer()->AddObserver(this); } FOR_EACH_OBSERVER(SyncManager::Observer, observers_, OnInitializationComplete( MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()), signed_in)); if (!signed_in && testing_mode_ == NON_TEST) return false; sync_notifier_->AddObserver(this); return signed_in; }
170,793
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DisconnectWindowLinux::Hide() { NOTIMPLEMENTED(); } Commit Message: Initial implementation of DisconnectWindow on Linux. BUG=None TEST=Manual Review URL: http://codereview.chromium.org/7089016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88889 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DisconnectWindowLinux::Hide() { DCHECK(disconnect_window_); gtk_widget_hide(disconnect_window_); } gboolean DisconnectWindowLinux::OnWindowDelete(GtkWidget* widget, GdkEvent* event) { // Don't allow the window to be closed. return TRUE; } void DisconnectWindowLinux::OnDisconnectClicked(GtkButton* sender) { DCHECK(host_); host_->Shutdown(); }
170,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_expand_16_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_16(pp); this->next->set(this->next, that, pp, pi); } 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_expand_16_set(PNG_CONST image_transform *this, image_transform_png_set_expand_16_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_16(pp); /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */ # if PNG_LIBPNG_VER < 10700 if (that->this.has_tRNS) that->this.is_transparent = 1; # endif this->next->set(this->next, that, pp, pi); }
173,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_emit_frobnicate (MyObject *obj, GError **error) { g_signal_emit (obj, signals[FROBNICATE], 0, 42); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_emit_frobnicate (MyObject *obj, GError **error)
165,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284
int socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; }
167,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: HarfBuzzShaperBase::HarfBuzzShaperBase(const Font* font, const TextRun& run) : m_font(font) , m_run(run) , m_wordSpacingAdjustment(font->wordSpacing()) , m_letterSpacing(font->letterSpacing()) { } Commit Message: Fix uninitialized variables in HarfBuzzShaperBase https://bugs.webkit.org/show_bug.cgi?id=79546 Reviewed by Dirk Pranke. These were introduced in r108733. * platform/graphics/harfbuzz/HarfBuzzShaperBase.cpp: (WebCore::HarfBuzzShaperBase::HarfBuzzShaperBase): git-svn-id: svn://svn.chromium.org/blink/trunk@108871 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-362
HarfBuzzShaperBase::HarfBuzzShaperBase(const Font* font, const TextRun& run) : m_font(font) , m_normalizedBufferLength(0) , m_run(run) , m_wordSpacingAdjustment(font->wordSpacing()) , m_padding(0) , m_padPerWordBreak(0) , m_padError(0) , m_letterSpacing(font->letterSpacing()) { }
170,964
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int send_full_color_rect(VncState *vs, int x, int y, int w, int h) { int stream = 0; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, NULL); } #endif tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->clientds.pf.bytes_per_pixel; } Commit Message: CWE ID: CWE-125
static int send_full_color_rect(VncState *vs, int x, int y, int w, int h) { int stream = 0; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, NULL); } #endif tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->client_pf.bytes_per_pixel; }
165,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: main(void) { fprintf(stderr, "pngfix does not work without read support\n"); return 77; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
main(void) { fprintf(stderr, "pngfix does not work without read deinterlace support\n"); return 77; }
173,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv; unsigned ii; const unsigned char *tag = NULL; unsigned char ops_DF[8] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; unsigned char ops_EF[8] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); if (!file->sec_attr_len) { sc_log_hex(ctx, "ACLs not found in data", buf, buflen); sc_log(ctx, "Path:%s; Type:%X; PathType:%X", sc_print_path(&file->path), file->type, file->path.type); if (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) { file->type = SC_FILE_TYPE_DF; } else { LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } } sc_log_hex(ctx, "ACL data", file->sec_attr, file->sec_attr_len); for (ii = 0; ii < file->sec_attr_len / 2; ii++) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; unsigned char acl = *(file->sec_attr + ii*2); unsigned char cred_id = *(file->sec_attr + ii*2 + 1); unsigned sc = acl * 0x100 + cred_id; sc_log(ctx, "ACL(%i) op 0x%X, acl %X:%X", ii, op, acl, cred_id); if (op == 0xFF) ; else if (!acl && !cred_id) sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); else if (acl == 0xFF) sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); else if (acl & AUTHENTIC_AC_SM_MASK) sc_file_add_acl_entry(file, op, SC_AC_SCB, sc); else if (cred_id) sc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id); else sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } LOG_FUNC_RETURN(ctx, 0); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv; unsigned ii; const unsigned char *tag = NULL; unsigned char ops_DF[8] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; unsigned char ops_EF[8] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); if (!file->sec_attr_len) { sc_log_hex(ctx, "ACLs not found in data", buf, buflen); sc_log(ctx, "Path:%s; Type:%X; PathType:%X", sc_print_path(&file->path), file->type, file->path.type); if (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) { file->type = SC_FILE_TYPE_DF; } else { LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } } sc_log_hex(ctx, "ACL data", file->sec_attr, file->sec_attr_len); for (ii = 0; ii < file->sec_attr_len / 2 && ii < sizeof ops_DF; ii++) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; unsigned char acl = *(file->sec_attr + ii*2); unsigned char cred_id = *(file->sec_attr + ii*2 + 1); unsigned sc = acl * 0x100 + cred_id; sc_log(ctx, "ACL(%i) op 0x%X, acl %X:%X", ii, op, acl, cred_id); if (op == 0xFF) ; else if (!acl && !cred_id) sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); else if (acl == 0xFF) sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); else if (acl & AUTHENTIC_AC_SM_MASK) sc_file_add_acl_entry(file, op, SC_AC_SCB, sc); else if (cred_id) sc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id); else sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } LOG_FUNC_RETURN(ctx, 0); }
169,048
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 parse_report(transport_smart *transport, git_push *push) { git_pkt *pkt = NULL; const char *line_end = NULL; gitno_buffer *buf = &transport->buffer; int error, recvd; git_buf data_pkt_buf = GIT_BUF_INIT; for (;;) { if (buf->offset > 0) error = git_pkt_parse_line(&pkt, buf->data, &line_end, buf->offset); else error = GIT_EBUFS; if (error < 0 && error != GIT_EBUFS) { error = -1; goto done; } if (error == GIT_EBUFS) { if ((recvd = gitno_recv(buf)) < 0) { error = recvd; goto done; } if (recvd == 0) { giterr_set(GITERR_NET, "early EOF"); error = GIT_EEOF; goto done; } continue; } gitno_consume(buf, line_end); error = 0; if (pkt == NULL) continue; switch (pkt->type) { case GIT_PKT_DATA: /* This is a sideband packet which contains other packets */ error = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf); break; case GIT_PKT_ERR: giterr_set(GITERR_NET, "report-status: Error reported: %s", ((git_pkt_err *)pkt)->error); error = -1; break; case GIT_PKT_PROGRESS: if (transport->progress_cb) { git_pkt_progress *p = (git_pkt_progress *) pkt; error = transport->progress_cb(p->data, p->len, transport->message_cb_payload); } break; default: error = add_push_report_pkt(push, pkt); break; } git_pkt_free(pkt); /* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */ if (error == GIT_ITEROVER) { error = 0; if (data_pkt_buf.size > 0) { /* If there was data remaining in the pack data buffer, * then the server sent a partial pkt-line */ giterr_set(GITERR_NET, "Incomplete pack data pkt-line"); error = GIT_ERROR; } goto done; } if (error < 0) { goto done; } } done: git_buf_free(&data_pkt_buf); return error; } Commit Message: smart_pkt: treat empty packet lines as error The Git protocol does not specify what should happen in the case of an empty packet line (that is a packet line "0004"). We currently indicate success, but do not return a packet in the case where we hit an empty line. The smart protocol was not prepared to handle such packets in all cases, though, resulting in a `NULL` pointer dereference. Fix the issue by returning an error instead. As such kind of packets is not even specified by upstream, this is the right thing to do. CWE ID: CWE-476
static int parse_report(transport_smart *transport, git_push *push) { git_pkt *pkt = NULL; const char *line_end = NULL; gitno_buffer *buf = &transport->buffer; int error, recvd; git_buf data_pkt_buf = GIT_BUF_INIT; for (;;) { if (buf->offset > 0) error = git_pkt_parse_line(&pkt, buf->data, &line_end, buf->offset); else error = GIT_EBUFS; if (error < 0 && error != GIT_EBUFS) { error = -1; goto done; } if (error == GIT_EBUFS) { if ((recvd = gitno_recv(buf)) < 0) { error = recvd; goto done; } if (recvd == 0) { giterr_set(GITERR_NET, "early EOF"); error = GIT_EEOF; goto done; } continue; } gitno_consume(buf, line_end); error = 0; switch (pkt->type) { case GIT_PKT_DATA: /* This is a sideband packet which contains other packets */ error = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf); break; case GIT_PKT_ERR: giterr_set(GITERR_NET, "report-status: Error reported: %s", ((git_pkt_err *)pkt)->error); error = -1; break; case GIT_PKT_PROGRESS: if (transport->progress_cb) { git_pkt_progress *p = (git_pkt_progress *) pkt; error = transport->progress_cb(p->data, p->len, transport->message_cb_payload); } break; default: error = add_push_report_pkt(push, pkt); break; } git_pkt_free(pkt); /* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */ if (error == GIT_ITEROVER) { error = 0; if (data_pkt_buf.size > 0) { /* If there was data remaining in the pack data buffer, * then the server sent a partial pkt-line */ giterr_set(GITERR_NET, "Incomplete pack data pkt-line"); error = GIT_ERROR; } goto done; } if (error < 0) { goto done; } } done: git_buf_free(&data_pkt_buf); return error; }
168,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 void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow * const pflow) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP); /* cleanup pkt specific part of the patternmatcher */ PacketPatternCleanup(det_ctx); if (pflow != NULL) { /* update inspected tracker for raw reassembly */ if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) { StreamReassembleRawUpdateProgress(pflow->protoctx, p, det_ctx->raw_stream_progress); DetectEngineCleanHCBDBuffers(det_ctx); } } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP); SCReturn; } Commit Message: stream: fix false negative on bad RST If a bad RST was received the stream inspection would not happen for that packet, but it would still move the 'raw progress' tracker forward. Following good packets would then fail to detect anything before the 'raw progress' position. Bug #2770 Reported-by: Alexey Vishnyakov CWE ID: CWE-347
static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow * const pflow) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP); /* cleanup pkt specific part of the patternmatcher */ PacketPatternCleanup(det_ctx); if (pflow != NULL) { /* update inspected tracker for raw reassembly */ if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL && (p->flags & PKT_STREAM_EST)) { StreamReassembleRawUpdateProgress(pflow->protoctx, p, det_ctx->raw_stream_progress); DetectEngineCleanHCBDBuffers(det_ctx); } } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP); SCReturn; }
169,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: m_authenticate(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *agent_p = NULL; struct Client *saslserv_p = NULL; /* They really should use CAP for their own sake. */ if(!IsCapable(source_p, CLICAP_SASL)) return 0; if (strlen(client_p->id) == 3) { exit_client(client_p, client_p, client_p, "Mixing client and server protocol"); return 0; } saslserv_p = find_named_client(ConfigFileEntry.sasl_service); if (saslserv_p == NULL || !IsService(saslserv_p)) { sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(source_p->localClient->sasl_complete) { *source_p->localClient->sasl_agent = '\0'; source_p->localClient->sasl_complete = 0; } if(strlen(parv[1]) > 400) { sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(!*source_p->id) { /* Allocate a UID. */ strcpy(source_p->id, generate_uid()); add_to_id_hash(source_p->id, source_p); } if(*source_p->localClient->sasl_agent) agent_p = find_id(source_p->localClient->sasl_agent); if(agent_p == NULL) { sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, source_p->host, source_p->sockhost); if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL) sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1], source_p->certfp); else sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1]); rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN); } else sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s", me.id, agent_p->servptr->name, source_p->id, agent_p->id, parv[1]); source_p->localClient->sasl_out++; return 0; } Commit Message: SASL: Disallow beginning : and space anywhere in AUTHENTICATE parameter This is a FIX FOR A SECURITY VULNERABILITY. All Charybdis users must apply this fix if you support SASL on your servers, or unload m_sasl.so in the meantime. CWE ID: CWE-285
m_authenticate(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *agent_p = NULL; struct Client *saslserv_p = NULL; /* They really should use CAP for their own sake. */ if(!IsCapable(source_p, CLICAP_SASL)) return 0; if (strlen(client_p->id) == 3) { exit_client(client_p, client_p, client_p, "Mixing client and server protocol"); return 0; } if (*parv[1] == ':' || strchr(parv[1], ' ')) { exit_client(client_p, client_p, client_p, "Malformed AUTHENTICATE"); return 0; } saslserv_p = find_named_client(ConfigFileEntry.sasl_service); if (saslserv_p == NULL || !IsService(saslserv_p)) { sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(source_p->localClient->sasl_complete) { *source_p->localClient->sasl_agent = '\0'; source_p->localClient->sasl_complete = 0; } if(strlen(parv[1]) > 400) { sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(!*source_p->id) { /* Allocate a UID. */ strcpy(source_p->id, generate_uid()); add_to_id_hash(source_p->id, source_p); } if(*source_p->localClient->sasl_agent) agent_p = find_id(source_p->localClient->sasl_agent); if(agent_p == NULL) { sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, source_p->host, source_p->sockhost); if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL) sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1], source_p->certfp); else sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1]); rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN); } else sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s", me.id, agent_p->servptr->name, source_p->id, agent_p->id, parv[1]); source_p->localClient->sasl_out++; return 0; }
166,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DOMHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { host_ = frame_host; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void DOMHandler::SetRenderer(RenderProcessHost* process_host, void DOMHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { host_ = frame_host; }
172,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; } Commit Message: Encoder: grow buffer size in opj_tcd_code_block_enc_allocate_data() to avoid write heap buffer overflow in opj_mqc_flush (#982) CWE ID: CWE-119
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */ /* TODO: is there a theoretical upper-bound for the compressed code */ /* block size ? */ l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; }
167,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: 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) { 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; } err = check_entry(e); 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_err("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: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-119
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; } err = check_entry(e); 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_err("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,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t oz_cdev_write(struct file *filp, const char __user *buf, size_t count, loff_t *fpos) { struct oz_pd *pd; struct oz_elt_buf *eb; struct oz_elt_info *ei; struct oz_elt *elt; struct oz_app_hdr *app_hdr; struct oz_serial_ctx *ctx; spin_lock_bh(&g_cdev.lock); pd = g_cdev.active_pd; if (pd) oz_pd_get(pd); spin_unlock_bh(&g_cdev.lock); if (pd == NULL) return -ENXIO; if (!(pd->state & OZ_PD_S_CONNECTED)) return -EAGAIN; eb = &pd->elt_buff; ei = oz_elt_info_alloc(eb); if (ei == NULL) { count = 0; goto out; } elt = (struct oz_elt *)ei->data; app_hdr = (struct oz_app_hdr *)(elt+1); elt->length = sizeof(struct oz_app_hdr) + count; elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_SERIAL; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_SERIAL; if (copy_from_user(app_hdr+1, buf, count)) goto out; spin_lock_bh(&pd->app_lock[OZ_APPID_USB-1]); ctx = (struct oz_serial_ctx *)pd->app_ctx[OZ_APPID_SERIAL-1]; if (ctx) { app_hdr->elt_seq_num = ctx->tx_seq_num++; if (ctx->tx_seq_num == 0) ctx->tx_seq_num = 1; spin_lock(&eb->lock); if (oz_queue_elt_info(eb, 0, 0, ei) == 0) ei = NULL; spin_unlock(&eb->lock); } spin_unlock_bh(&pd->app_lock[OZ_APPID_USB-1]); out: if (ei) { count = 0; spin_lock_bh(&eb->lock); oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); } oz_pd_put(pd); return count; } Commit Message: staging: ozwpan: prevent overflow in oz_cdev_write() We need to check "count" so we don't overflow the ei->data buffer. Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-119
static ssize_t oz_cdev_write(struct file *filp, const char __user *buf, size_t count, loff_t *fpos) { struct oz_pd *pd; struct oz_elt_buf *eb; struct oz_elt_info *ei; struct oz_elt *elt; struct oz_app_hdr *app_hdr; struct oz_serial_ctx *ctx; if (count > sizeof(ei->data) - sizeof(*elt) - sizeof(*app_hdr)) return -EINVAL; spin_lock_bh(&g_cdev.lock); pd = g_cdev.active_pd; if (pd) oz_pd_get(pd); spin_unlock_bh(&g_cdev.lock); if (pd == NULL) return -ENXIO; if (!(pd->state & OZ_PD_S_CONNECTED)) return -EAGAIN; eb = &pd->elt_buff; ei = oz_elt_info_alloc(eb); if (ei == NULL) { count = 0; goto out; } elt = (struct oz_elt *)ei->data; app_hdr = (struct oz_app_hdr *)(elt+1); elt->length = sizeof(struct oz_app_hdr) + count; elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_SERIAL; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_SERIAL; if (copy_from_user(app_hdr+1, buf, count)) goto out; spin_lock_bh(&pd->app_lock[OZ_APPID_USB-1]); ctx = (struct oz_serial_ctx *)pd->app_ctx[OZ_APPID_SERIAL-1]; if (ctx) { app_hdr->elt_seq_num = ctx->tx_seq_num++; if (ctx->tx_seq_num == 0) ctx->tx_seq_num = 1; spin_lock(&eb->lock); if (oz_queue_elt_info(eb, 0, 0, ei) == 0) ei = NULL; spin_unlock(&eb->lock); } spin_unlock_bh(&pd->app_lock[OZ_APPID_USB-1]); out: if (ei) { count = 0; spin_lock_bh(&eb->lock); oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); } oz_pd_put(pd); return count; }
165,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Error: invalid .asoundrc file\n"); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); if (chown(dest, getuid(), getgid()) == -1) errExit("fchown"); if (chmod(dest, 0644) == -1) errExit("fchmod"); return 1; // file copied } return 0; } Commit Message: security fix CWE ID: CWE-269
static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; // create an empty file as root, and change ownership to user FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { // make sure the real path of the file is inside the home directory /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } copy_file_as_user(src, dest, getuid(), getgid(), 0644); // regular user fs_logger2("clone", dest); return 1; // file copied } return 0; }
170,099
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rng_egd_request_entropy(RngBackend *b, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngEgd *s = RNG_EGD(b); RngRequest *req; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); while (size > 0) { uint8_t header[2]; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); size -= len; } s->parent.requests = g_slist_append(s->parent.requests, req); } Commit Message: CWE ID: CWE-119
static void rng_egd_request_entropy(RngBackend *b, size_t size, static void rng_egd_request_entropy(RngBackend *b, RngRequest *req) { RngEgd *s = RNG_EGD(b); size_t size = req->size; while (size > 0) { uint8_t header[2]; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); size -= len; } }
165,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: static int nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; } Commit Message: nfc: Ensure presence of required attributes in the deactivate_target handler Check that the NFC_ATTR_TARGET_INDEX attributes (in addition to NFC_ATTR_DEVICE_INDEX) are provided by the netlink client prior to accessing them. This prevents potential unhandled NULL pointer dereference exceptions which can be triggered by malicious user-mode programs, if they omit one or both of these attributes. Signed-off-by: Young Xiao <92siuyang@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-476
static int nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX] || !info->attrs[NFC_ATTR_TARGET_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; }
169,645
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Encoder::EncodeFrameInternal(const VideoSource &video, const unsigned long frame_flags) { vpx_codec_err_t res; const vpx_image_t *img = video.img(); if (!encoder_.priv) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; cfg_.g_timebase = video.timebase(); cfg_.rc_twopass_stats_in = stats_->buf(); res = vpx_codec_enc_init(&encoder_, CodecInterface(), &cfg_, init_flags_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; res = vpx_codec_enc_config_set(&encoder_, &cfg_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } REGISTER_STATE_CHECK( res = vpx_codec_encode(&encoder_, video.img(), video.pts(), video.duration(), frame_flags, deadline_)); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void Encoder::EncodeFrameInternal(const VideoSource &video, const unsigned long frame_flags) { vpx_codec_err_t res; const vpx_image_t *img = video.img(); if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; res = vpx_codec_enc_config_set(&encoder_, &cfg_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } API_REGISTER_STATE_CHECK( res = vpx_codec_encode(&encoder_, img, video.pts(), video.duration(), frame_flags, deadline_)); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); }
174,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) { if (!agent_.get() || passkey_callback_.is_null()) return; passkey_callback_.Run(SUCCESS, passkey); passkey_callback_.Reset(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) { if (!pairing_context_.get()) return; pairing_context_->SetPasskey(passkey); }
171,239