instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool on_accept(private_stroke_socket_t *this, stream_t *stream) { stroke_msg_t *msg; uint16_t len; FILE *out; /* read length */ if (!stream->read_all(stream, &len, sizeof(len))) { if (errno != EWOULDBLOCK) { DBG1(DBG_CFG, "reading length of stroke message failed: %s", strerror(errno)); } return FALSE; } /* read message (we need an additional byte to terminate the buffer) */ msg = malloc(len + 1); DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno)); } Commit Message: CWE ID: CWE-787
static bool on_accept(private_stroke_socket_t *this, stream_t *stream) { stroke_msg_t *msg; uint16_t len; FILE *out; /* read length */ if (!stream->read_all(stream, &len, sizeof(len))) { if (errno != EWOULDBLOCK) { DBG1(DBG_CFG, "reading length of stroke message failed: %s", strerror(errno)); } return FALSE; } if (len < offsetof(stroke_msg_t, buffer)) { DBG1(DBG_CFG, "invalid stroke message length %d", len); return FALSE; } /* read message (we need an additional byte to terminate the buffer) */ msg = malloc(len + 1); DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno)); }
165,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ClipboardMessageFilter::OnWriteObjectsSync( const ui::Clipboard::ObjectMap& objects, base::SharedMemoryHandle bitmap_handle) { DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle)) << "Bad bitmap handle"; scoped_ptr<ui::Clipboard::ObjectMap> long_living_objects( new ui::Clipboard::ObjectMap(objects)); if (!ui::Clipboard::ReplaceSharedMemHandle( long_living_objects.get(), bitmap_handle, PeerHandle())) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WriteObjectsOnUIThread, base::Owned(long_living_objects.release()))); } Commit Message: Refactor ui::Clipboard::ObjectMap sanitization in ClipboardMsgFilter. BUG=352395 R=tony@chromium.org TBR=creis@chromium.org Review URL: https://codereview.chromium.org/200523004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@257164 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ClipboardMessageFilter::OnWriteObjectsSync( const ui::Clipboard::ObjectMap& objects, base::SharedMemoryHandle bitmap_handle) { DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle)) << "Bad bitmap handle"; scoped_ptr<ui::Clipboard::ObjectMap> long_living_objects( new ui::Clipboard::ObjectMap(objects)); SanitizeObjectMap(long_living_objects.get(), kAllowBitmap); if (!ui::Clipboard::ReplaceSharedMemHandle( long_living_objects.get(), bitmap_handle, PeerHandle())) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WriteObjectsOnUIThread, base::Owned(long_living_objects.release()))); }
171,692
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter) { u_char buf[OSPF_API_MAX_MSG_SIZE]; struct msg_register_event *emsg; int len; emsg = (struct msg_register_event *) buf; len = sizeof (struct msg_register_event) + filter->num_areas * sizeof (struct in_addr); emsg->filter.typemask = htons (filter->typemask); emsg->filter.origin = filter->origin; emsg->filter.num_areas = filter->num_areas; return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len); } Commit Message: CWE ID: CWE-119
new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter) { u_char buf[OSPF_API_MAX_MSG_SIZE]; struct msg_register_event *emsg; int len; emsg = (struct msg_register_event *) buf; len = sizeof (struct msg_register_event) + filter->num_areas * sizeof (struct in_addr); emsg->filter.typemask = htons (filter->typemask); emsg->filter.origin = filter->origin; emsg->filter.num_areas = filter->num_areas; if (len > sizeof (buf)) len = sizeof(buf); /* API broken - missing memcpy to fill data */ return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len); }
164,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_ERRORTYPE SoftMPEG4Encoder::releaseEncoder() { if (!mStarted) { return OMX_ErrorNone; } PVCleanUpVideoEncoder(mHandle); free(mInputFrameData); mInputFrameData = NULL; delete mEncParams; mEncParams = NULL; delete mHandle; mHandle = NULL; mStarted = false; return OMX_ErrorNone; } Commit Message: codecs: handle onReset() for a few encoders Test: Run PoC binaries Bug: 34749392 Bug: 34705519 Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd CWE ID:
OMX_ERRORTYPE SoftMPEG4Encoder::releaseEncoder() { if (mEncParams) { delete mEncParams; mEncParams = NULL; } if (mHandle) { delete mHandle; mHandle = NULL; } return OMX_ErrorNone; }
174,010
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PP_Bool StartPpapiProxy(PP_Instance instance) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNaClIPCProxy)) { ChannelHandleMap& map = g_channel_handle_map.Get(); ChannelHandleMap::iterator it = map.find(instance); if (it == map.end()) return PP_FALSE; IPC::ChannelHandle channel_handle = it->second; map.erase(it); webkit::ppapi::PluginInstance* plugin_instance = content::GetHostGlobals()->GetInstance(instance); if (!plugin_instance) return PP_FALSE; WebView* web_view = plugin_instance->container()->element().document().frame()->view(); RenderView* render_view = content::RenderView::FromWebView(web_view); webkit::ppapi::PluginModule* plugin_module = plugin_instance->module(); scoped_refptr<SyncMessageStatusReceiver> status_receiver(new SyncMessageStatusReceiver()); scoped_ptr<OutOfProcessProxy> out_of_process_proxy(new OutOfProcessProxy); if (out_of_process_proxy->Init( channel_handle, plugin_module->pp_module(), webkit::ppapi::PluginModule::GetLocalGetInterfaceFunc(), ppapi::Preferences(render_view->GetWebkitPreferences()), status_receiver.get())) { plugin_module->InitAsProxiedNaCl( out_of_process_proxy.PassAs<PluginDelegate::OutOfProcessProxy>(), instance); return PP_TRUE; } } return PP_FALSE; } 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
PP_Bool StartPpapiProxy(PP_Instance instance) { return PP_FALSE; }
170,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(size_t) (*p++ << 24); *quantum|=(size_t) (*p++ << 16); *quantum|=(size_t) (*p++ << 8); *quantum|=(size_t) (*p++ << 0); return(p); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(unsigned int) (*p++) << 24; *quantum|=(unsigned int) (*p++) << 16; *quantum|=(unsigned int) (*p++) << 8; *quantum|=(unsigned int) (*p++) << 0; return(p); }
169,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct usb_serial_port *wport; wport = serial->port[1]; tty_port_tty_set(&wport->port, tty); return usb_serial_generic_open(tty, port); } Commit Message: USB: serial: omninet: fix reference leaks at open This driver needlessly took another reference to the tty on open, a reference which was then never released on close. This lead to not just a leak of the tty, but also a driver reference leak that prevented the driver from being unloaded after a port had once been opened. Fixes: 4a90f09b20f4 ("tty: usb-serial krefs") Cc: stable <stable@vger.kernel.org> # 2.6.28 Signed-off-by: Johan Hovold <johan@kernel.org> CWE ID: CWE-404
static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port) { return usb_serial_generic_open(tty, port); }
168,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const { assert(m_pos >= m_element_start); pEntry = NULL; if (index < 0) return -1; //generic error if (m_entries_count < 0) return E_BUFFER_NOT_FULL; assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (index < m_entries_count) { pEntry = m_entries[index]; assert(pEntry); return 1; //found entry } if (m_element_size < 0) //we don't know cluster end yet return E_BUFFER_NOT_FULL; //underflow const long long element_stop = m_element_start + m_element_size; if (m_pos >= element_stop) return 0; //nothing left to parse return E_BUFFER_NOT_FULL; //underflow, since more remains to be parsed } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } unsigned char flags; status = pReader->Read(pos, 1, &flags);
174,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */
167,112
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } s += padlen + 3; (*psig) = s; /* return SUCCESS */ return NULL; } Commit Message: wo#7449 . verify padding contents for IKEv2 RSA sig check Special thanks to Sze Yiu Chau of Purdue University (schau@purdue.edu) who reported the issue. CWE ID: CWE-347
err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } /* signature starts after ASN wrapped padding [00,01,FF..FF,00] */ (*psig) = s + padlen + 3; /* verify padding contents */ { const u_char *p; size_t cnt_ffs = 0; for (p = s+2; p < s+padlen+2; p++) if (*p == 0xFF) cnt_ffs ++; if (cnt_ffs != padlen) return "4" "invalid Padding String"; } /* return SUCCESS */ return NULL; }
169,097
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AppCacheUpdateJob::OnDestructionImminent(AppCacheHost* host) { PendingMasters::iterator found = pending_master_entries_.find(host->pending_master_entry_url()); DCHECK(found != pending_master_entries_.end()); PendingHosts& hosts = found->second; PendingHosts::iterator it = std::find(hosts.begin(), hosts.end(), host); DCHECK(it != hosts.end()); hosts.erase(it); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheUpdateJob::OnDestructionImminent(AppCacheHost* host) { PendingMasters::iterator found = pending_master_entries_.find(host->pending_master_entry_url()); CHECK(found != pending_master_entries_.end()); PendingHosts& hosts = found->second; PendingHosts::iterator it = std::find(hosts.begin(), hosts.end(), host); CHECK(it != hosts.end()); hosts.erase(it); }
171,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static PHP_NAMED_FUNCTION(zif_zip_entry_read) { zval * zip_entry; zend_long len = 0; zip_read_rsrc * zr_rsrc; zend_string *buffer; int n = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &zip_entry, &len) == FAILURE) { return; } if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) { RETURN_FALSE; } if (len <= 0) { len = 1024; } if (zr_rsrc->zf) { buffer = zend_string_alloc(len, 0); n = zip_fread(zr_rsrc->zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n > 0) { ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } else { zend_string_free(buffer); RETURN_EMPTY_STRING() } } else { RETURN_FALSE; } } Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom* CWE ID: CWE-190
static PHP_NAMED_FUNCTION(zif_zip_entry_read) { zval * zip_entry; zend_long len = 0; zip_read_rsrc * zr_rsrc; zend_string *buffer; int n = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &zip_entry, &len) == FAILURE) { return; } if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) { RETURN_FALSE; } if (len <= 0) { len = 1024; } if (zr_rsrc->zf) { buffer = zend_string_safe_alloc(1, len, 0, 0); n = zip_fread(zr_rsrc->zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n > 0) { ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } else { zend_string_free(buffer); RETURN_EMPTY_STRING() } } else { RETURN_FALSE; } }
167,380
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MaybeStartInputMethodDaemon(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 && !value.string_list_value.empty()) { if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) { return; } const bool just_started = StartInputMethodDaemon(); if (!just_started) { return; } if (tentative_current_input_method_id_.empty()) { tentative_current_input_method_id_ = current_input_method_.id; } if (std::find(value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_) == value.string_list_value.end()) { tentative_current_input_method_id_.clear(); } } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeStartInputMethodDaemon(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 && !value.string_list_value.empty()) { if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) { return; } const bool just_started = StartInputMethodDaemon(); if (!just_started) { return; } if (tentative_current_input_method_id_.empty()) { tentative_current_input_method_id_ = current_input_method_.id; } if (std::find(value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_) == value.string_list_value.end()) { tentative_current_input_method_id_.clear(); } } }
170,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: header_put_le_int (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; } ; } /* header_put_le_int */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_le_int (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; } /* header_put_le_int */
170,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebRuntimeFeatures::EnableRequireCSSExtensionForFile(bool enable) { RuntimeEnabledFeatures::SetRequireCSSExtensionForFileEnabled(enable); } Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <mkwst@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Dave Tapuska <dtapuska@chromium.org> Cr-Commit-Position: refs/heads/master@{#607329} CWE ID: CWE-254
void WebRuntimeFeatures::EnableRequireCSSExtensionForFile(bool enable) {
173,187
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FrameSelection::MoveRangeSelection(const VisiblePosition& base_position, const VisiblePosition& extent_position, TextGranularity granularity) { SelectionInDOMTree new_selection = SelectionInDOMTree::Builder() .SetBaseAndExtentDeprecated(base_position.DeepEquivalent(), extent_position.DeepEquivalent()) .SetAffinity(base_position.Affinity()) .SetIsHandleVisible(IsHandleVisible()) .Build(); if (new_selection.IsNone()) return; const VisibleSelection& visible_selection = CreateVisibleSelectionWithGranularity(new_selection, granularity); if (visible_selection.IsNone()) return; SelectionInDOMTree::Builder builder; if (visible_selection.IsBaseFirst()) { builder.SetBaseAndExtent(visible_selection.Start(), visible_selection.End()); } else { builder.SetBaseAndExtent(visible_selection.End(), visible_selection.Start()); } builder.SetAffinity(visible_selection.Affinity()); builder.SetIsHandleVisible(IsHandleVisible()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetGranularity(granularity) .Build()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Reviewed-by: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
void FrameSelection::MoveRangeSelection(const VisiblePosition& base_position, const VisiblePosition& extent_position, TextGranularity granularity) { SelectionInDOMTree new_selection = SelectionInDOMTree::Builder() .SetBaseAndExtentDeprecated(base_position.DeepEquivalent(), extent_position.DeepEquivalent()) .SetAffinity(base_position.Affinity()) .Build(); if (new_selection.IsNone()) return; const VisibleSelection& visible_selection = CreateVisibleSelectionWithGranularity(new_selection, granularity); if (visible_selection.IsNone()) return; SelectionInDOMTree::Builder builder; if (visible_selection.IsBaseFirst()) { builder.SetBaseAndExtent(visible_selection.Start(), visible_selection.End()); } else { builder.SetBaseAndExtent(visible_selection.End(), visible_selection.Start()); } builder.SetAffinity(visible_selection.Affinity()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetGranularity(granularity) .SetShouldShowHandle(IsHandleVisible()) .Build()); }
171,757
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Cluster::CreateSimpleBlock( long long st, long long sz) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz); if (pEntry == NULL) return -1; //generic error SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry); const long status = p->Parse(); if (status == 0) { ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::CreateSimpleBlock(
174,260
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
168,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CoordinatorImpl::RegisterClientProcess( mojom::ClientProcessPtr client_process_ptr, mojom::ProcessType process_type) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); mojom::ClientProcess* client_process = client_process_ptr.get(); client_process_ptr.set_connection_error_handler( base::BindOnce(&CoordinatorImpl::UnregisterClientProcess, base::Unretained(this), client_process)); auto identity = GetClientIdentityForCurrentRequest(); auto client_info = std::make_unique<ClientInfo>( std::move(identity), std::move(client_process_ptr), process_type); auto iterator_and_inserted = clients_.emplace(client_process, std::move(client_info)); DCHECK(iterator_and_inserted.second); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <hjd@chromium.org> Commit-Queue: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::RegisterClientProcess( mojom::ClientProcessPtr client_process_ptr, mojom::ProcessType process_type) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); mojom::ClientProcess* client_process = client_process_ptr.get(); client_process_ptr.set_connection_error_handler( base::BindOnce(&CoordinatorImpl::UnregisterClientProcess, weak_ptr_factory_.GetWeakPtr(), client_process)); auto identity = GetClientIdentityForCurrentRequest(); auto client_info = std::make_unique<ClientInfo>( std::move(identity), std::move(client_process_ptr), process_type); auto iterator_and_inserted = clients_.emplace(client_process, std::move(client_info)); DCHECK(iterator_and_inserted.second); }
173,215
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: AXObjectInclusion AXLayoutObject::defaultObjectInclusion( IgnoredReasons* ignoredReasons) const { if (!m_layoutObject) { if (ignoredReasons) ignoredReasons->push_back(IgnoredReason(AXNotRendered)); return IgnoreObject; } if (m_layoutObject->style()->visibility() != EVisibility::kVisible) { if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false")) return DefaultBehavior; if (ignoredReasons) ignoredReasons->push_back(IgnoredReason(AXNotVisible)); return IgnoreObject; } return AXObject::defaultObjectInclusion(ignoredReasons); } 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
AXObjectInclusion AXLayoutObject::defaultObjectInclusion( IgnoredReasons* ignoredReasons) const { if (!m_layoutObject) { if (ignoredReasons) ignoredReasons->push_back(IgnoredReason(AXNotRendered)); return IgnoreObject; } if (m_layoutObject->style()->visibility() != EVisibility::kVisible) { if (equalIgnoringASCIICase(getAttribute(aria_hiddenAttr), "false")) return DefaultBehavior; if (ignoredReasons) ignoredReasons->push_back(IgnoredReason(AXNotVisible)); return IgnoreObject; } return AXObject::defaultObjectInclusion(ignoredReasons); }
171,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void net_checksum_calculate(uint8_t *data, int length) { int hlen, plen, proto, csum_offset; uint16_t csum; if ((data[14] & 0xf0) != 0x40) return; /* not IPv4 */ hlen = (data[14] & 0x0f) * 4; csum_offset = 16; break; case PROTO_UDP: csum_offset = 6; break; default: return; } Commit Message: CWE ID: CWE-119
void net_checksum_calculate(uint8_t *data, int length) { int hlen, plen, proto, csum_offset; uint16_t csum; /* Ensure data has complete L2 & L3 headers. */ if (length < 14 + 20) { return; } if ((data[14] & 0xf0) != 0x40) return; /* not IPv4 */ hlen = (data[14] & 0x0f) * 4; csum_offset = 16; break; case PROTO_UDP: csum_offset = 6; break; default: return; }
165,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ND_TCHECK2(p[0], 2); extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_pppoe_atm]")); return l2info.header_len; }
167,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int decode_zbuf(AVBPrint *bp, const uint8_t *data, const uint8_t *data_end) { z_stream zstream; unsigned char *buf; unsigned buf_size; int ret; zstream.zalloc = ff_png_zalloc; zstream.zfree = ff_png_zfree; zstream.opaque = NULL; if (inflateInit(&zstream) != Z_OK) return AVERROR_EXTERNAL; zstream.next_in = (unsigned char *)data; zstream.avail_in = data_end - data; av_bprint_init(bp, 0, -1); while (zstream.avail_in > 0) { av_bprint_get_buffer(bp, 1, &buf, &buf_size); if (!buf_size) { ret = AVERROR(ENOMEM); goto fail; } zstream.next_out = buf; zstream.avail_out = buf_size; ret = inflate(&zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { ret = AVERROR_EXTERNAL; goto fail; } bp->len += zstream.next_out - buf; if (ret == Z_STREAM_END) break; } inflateEnd(&zstream); bp->str[bp->len] = 0; return 0; fail: inflateEnd(&zstream); av_bprint_finalize(bp, NULL); return ret; } Commit Message: avcodec/pngdec: Fix off by 1 size in decode_zbuf() Fixes out of array access Fixes: 444/fuzz-2-ffmpeg_VIDEO_AV_CODEC_ID_PNG_fuzzer Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-787
static int decode_zbuf(AVBPrint *bp, const uint8_t *data, const uint8_t *data_end) { z_stream zstream; unsigned char *buf; unsigned buf_size; int ret; zstream.zalloc = ff_png_zalloc; zstream.zfree = ff_png_zfree; zstream.opaque = NULL; if (inflateInit(&zstream) != Z_OK) return AVERROR_EXTERNAL; zstream.next_in = (unsigned char *)data; zstream.avail_in = data_end - data; av_bprint_init(bp, 0, -1); while (zstream.avail_in > 0) { av_bprint_get_buffer(bp, 2, &buf, &buf_size); if (buf_size < 2) { ret = AVERROR(ENOMEM); goto fail; } zstream.next_out = buf; zstream.avail_out = buf_size - 1; ret = inflate(&zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { ret = AVERROR_EXTERNAL; goto fail; } bp->len += zstream.next_out - buf; if (ret == Z_STREAM_END) break; } inflateEnd(&zstream); bp->str[bp->len] = 0; return 0; fail: inflateEnd(&zstream); av_bprint_finalize(bp, NULL); return ret; }
168,245
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1553 CWE ID: CWE-125
ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
169,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command) { CATEnum cat_enum; char *sep; cat_enum.dest = dest; cat_enum.import_flags = import_flags; cat_enum.force_fps = force_fps; cat_enum.frames_per_sample = frames_per_sample; cat_enum.tmp_dir = tmp_dir; cat_enum.force_cat = force_cat; cat_enum.align_timelines = align_timelines; cat_enum.allow_add_in_command = allow_add_in_command; strcpy(cat_enum.szPath, fileName); sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR); if (!sep) sep = strrchr(cat_enum.szPath, '/'); if (!sep) { strcpy(cat_enum.szPath, "."); strcpy(cat_enum.szRad1, fileName); } else { strcpy(cat_enum.szRad1, sep+1); sep[0] = 0; } sep = strchr(cat_enum.szRad1, '*'); strcpy(cat_enum.szRad2, sep+1); sep[0] = 0; sep = strchr(cat_enum.szRad2, '%'); if (!sep) sep = strchr(cat_enum.szRad2, '#'); if (!sep) sep = strchr(cat_enum.szRad2, ':'); strcpy(cat_enum.szOpt, ""); if (sep) { strcpy(cat_enum.szOpt, sep); sep[0] = 0; } return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL); } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command) { CATEnum cat_enum; char *sep; cat_enum.dest = dest; cat_enum.import_flags = import_flags; cat_enum.force_fps = force_fps; cat_enum.frames_per_sample = frames_per_sample; cat_enum.tmp_dir = tmp_dir; cat_enum.force_cat = force_cat; cat_enum.align_timelines = align_timelines; cat_enum.allow_add_in_command = allow_add_in_command; if (strlen(fileName) >= sizeof(cat_enum.szPath)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", fileName)); return GF_NOT_SUPPORTED; } strcpy(cat_enum.szPath, fileName); sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR); if (!sep) sep = strrchr(cat_enum.szPath, '/'); if (!sep) { strcpy(cat_enum.szPath, "."); if (strlen(fileName) >= sizeof(cat_enum.szRad1)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", fileName)); return GF_NOT_SUPPORTED; } strcpy(cat_enum.szRad1, fileName); } else { if (strlen(sep + 1) >= sizeof(cat_enum.szRad1)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", (sep + 1))); return GF_NOT_SUPPORTED; } strcpy(cat_enum.szRad1, sep+1); sep[0] = 0; } sep = strchr(cat_enum.szRad1, '*'); if (strlen(sep + 1) >= sizeof(cat_enum.szRad2)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("File name %s is too long.\n", (sep + 1))); return GF_NOT_SUPPORTED; } strcpy(cat_enum.szRad2, sep+1); sep[0] = 0; sep = strchr(cat_enum.szRad2, '%'); if (!sep) sep = strchr(cat_enum.szRad2, '#'); if (!sep) sep = strchr(cat_enum.szRad2, ':'); strcpy(cat_enum.szOpt, ""); if (sep) { if (strlen(sep) >= sizeof(cat_enum.szOpt)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Invalid option: %s.\n", sep)); return GF_NOT_SUPPORTED; } strcpy(cat_enum.szOpt, sep); sep[0] = 0; } return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL); }
169,788
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inI1outR1: calculated ke+nonce, sending R1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inI1outR1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_globals(); passert(GLOBALS_ARE_RESET()); } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20
static void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inI1outR1: calculated ke+nonce, sending R1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inI1outR1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_globals(); }
166,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void nalm_dump(FILE * trace, char *data, u32 data_size) { GF_BitStream *bs; Bool rle, large_size; u32 entry_count; if (!data) { fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n"); fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n"); fprintf(trace, "</NALUMap>\n"); return; } bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ); gf_bs_read_int(bs, 6); large_size = gf_bs_read_int(bs, 1); rle = gf_bs_read_int(bs, 1); entry_count = gf_bs_read_int(bs, large_size ? 16 : 8); fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size); while (entry_count) { u32 ID; fprintf(trace, "<NALUMapEntry "); if (rle) { u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8); fprintf(trace, "NALU_startNumber=\"%d\" ", start_num); } ID = gf_bs_read_u16(bs); fprintf(trace, "groupID=\"%d\"/>\n", ID); entry_count--; } gf_bs_del(bs); fprintf(trace, "</NALUMap>\n"); return; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
static void nalm_dump(FILE * trace, char *data, u32 data_size) { GF_BitStream *bs; Bool rle, large_size; u32 entry_count; if (!data) { fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n"); fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n"); fprintf(trace, "</NALUMap>\n"); return; } bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ); gf_bs_read_int(bs, 6); large_size = gf_bs_read_int(bs, 1); rle = gf_bs_read_int(bs, 1); entry_count = gf_bs_read_int(bs, large_size ? 16 : 8); fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size); while (entry_count) { u32 ID; fprintf(trace, "<NALUMapEntry "); if (rle) { u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8); fprintf(trace, "NALU_startNumber=\"%d\" ", start_num); } ID = gf_bs_read_u16(bs); fprintf(trace, "groupID=\"%d\"/>\n", ID); entry_count--; } gf_bs_del(bs); fprintf(trace, "</NALUMap>\n"); return; }
169,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel, int gpu_host_id) { surface_route_id_ = params_in_pixel.route_id; if (params_in_pixel.protection_state_id && params_in_pixel.protection_state_id != protection_state_id_) { DCHECK(!current_surface_); if (!params_in_pixel.skip_ack) InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } if (ShouldFastACK(params_in_pixel.surface_handle)) { if (!params_in_pixel.skip_ack) InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } current_surface_ = params_in_pixel.surface_handle; if (!params_in_pixel.skip_ack) released_front_lock_ = NULL; UpdateExternalTexture(); ui::Compositor* compositor = GetCompositor(); if (!compositor) { if (!params_in_pixel.skip_ack) InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, true, NULL); } else { DCHECK(image_transport_clients_.find(params_in_pixel.surface_handle) != image_transport_clients_.end()); gfx::Size surface_size_in_pixel = image_transport_clients_[params_in_pixel.surface_handle]->size(); gfx::Size surface_size = ConvertSizeToDIP(this, surface_size_in_pixel); window_->SchedulePaintInRect(gfx::Rect(surface_size)); if (!params_in_pixel.skip_ack) { can_lock_compositor_ = NO_PENDING_COMMIT; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK, params_in_pixel.route_id, gpu_host_id, true)); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped( bool RenderWidgetHostViewAura::SwapBuffersPrepare( const gfx::Rect& surface_rect, const gfx::Rect& damage_rect, BufferPresentedParams* params) { DCHECK(params->surface_handle); DCHECK(!params->texture_to_produce); if (last_swapped_surface_size_ != surface_rect.size()) { // The surface could have shrunk since we skipped an update, in which // case we can expect a full update. DLOG_IF(ERROR, damage_rect != surface_rect) << "Expected full damage rect"; skipped_damage_.setEmpty(); last_swapped_surface_size_ = surface_rect.size(); } if (ShouldSkipFrame(surface_rect.size())) { skipped_damage_.op(RectToSkIRect(damage_rect), SkRegion::kUnion_Op); InsertSyncPointAndACK(*params); return false; } DCHECK(!current_surface_ || image_transport_clients_.find(current_surface_) != image_transport_clients_.end()); if (current_surface_) params->texture_to_produce = image_transport_clients_[current_surface_]; std::swap(current_surface_, params->surface_handle); DCHECK(image_transport_clients_.find(current_surface_) != image_transport_clients_.end()); image_transport_clients_[current_surface_]->Consume(surface_rect.size()); released_front_lock_ = NULL; UpdateExternalTexture(); return true; } void RenderWidgetHostViewAura::SwapBuffersCompleted( const BufferPresentedParams& params) { ui::Compositor* compositor = GetCompositor(); if (!compositor) { InsertSyncPointAndACK(params); } else { // Add sending an ACK to the list of things to do OnCompositingDidCommit can_lock_compositor_ = NO_PENDING_COMMIT; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK, params)); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } } void RenderWidgetHostViewAura::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params_in_pixel, int gpu_host_id) { const gfx::Rect surface_rect = gfx::Rect(gfx::Point(), params_in_pixel.size); BufferPresentedParams ack_params( params_in_pixel.route_id, gpu_host_id, params_in_pixel.surface_handle); if (!SwapBuffersPrepare(surface_rect, surface_rect, &ack_params)) return; previous_damage_.setRect(RectToSkIRect(surface_rect)); skipped_damage_.setEmpty(); ui::Compositor* compositor = GetCompositor(); if (compositor) { gfx::Size surface_size = ConvertSizeToDIP(this, params_in_pixel.size); window_->SchedulePaintInRect(gfx::Rect(surface_size)); } SwapBuffersCompleted(ack_params); }
171,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_scale_16_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; } 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_scale_16_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; }
173,645
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BluetoothDeviceChooserController::OnBluetoothChooserEvent( BluetoothChooser::Event event, const std::string& device_address) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(chooser_.get()); switch (event) { case BluetoothChooser::Event::RESCAN: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); device_ids_.clear(); PopulateConnectedDevices(); DCHECK(chooser_); StartDeviceDiscovery(); return; case BluetoothChooser::Event::DENIED_PERMISSION: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult:: CHOOSER_NOT_SHOWN_USER_DENIED_PERMISSION_TO_SCAN); break; case BluetoothChooser::Event::CANCELLED: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_OVERVIEW_HELP: DVLOG(1) << "Overview Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_ADAPTER_OFF_HELP: DVLOG(1) << "Adapter Off Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_NEED_LOCATION_HELP: DVLOG(1) << "Need Location Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SELECTED: RecordNumOfDevices(options_->accept_all_devices, device_ids_.size()); PostSuccessCallback(device_address); break; } chooser_.reset(); } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <chrishtr@chromium.org> Reviewed-by: Giovanni Ortuño Urquidi <ortuno@chromium.org> Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
void BluetoothDeviceChooserController::OnBluetoothChooserEvent( BluetoothChooser::Event event, const std::string& device_address) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(chooser_.get()); switch (event) { case BluetoothChooser::Event::RESCAN: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); device_ids_.clear(); PopulateConnectedDevices(); DCHECK(chooser_); StartDeviceDiscovery(); return; case BluetoothChooser::Event::DENIED_PERMISSION: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback( WebBluetoothResult::CHOOSER_NOT_SHOWN_USER_DENIED_PERMISSION_TO_SCAN); break; case BluetoothChooser::Event::CANCELLED: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_OVERVIEW_HELP: DVLOG(1) << "Overview Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_ADAPTER_OFF_HELP: DVLOG(1) << "Adapter Off Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_NEED_LOCATION_HELP: DVLOG(1) << "Need Location Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SELECTED: RecordNumOfDevices(options_->accept_all_devices, device_ids_.size()); PostSuccessCallback(device_address); break; } chooser_.reset(); }
172,444
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Cues::LoadCuePoint() const { const long long stop = m_start + m_size; if (m_pos >= stop) return false; //nothing else to do Init(); IMkvReader* const pReader = m_pSegment->m_pReader; while (m_pos < stop) { const long long idpos = m_pos; long len; const long long id = ReadUInt(pReader, m_pos, len); assert(id >= 0); //TODO assert((m_pos + len) <= stop); m_pos += len; //consume ID const long long size = ReadUInt(pReader, m_pos, len); assert(size >= 0); assert((m_pos + len) <= stop); m_pos += len; //consume Size field assert((m_pos + size) <= stop); if (id != 0x3B) //CuePoint ID { m_pos += size; //consume payload assert(m_pos <= stop); continue; } assert(m_preload_count > 0); CuePoint* const pCP = m_cue_points[m_count]; assert(pCP); assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) return false; pCP->Load(pReader); ++m_count; --m_preload_count; m_pos += size; //consume payload assert(m_pos <= stop); return true; //yes, we loaded a cue point } return false; //no, we did not load a cue point } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Cues::LoadCuePoint() const
174,397
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: alloc_limit_assert (char *fn_name, size_t size) { if (alloc_limit && size > alloc_limit) { alloc_limit_failure (fn_name, size); exit (-1); } } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
alloc_limit_assert (char *fn_name, size_t size) { if (alloc_limit && size > alloc_limit) { alloc_limit_failure (fn_name, size); exit (-1); } }
168,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) { EXPECT_TRUE(fb != NULL); ExternalFrameBuffer *const ext_fb = reinterpret_cast<ExternalFrameBuffer*>(fb->priv); EXPECT_TRUE(ext_fb != NULL); EXPECT_EQ(1, ext_fb->in_use); ext_fb->in_use = 0; return 0; } 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 ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) { if (fb == NULL) { EXPECT_TRUE(fb != NULL); return -1; } ExternalFrameBuffer *const ext_fb = reinterpret_cast<ExternalFrameBuffer*>(fb->priv); if (ext_fb == NULL) { EXPECT_TRUE(ext_fb != NULL); return -1; } EXPECT_EQ(1, ext_fb->in_use); ext_fb->in_use = 0; return 0; }
174,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int createFromTiffRgba(TIFF * tif, gdImagePtr im) { int a; int x, y; int alphaBlendingFlag = 0; int color; int width = im->sx; int height = im->sy; uint32 *buffer; uint32 rgba; /* switch off colour merging on target gd image just while we write out * content - we want to preserve the alpha data until the user chooses * what to do with the image */ alphaBlendingFlag = im->alphaBlendingFlag; gdImageAlphaBlending(im, 0); buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height); if (!buffer) { return GD_FAILURE; } TIFFReadRGBAImage(tif, width, height, buffer, 0); for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { /* if it doesn't already exist, allocate a new colour, * else use existing one */ rgba = buffer[(y * width + x)]; a = (0xff - TIFFGetA(rgba)) / 2; color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a); /* set pixel colour to this colour */ gdImageSetPixel(im, x, height - y - 1, color); } } gdFree(buffer); /* now reset colour merge for alpha blending routines */ gdImageAlphaBlending(im, alphaBlendingFlag); return GD_SUCCESS; } Commit Message: Fix invalid read in gdImageCreateFromTiffPtr() tiff_invalid_read.tiff is corrupt, and causes an invalid read in gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case, dynamicGetbuf() is called with a negative dp->pos, but also positive buffer overflows have to be handled, in which case 0 has to be returned (cf. commit 75e29a9). Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create the image, because the return value of TIFFReadRGBAImage() is not checked. We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails. This issue had been reported by Ibrahim El-Sayed to security@libgd.org. CVE-2016-6911 CWE ID: CWE-125
static int createFromTiffRgba(TIFF * tif, gdImagePtr im) { int a; int x, y; int alphaBlendingFlag = 0; int color; int width = im->sx; int height = im->sy; uint32 *buffer; uint32 rgba; int success; /* switch off colour merging on target gd image just while we write out * content - we want to preserve the alpha data until the user chooses * what to do with the image */ alphaBlendingFlag = im->alphaBlendingFlag; gdImageAlphaBlending(im, 0); buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height); if (!buffer) { return GD_FAILURE; } success = TIFFReadRGBAImage(tif, width, height, buffer, 1); if (success) { for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { /* if it doesn't already exist, allocate a new colour, * else use existing one */ rgba = buffer[(y * width + x)]; a = (0xff - TIFFGetA(rgba)) / 2; color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a); /* set pixel colour to this colour */ gdImageSetPixel(im, x, height - y - 1, color); } } } gdFree(buffer); /* now reset colour merge for alpha blending routines */ gdImageAlphaBlending(im, alphaBlendingFlag); return success; }
168,822
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: TestJavaScriptDialogManager() : is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {} Commit Message: If a page shows a popup, end fullscreen. This was implemented in Blink r159834, but it is susceptible to a popup/fullscreen race. This CL reverts that implementation and re-implements it in WebContents. BUG=752003 TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f Reviewed-on: https://chromium-review.googlesource.com/606987 Commit-Queue: Avi Drissman <avi@chromium.org> Reviewed-by: Charlie Reis <creis@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Cr-Commit-Position: refs/heads/master@{#498171} CWE ID: CWE-20
TestJavaScriptDialogManager() TestWCDelegateForDialogsAndFullscreen() : is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
172,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BrowserEventRouter::ExtensionActionExecuted( Profile* profile, const ExtensionAction& extension_action, WebContents* web_contents) { const char* event_name = NULL; switch (extension_action.action_type()) { case Extension::ActionInfo::TYPE_BROWSER: event_name = "browserAction.onClicked"; break; case Extension::ActionInfo::TYPE_PAGE: event_name = "pageAction.onClicked"; break; case Extension::ActionInfo::TYPE_SCRIPT_BADGE: event_name = "scriptBadge.onClicked"; break; case Extension::ActionInfo::TYPE_SYSTEM_INDICATOR: break; } if (event_name) { scoped_ptr<ListValue> args(new ListValue()); DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue( web_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS); args->Append(tab_value); DispatchEventToExtension(profile, extension_action.extension_id(), event_name, args.Pass(), EventRouter::USER_GESTURE_ENABLED); } } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void BrowserEventRouter::ExtensionActionExecuted( Profile* profile, const ExtensionAction& extension_action, WebContents* web_contents) { const char* event_name = NULL; switch (extension_action.action_type()) { case Extension::ActionInfo::TYPE_BROWSER: event_name = "browserAction.onClicked"; break; case Extension::ActionInfo::TYPE_PAGE: event_name = "pageAction.onClicked"; break; case Extension::ActionInfo::TYPE_SCRIPT_BADGE: event_name = "scriptBadge.onClicked"; break; case Extension::ActionInfo::TYPE_SYSTEM_INDICATOR: break; } if (event_name) { scoped_ptr<ListValue> args(new ListValue()); DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue( web_contents); args->Append(tab_value); DispatchEventToExtension(profile, extension_action.extension_id(), event_name, args.Pass(), EventRouter::USER_GESTURE_ENABLED); } }
171,450
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_MostVisitedURLsObserver_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); } Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer. BUG=677672 Review-Url: https://codereview.chromium.org/2697543002 Cr-Commit-Position: refs/heads/master@{#449958} CWE ID: CWE-17
void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_Observer_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); }
172,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::unique_ptr<content::BluetoothChooser> Browser::RunBluetoothChooser( content::RenderFrameHost* frame, const content::BluetoothChooser::EventHandler& event_handler) { std::unique_ptr<BluetoothChooserController> bluetooth_chooser_controller( new BluetoothChooserController(frame, event_handler)); std::unique_ptr<BluetoothChooserDesktop> bluetooth_chooser_desktop( new BluetoothChooserDesktop(bluetooth_chooser_controller.get())); std::unique_ptr<ChooserBubbleDelegate> chooser_bubble_delegate( new ChooserBubbleDelegate(frame, std::move(bluetooth_chooser_controller))); Browser* browser = chrome::FindBrowserWithWebContents( WebContents::FromRenderFrameHost(frame)); BubbleReference bubble_reference = browser->GetBubbleManager()->ShowBubble( std::move(chooser_bubble_delegate)); return std::move(bluetooth_chooser_desktop); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <reillyg@chromium.org> Reviewed-by: Michael Wasserman <msw@chromium.org> Reviewed-by: Jeffrey Yasskin <jyasskin@chromium.org> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362
std::unique_ptr<content::BluetoothChooser> Browser::RunBluetoothChooser( content::RenderFrameHost* frame, const content::BluetoothChooser::EventHandler& event_handler) { std::unique_ptr<BluetoothChooserController> bluetooth_chooser_controller( new BluetoothChooserController(frame, event_handler)); std::unique_ptr<BluetoothChooserDesktop> bluetooth_chooser_desktop( new BluetoothChooserDesktop(bluetooth_chooser_controller.get())); std::unique_ptr<ChooserBubbleDelegate> chooser_bubble_delegate( new ChooserBubbleDelegate(frame, std::move(bluetooth_chooser_controller))); Browser* browser = chrome::FindBrowserWithWebContents( WebContents::FromRenderFrameHost(frame)); BubbleReference bubble_reference = browser->GetBubbleManager()->ShowBubble( std::move(chooser_bubble_delegate)); bluetooth_chooser_desktop->set_bubble(std::move(bubble_reference)); return std::move(bluetooth_chooser_desktop); }
173,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen > 0) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); return union_desc; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL; } Commit Message: Input: ims-psu - check if CDC union descriptor is sane Before trying to use CDC union descriptor, try to validate whether that it is sane by checking that intf->altsetting->extra is big enough and that descriptor bLength is not too big and not too small. Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com> CWE ID: CWE-125
ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen >= sizeof(*union_desc)) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bLength > buflen) { dev_err(&intf->dev, "Too large descriptor\n"); return NULL; } if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); if (union_desc->bLength >= sizeof(*union_desc)) return union_desc; dev_err(&intf->dev, "Union descriptor to short (%d vs %zd\n)", union_desc->bLength, sizeof(*union_desc)); return NULL; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL; }
167,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SMB2_sess_establish_session(struct SMB2_sess_data *sess_data) { int rc = 0; struct cifs_ses *ses = sess_data->ses; mutex_lock(&ses->server->srv_mutex); if (ses->server->sign && ses->server->ops->generate_signingkey) { rc = ses->server->ops->generate_signingkey(ses); kfree(ses->auth_key.response); ses->auth_key.response = NULL; if (rc) { cifs_dbg(FYI, "SMB3 session key generation failed\n"); mutex_unlock(&ses->server->srv_mutex); goto keygen_exit; } } if (!ses->server->session_estab) { ses->server->sequence_number = 0x2; ses->server->session_estab = true; } mutex_unlock(&ses->server->srv_mutex); cifs_dbg(FYI, "SMB2/3 session established successfully\n"); spin_lock(&GlobalMid_Lock); ses->status = CifsGood; ses->need_reconnect = false; spin_unlock(&GlobalMid_Lock); keygen_exit: if (!ses->server->sign) { kfree(ses->auth_key.response); ses->auth_key.response = NULL; } return rc; } Commit Message: CIFS: Enable encryption during session setup phase In order to allow encryption on SMB connection we need to exchange a session key and generate encryption and decryption keys. Signed-off-by: Pavel Shilovsky <pshilov@microsoft.com> CWE ID: CWE-476
SMB2_sess_establish_session(struct SMB2_sess_data *sess_data) { int rc = 0; struct cifs_ses *ses = sess_data->ses; mutex_lock(&ses->server->srv_mutex); if (ses->server->ops->generate_signingkey) { rc = ses->server->ops->generate_signingkey(ses); if (rc) { cifs_dbg(FYI, "SMB3 session key generation failed\n"); mutex_unlock(&ses->server->srv_mutex); return rc; } } if (!ses->server->session_estab) { ses->server->sequence_number = 0x2; ses->server->session_estab = true; } mutex_unlock(&ses->server->srv_mutex); cifs_dbg(FYI, "SMB2/3 session established successfully\n"); spin_lock(&GlobalMid_Lock); ses->status = CifsGood; ses->need_reconnect = false; spin_unlock(&GlobalMid_Lock); return rc; }
169,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MediaElementAudioSourceNode::OnCurrentSrcChanged(const KURL& current_src) { GetMediaElementAudioSourceHandler().OnCurrentSrcChanged(current_src); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <rtoy@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Hongchan Choi <hongchan@chromium.org> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceNode::OnCurrentSrcChanged(const KURL& current_src) {
173,146
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_get_objs (MyObject *obj, GPtrArray **objs, GError **error) { *objs = g_ptr_array_new (); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject")); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject2")); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_get_objs (MyObject *obj, GPtrArray **objs, GError **error)
165,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderLayerCompositor::frameViewDidScroll() { FrameView* frameView = m_renderView->frameView(); IntPoint scrollPosition = frameView->scrollPosition(); if (!m_scrollLayer) return; bool scrollingCoordinatorHandlesOffset = false; if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) { if (Settings* settings = m_renderView->document().settings()) { if (isMainFrame() || settings->compositedScrollingForFramesEnabled()) scrollingCoordinatorHandlesOffset = scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView); } } if (scrollingCoordinatorHandlesOffset) m_scrollLayer->setPosition(-frameView->minimumScrollPosition()); else m_scrollLayer->setPosition(-scrollPosition); blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground", ScrolledMainFrameBucket, AcceleratedFixedRootBackgroundHistogramMax); if (!m_renderView->rootBackgroundIsEntirelyFixed()) return; blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground", !!fixedRootBackgroundLayer() ? ScrolledMainFrameWithAcceleratedFixedRootBackground : ScrolledMainFrameWithUnacceleratedFixedRootBackground, AcceleratedFixedRootBackgroundHistogramMax); } Commit Message: Disable some more query compositingState asserts. This gets the tests passing again on Mac. See the bug for the stacktrace. A future patch will need to actually fix the incorrect reading of compositingState. BUG=343179 Review URL: https://codereview.chromium.org/162153002 git-svn-id: svn://svn.chromium.org/blink/trunk@167069 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
void RenderLayerCompositor::frameViewDidScroll() { FrameView* frameView = m_renderView->frameView(); IntPoint scrollPosition = frameView->scrollPosition(); if (!m_scrollLayer) return; bool scrollingCoordinatorHandlesOffset = false; if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) { if (Settings* settings = m_renderView->document().settings()) { if (isMainFrame() || settings->compositedScrollingForFramesEnabled()) scrollingCoordinatorHandlesOffset = scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView); } } if (scrollingCoordinatorHandlesOffset) m_scrollLayer->setPosition(-frameView->minimumScrollPosition()); else m_scrollLayer->setPosition(-scrollPosition); blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground", ScrolledMainFrameBucket, AcceleratedFixedRootBackgroundHistogramMax); if (!m_renderView->rootBackgroundIsEntirelyFixed()) return; // FIXME: fixedRootBackgroundLayer calls compositingState, which is not necessarily up to date here on mac. // See crbug.com/343179. DisableCompositingQueryAsserts disabler; blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground", !!fixedRootBackgroundLayer() ? ScrolledMainFrameWithAcceleratedFixedRootBackground : ScrolledMainFrameWithUnacceleratedFixedRootBackground, AcceleratedFixedRootBackgroundHistogramMax); }
171,342
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: write_header( FT_Error error_code ) { FT_Face face; const char* basename; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) PanicZ( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%s')", basename ); break; default: sprintf( status.header_buffer, "File `%s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); sprintf( status.header_buffer, "at %g points, angle = %d", status.ptsize/64.0, status.angle ); grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); } Commit Message: CWE ID: CWE-119
write_header( FT_Error error_code ) { FT_Face face; const char* basename; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) PanicZ( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%.50s %.50s (file `%.100s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')", basename ); break; default: sprintf( status.header_buffer, "File `%.100s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); sprintf( status.header_buffer, "at %g points, angle = %d", status.ptsize/64.0, status.angle ); grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); }
165,000
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Wait() { message_loop_runner_->Run(); message_loop_runner_ = new MessageLoopRunner; } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <nasko@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
void Wait() { run_loop_->Run(); run_loop_ = std::make_unique<base::RunLoop>(); }
172,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: uint32 ResourceTracker::GetLiveObjectsForInstance( PP_Instance instance) const { InstanceMap::const_iterator found = instance_map_.find(instance); if (found == instance_map_.end()) return 0; return static_cast<uint32>(found->second->resources.size() + found->second->object_vars.size()); } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
uint32 ResourceTracker::GetLiveObjectsForInstance( PP_Instance instance) const { InstanceMap::const_iterator found = instance_map_.find(instance); if (found == instance_map_.end()) return 0; return static_cast<uint32>(found->second->ref_resources.size() + found->second->object_vars.size()); }
170,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FileReaderLoader::OnCalculatedSize(uint64_t total_size, uint64_t expected_content_size) { OnStartLoading(expected_content_size); if (expected_content_size == 0) { received_all_data_ = true; return; } if (IsSyncLoad()) { OnDataPipeReadable(MOJO_RESULT_OK); } else { handle_watcher_.Watch( consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE, WTF::BindRepeating(&FileReaderLoader::OnDataPipeReadable, WTF::Unretained(this))); } } Commit Message: Fix use-after-free in FileReaderLoader. Anything that calls out to client_ can cause FileReaderLoader to be destroyed, so make sure to check for that situation. Bug: 835639 Change-Id: I57533d41b7118c06da17abec28bbf301e1f50646 Reviewed-on: https://chromium-review.googlesource.com/1024450 Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Commit-Queue: Daniel Murphy <dmurph@chromium.org> Reviewed-by: Daniel Murphy <dmurph@chromium.org> Cr-Commit-Position: refs/heads/master@{#552807} CWE ID: CWE-416
void FileReaderLoader::OnCalculatedSize(uint64_t total_size, uint64_t expected_content_size) { auto weak_this = weak_factory_.GetWeakPtr(); OnStartLoading(expected_content_size); // OnStartLoading calls out to our client, which could delete |this|, so bail // out if that happened. if (!weak_this) return; if (expected_content_size == 0) { received_all_data_ = true; return; } if (IsSyncLoad()) { OnDataPipeReadable(MOJO_RESULT_OK); } else { handle_watcher_.Watch( consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE, WTF::BindRepeating(&FileReaderLoader::OnDataPipeReadable, WTF::Unretained(this))); } }
173,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MagickExport unsigned char *DetachBlob(BlobInfo *blob_info) { unsigned char *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; return(data); } Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43 CWE ID: CWE-416
MagickExport unsigned char *DetachBlob(BlobInfo *blob_info) { unsigned char *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; return(data); }
169,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void SetUp() { full_itxfm_ = GET_PARAM(0); partial_itxfm_ = GET_PARAM(1); tx_size_ = GET_PARAM(2); last_nonzero_ = GET_PARAM(3); } 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 SetUp() { ftxfm_ = GET_PARAM(0); full_itxfm_ = GET_PARAM(1); partial_itxfm_ = GET_PARAM(2); tx_size_ = GET_PARAM(3); last_nonzero_ = GET_PARAM(4); }
174,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fdct8x8_ref; } 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 SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fdct8x8_ref; bit_depth_ = GET_PARAM(3); mask_ = (1 << bit_depth_) - 1; }
174,562
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfs41_callback_svc(void *vrqstp) { struct svc_rqst *rqstp = vrqstp; struct svc_serv *serv = rqstp->rq_server; struct rpc_rqst *req; int error; DEFINE_WAIT(wq); set_freezable(); while (!kthread_should_stop()) { if (try_to_freeze()) continue; prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE); spin_lock_bh(&serv->sv_cb_lock); if (!list_empty(&serv->sv_cb_list)) { req = list_first_entry(&serv->sv_cb_list, struct rpc_rqst, rq_bc_list); list_del(&req->rq_bc_list); spin_unlock_bh(&serv->sv_cb_lock); finish_wait(&serv->sv_cb_waitq, &wq); dprintk("Invoking bc_svc_process()\n"); error = bc_svc_process(serv, req, rqstp); dprintk("bc_svc_process() returned w/ error code= %d\n", error); } else { spin_unlock_bh(&serv->sv_cb_lock); schedule(); finish_wait(&serv->sv_cb_waitq, &wq); } flush_signals(current); } return 0; } 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
nfs41_callback_svc(void *vrqstp) { struct svc_rqst *rqstp = vrqstp; struct svc_serv *serv = rqstp->rq_server; struct rpc_rqst *req; int error; DEFINE_WAIT(wq); set_freezable(); while (!kthread_freezable_should_stop(NULL)) { if (signal_pending(current)) flush_signals(current); prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE); spin_lock_bh(&serv->sv_cb_lock); if (!list_empty(&serv->sv_cb_list)) { req = list_first_entry(&serv->sv_cb_list, struct rpc_rqst, rq_bc_list); list_del(&req->rq_bc_list); spin_unlock_bh(&serv->sv_cb_lock); finish_wait(&serv->sv_cb_waitq, &wq); dprintk("Invoking bc_svc_process()\n"); error = bc_svc_process(serv, req, rqstp); dprintk("bc_svc_process() returned w/ error code= %d\n", error); } else { spin_unlock_bh(&serv->sv_cb_lock); if (!kthread_should_stop()) schedule(); finish_wait(&serv->sv_cb_waitq, &wq); } } svc_exit_thread(rqstp); module_put_and_exit(0); return 0; }
168,137
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc) { xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; __GLXconfig *config; __GLXscreen *pGlxScreen; int err; if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) return err; if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err)) config, pGlxScreen, req->isDirect); } Commit Message: CWE ID: CWE-20
int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc) { ClientPtr client = cl->client; xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; __GLXconfig *config; __GLXscreen *pGlxScreen; int err; REQUEST_SIZE_MATCH(xGLXCreateContextReq); if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) return err; if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err)) config, pGlxScreen, req->isDirect); }
165,271
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case SEQ_DISPLAY_EXT_ID: impeg2d_dec_seq_disp_ext(ps_dec); break; case SEQ_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_peek_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; } 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
IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error && (ps_stream->u4_offset < ps_stream->u4_max_offset)) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case SEQ_DISPLAY_EXT_ID: impeg2d_dec_seq_disp_ext(ps_dec); break; case SEQ_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_peek_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; }
173,946
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static Frame* ReuseExistingWindow(LocalFrame& active_frame, LocalFrame& lookup_frame, const AtomicString& frame_name, NavigationPolicy policy, const KURL& destination_url) { if (!frame_name.IsEmpty() && !EqualIgnoringASCIICase(frame_name, "_blank") && policy == kNavigationPolicyIgnore) { if (Frame* frame = lookup_frame.FindFrameForNavigation( frame_name, active_frame, destination_url)) { if (!EqualIgnoringASCIICase(frame_name, "_self")) { if (Page* page = frame->GetPage()) { if (page == active_frame.GetPage()) page->GetFocusController().SetFocusedFrame(frame); else page->GetChromeClient().Focus(); } } return frame; } } return nullptr; } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <nasko@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
static Frame* ReuseExistingWindow(LocalFrame& active_frame, LocalFrame& lookup_frame, const AtomicString& frame_name, NavigationPolicy policy, const KURL& destination_url) { if (!frame_name.IsEmpty() && !EqualIgnoringASCIICase(frame_name, "_blank") && policy == kNavigationPolicyIgnore) { if (Frame* frame = lookup_frame.FindFrameForNavigation( frame_name, active_frame, destination_url)) { if (!EqualIgnoringASCIICase(frame_name, "_self")) { if (Page* page = frame->GetPage()) { if (page == active_frame.GetPage()) page->GetFocusController().SetFocusedFrame(frame); else page->GetChromeClient().Focus(&active_frame); } } return frame; } } return nullptr; }
172,725
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ProcXSendExtensionEvent(ClientPtr client) { int ret; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); if (!((EXTENSION_EVENT_BASE <= first->u.u.type) && (first->u.u.type < lastEvent))) { client->errorValue = first->u.u.type; return BadValue; } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; } Commit Message: CWE ID: CWE-119
ProcXSendExtensionEvent(ClientPtr client) { int ret, i; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); for (i = 0; i < stuff->num_events; i++) { if (!((EXTENSION_EVENT_BASE <= first[i].u.u.type) && (first[i].u.u.type < lastEvent))) { client->errorValue = first[i].u.u.type; return BadValue; } } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; }
164,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() { if (texture_holder_->IsSkiaTextureHolder()) return; texture_holder_ = std::make_unique<SkiaTextureHolder>(std::move(texture_holder_)); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::CreateImageFromMailboxIfNeeded() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (texture_holder_->IsSkiaTextureHolder()) return; texture_holder_ = std::make_unique<SkiaTextureHolder>(std::move(texture_holder_)); }
172,592
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: omx_vdec::~omx_vdec() { m_pmem_info = NULL; struct v4l2_decoder_cmd dec; DEBUG_PRINT_HIGH("In OMX vdec Destructor"); if (m_pipe_in) close(m_pipe_in); if (m_pipe_out) close(m_pipe_out); m_pipe_in = -1; m_pipe_out = -1; DEBUG_PRINT_HIGH("Waiting on OMX Msg Thread exit"); if (msg_thread_created) pthread_join(msg_thread_id,NULL); DEBUG_PRINT_HIGH("Waiting on OMX Async Thread exit"); dec.cmd = V4L2_DEC_CMD_STOP; if (drv_ctx.video_driver_fd >=0 ) { if (ioctl(drv_ctx.video_driver_fd, VIDIOC_DECODER_CMD, &dec)) DEBUG_PRINT_ERROR("STOP Command failed"); } if (async_thread_created) pthread_join(async_thread_id,NULL); unsubscribe_to_events(drv_ctx.video_driver_fd); close(drv_ctx.video_driver_fd); pthread_mutex_destroy(&m_lock); pthread_mutex_destroy(&c_lock); sem_destroy(&m_cmd_lock); if (perf_flag) { DEBUG_PRINT_HIGH("--> TOTAL PROCESSING TIME"); dec_time.end(); } DEBUG_PRINT_INFO("Exit OMX vdec Destructor: fd=%d",drv_ctx.video_driver_fd); } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e CWE ID:
omx_vdec::~omx_vdec() { m_pmem_info = NULL; struct v4l2_decoder_cmd dec; DEBUG_PRINT_HIGH("In OMX vdec Destructor"); if (m_pipe_in) close(m_pipe_in); if (m_pipe_out) close(m_pipe_out); m_pipe_in = -1; m_pipe_out = -1; DEBUG_PRINT_HIGH("Waiting on OMX Msg Thread exit"); if (msg_thread_created) pthread_join(msg_thread_id,NULL); DEBUG_PRINT_HIGH("Waiting on OMX Async Thread exit"); dec.cmd = V4L2_DEC_CMD_STOP; if (drv_ctx.video_driver_fd >=0 ) { if (ioctl(drv_ctx.video_driver_fd, VIDIOC_DECODER_CMD, &dec)) DEBUG_PRINT_ERROR("STOP Command failed"); } if (async_thread_created) pthread_join(async_thread_id,NULL); unsubscribe_to_events(drv_ctx.video_driver_fd); close(drv_ctx.video_driver_fd); pthread_mutex_destroy(&m_lock); pthread_mutex_destroy(&c_lock); pthread_mutex_destroy(&buf_lock); sem_destroy(&m_cmd_lock); if (perf_flag) { DEBUG_PRINT_HIGH("--> TOTAL PROCESSING TIME"); dec_time.end(); } DEBUG_PRINT_INFO("Exit OMX vdec Destructor: fd=%d",drv_ctx.video_driver_fd); }
173,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { return dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-362
static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { int err; struct inode *inode = file_inode(vma->vm_file); sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); err = __dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(inode->i_sb); return err; } /* * Handle write fault for VM_MIXEDMAP mappings. Similarly to ext4_dax_mkwrite() * handler we check for races agaist truncate. Note that since we cycle through * i_mmap_sem, we are sure that also any hole punching that began before we * were called is finished by now and so if it included part of the file we * are working on, our pte will get unmapped and the check for pte_same() in * wp_pfn_shared() fails. Thus fault gets retried and things work out as * desired. */ static int ext4_dax_pfn_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; int ret = VM_FAULT_NOPAGE; loff_t size; sb_start_pagefault(sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); size = (i_size_read(inode) + PAGE_SIZE - 1) >> PAGE_SHIFT; if (vmf->pgoff >= size) ret = VM_FAULT_SIGBUS; up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(sb); return ret; }
167,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long mkvparser::ParseElementHeader( IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume length of size if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long mkvparser::ParseElementHeader( long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size // pos now designates payload if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; // success }
174,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual bool IsURLAcceptableForWebUI( BrowserContext* browser_context, const GURL& url) const { return HasWebUIScheme(url); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual bool IsURLAcceptableForWebUI( BrowserContext* browser_context, const GURL& url) const { return content::GetContentClient()->HasWebUIScheme(url); } }; class TabContentsTestClient : public TestContentClient { public: TabContentsTestClient() { } virtual bool HasWebUIScheme(const GURL& url) const OVERRIDE { return url.SchemeIs("tabcontentstest"); }
171,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); }
167,030
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void IOHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_host_ = process_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 IOHandler::SetRenderer(RenderProcessHost* process_host, void IOHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { RenderProcessHost* process_host = RenderProcessHost::FromID(process_host_id); if (process_host) { browser_context_ = process_host->GetBrowserContext(); storage_partition_ = process_host->GetStoragePartition(); } else { browser_context_ = nullptr; storage_partition_ = nullptr; } }
172,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: __be32 ipv6_select_ident(struct net *net, const struct in6_addr *daddr, const struct in6_addr *saddr) { static u32 ip6_idents_hashrnd __read_mostly; u32 id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr); return htonl(id); } Commit Message: inet: switch IP ID generator to siphash According to Amit Klein and Benny Pinkas, IP ID generation is too weak and might be used by attackers. Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix()) having 64bit key and Jenkins hash is risky. It is time to switch to siphash and its 128bit keys. Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
__be32 ipv6_select_ident(struct net *net, const struct in6_addr *daddr, const struct in6_addr *saddr) { u32 id; id = __ipv6_select_ident(net, daddr, saddr); return htonl(id); }
169,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: V4L2JpegEncodeAccelerator::JobRecord::JobRecord( scoped_refptr<VideoFrame> input_frame, scoped_refptr<VideoFrame> output_frame, int quality, int32_t task_id, BitstreamBuffer* exif_buffer) : input_frame(input_frame), output_frame(output_frame), quality(quality), task_id(task_id), output_shm(base::SharedMemoryHandle(), 0, true), // dummy exif_shm(nullptr) { if (exif_buffer) { exif_shm.reset(new UnalignedSharedMemory(exif_buffer->TakeRegion(), exif_buffer->size(), false)); exif_offset = exif_buffer->offset(); } } Commit Message: media: remove base::SharedMemoryHandle usage in v4l2 encoder This replaces a use of the legacy UnalignedSharedMemory ctor taking a SharedMemoryHandle with the current ctor taking a PlatformSharedMemoryRegion. Bug: 849207 Change-Id: Iea24ebdcd941cf2fa97e19cf2aeac1a18f9773d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1697602 Commit-Queue: Matthew Cary (CET) <mattcary@chromium.org> Reviewed-by: Ricky Liang <jcliang@chromium.org> Cr-Commit-Position: refs/heads/master@{#681740} CWE ID: CWE-20
V4L2JpegEncodeAccelerator::JobRecord::JobRecord( scoped_refptr<VideoFrame> input_frame, scoped_refptr<VideoFrame> output_frame, int quality, int32_t task_id, BitstreamBuffer* exif_buffer) : input_frame(input_frame), output_frame(output_frame), quality(quality), task_id(task_id), output_shm(base::subtle::PlatformSharedMemoryRegion(), 0, true), // dummy exif_shm(nullptr) { if (exif_buffer) { exif_shm.reset(new UnalignedSharedMemory(exif_buffer->TakeRegion(), exif_buffer->size(), false)); exif_offset = exif_buffer->offset(); } }
172,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame) { const uint8_t* as_pack; int freq, stype, smpls, quant, i, ach; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack || !c->sys) { /* No audio ? */ c->ach = 0; return 0; } smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ /* note: ach counts PAIRS of channels (i.e. stereo channels) */ ach = ((int[4]){ 1, 0, 2, 4})[stype]; if (ach == 1 && quant && freq == 2) if (!c->ast[i]) break; avpriv_set_pts_info(c->ast[i], 64, 1, 30000); c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE; av_init_packet(&c->audio_pkt[i]); c->audio_pkt[i].size = 0; c->audio_pkt[i].data = c->audio_buf[i]; c->audio_pkt[i].stream_index = c->ast[i]->index; c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY; } Commit Message: CWE ID: CWE-20
static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame) { const uint8_t* as_pack; int freq, stype, smpls, quant, i, ach; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack || !c->sys) { /* No audio ? */ c->ach = 0; return 0; } smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (stype > 3) { av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype); c->ach = 0; return 0; } /* note: ach counts PAIRS of channels (i.e. stereo channels) */ ach = ((int[4]){ 1, 0, 2, 4})[stype]; if (ach == 1 && quant && freq == 2) if (!c->ast[i]) break; avpriv_set_pts_info(c->ast[i], 64, 1, 30000); c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE; av_init_packet(&c->audio_pkt[i]); c->audio_pkt[i].size = 0; c->audio_pkt[i].data = c->audio_buf[i]; c->audio_pkt[i].stream_index = c->ast[i]->index; c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY; }
165,243
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { u8 perm_addr[MAX_ADDR_LEN]; if (!netdev->dcbnl_ops->getpermhwaddr) return -EOPNOTSUPP; netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr); return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr); } Commit Message: dcbnl: fix various netlink info leaks The dcb netlink interface leaks stack memory in various places: * perm_addr[] buffer is only filled at max with 12 of the 32 bytes but copied completely, * no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand, so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes for ieee_pfc structs, etc., * the same is true for CEE -- no in-kernel driver fills the whole struct, Prevent all of the above stack info leaks by properly initializing the buffers/structures involved. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static int dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { u8 perm_addr[MAX_ADDR_LEN]; if (!netdev->dcbnl_ops->getpermhwaddr) return -EOPNOTSUPP; memset(perm_addr, 0, sizeof(perm_addr)); netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr); return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr); }
166,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: String AXNodeObject::textFromDescendants(AXObjectSet& visited, bool recursive) const { if (!canHaveChildren() && recursive) return String(); StringBuilder accumulatedText; AXObject* previous = nullptr; AXObjectVector children; HeapVector<Member<AXObject>> ownedChildren; computeAriaOwnsChildren(ownedChildren); for (AXObject* obj = rawFirstChild(); obj; obj = obj->rawNextSibling()) { if (!axObjectCache().isAriaOwned(obj)) children.push_back(obj); } for (const auto& ownedChild : ownedChildren) children.push_back(ownedChild); for (AXObject* child : children) { if (equalIgnoringCase(child->getAttribute(aria_hiddenAttr), "true")) continue; if (previous && accumulatedText.length() && !isHTMLSpace(accumulatedText[accumulatedText.length() - 1])) { if (!isInSameNonInlineBlockFlow(child->getLayoutObject(), previous->getLayoutObject())) accumulatedText.append(' '); } String result; if (child->isPresentational()) result = child->textFromDescendants(visited, true); else result = recursiveTextAlternative(*child, false, visited); accumulatedText.append(result); previous = child; } return accumulatedText.toString(); } 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
String AXNodeObject::textFromDescendants(AXObjectSet& visited, bool recursive) const { if (!canHaveChildren() && recursive) return String(); StringBuilder accumulatedText; AXObject* previous = nullptr; AXObjectVector children; HeapVector<Member<AXObject>> ownedChildren; computeAriaOwnsChildren(ownedChildren); for (AXObject* obj = rawFirstChild(); obj; obj = obj->rawNextSibling()) { if (!axObjectCache().isAriaOwned(obj)) children.push_back(obj); } for (const auto& ownedChild : ownedChildren) children.push_back(ownedChild); for (AXObject* child : children) { if (equalIgnoringASCIICase(child->getAttribute(aria_hiddenAttr), "true")) continue; if (previous && accumulatedText.length() && !isHTMLSpace(accumulatedText[accumulatedText.length() - 1])) { if (!isInSameNonInlineBlockFlow(child->getLayoutObject(), previous->getLayoutObject())) accumulatedText.append(' '); } String result; if (child->isPresentational()) result = child->textFromDescendants(visited, true); else result = recursiveTextAlternative(*child, false, visited); accumulatedText.append(result); previous = child; } return accumulatedText.toString(); }
171,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int tipc_nl_compat_link_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { struct nlattr *link[TIPC_NLA_LINK_MAX + 1]; struct tipc_link_info link_info; int err; if (!attrs[TIPC_NLA_LINK]) return -EINVAL; err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK], NULL); if (err) return err; link_info.dest = nla_get_flag(link[TIPC_NLA_LINK_DEST]); link_info.up = htonl(nla_get_flag(link[TIPC_NLA_LINK_UP])); strcpy(link_info.str, nla_data(link[TIPC_NLA_LINK_NAME])); return tipc_add_tlv(msg->rep, TIPC_TLV_LINK_INFO, &link_info, sizeof(link_info)); } Commit Message: tipc: fix an infoleak in tipc_nl_compat_link_dump link_info.str is a char array of size 60. Memory after the NULL byte is not initialized. Sending the whole object out can cause a leak. Signed-off-by: Kangjie Lu <kjlu@gatech.edu> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static int tipc_nl_compat_link_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { struct nlattr *link[TIPC_NLA_LINK_MAX + 1]; struct tipc_link_info link_info; int err; if (!attrs[TIPC_NLA_LINK]) return -EINVAL; err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK], NULL); if (err) return err; link_info.dest = nla_get_flag(link[TIPC_NLA_LINK_DEST]); link_info.up = htonl(nla_get_flag(link[TIPC_NLA_LINK_UP])); nla_strlcpy(link_info.str, nla_data(link[TIPC_NLA_LINK_NAME]), TIPC_MAX_LINK_NAME); return tipc_add_tlv(msg->rep, TIPC_TLV_LINK_INFO, &link_info, sizeof(link_info)); }
167,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedBytes>* data) { print_preview_data_service()->GetDataEntry(preview_ui_addr_str_, index, data); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedBytes>* data) { print_preview_data_service()->GetDataEntry(id_, index, data); }
170,834
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { RFlagsAtOffset *flags = NULL; RFlagsAtOffset key; key.off = off; if (dir >= 0) { flags = r_skiplist_get_geq (f->by_off, &key); } else { flags = r_skiplist_get_leq (f->by_off, &key); } if (dir == 0 && flags && flags->off != off) { return NULL; } return flags; } Commit Message: Fix crash in wasm disassembler CWE ID: CWE-125
static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { RFlagsAtOffset *flags = NULL; RFlagsAtOffset key; key.off = off; if (dir >= 0) { flags = r_skiplist_get_geq (f->by_off, &key); } else { flags = r_skiplist_get_leq (f->by_off, &key); } if (dir == 0 && flags && flags->off != off) { return NULL; } return flags; }
167,723
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MagickExport void CatchException(ExceptionInfo *exception) { register const ExceptionInfo *p; assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (exception->exceptions == (void *) NULL) return; LockSemaphoreInfo(exception->semaphore); ResetLinkedListIterator((LinkedListInfo *) exception->exceptions); p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *) exception->exceptions); while (p != (const ExceptionInfo *) NULL) { if ((p->severity >= WarningException) && (p->severity < ErrorException)) MagickWarning(p->severity,p->reason,p->description); if ((p->severity >= ErrorException) && (p->severity < FatalErrorException)) MagickError(p->severity,p->reason,p->description); if (p->severity >= FatalErrorException) MagickFatalError(p->severity,p->reason,p->description); p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *) exception->exceptions); } UnlockSemaphoreInfo(exception->semaphore); ClearMagickException(exception); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119
MagickExport void CatchException(ExceptionInfo *exception) { register const ExceptionInfo *p; ssize_t i; assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (exception->exceptions == (void *) NULL) return; LockSemaphoreInfo(exception->semaphore); ResetLinkedListIterator((LinkedListInfo *) exception->exceptions); p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *) exception->exceptions); for (i=0; p != (const ExceptionInfo *) NULL; i++) { if (p->severity >= FatalErrorException) MagickFatalError(p->severity,p->reason,p->description); if (i < MaxExceptions) { if ((p->severity >= ErrorException) && (p->severity < FatalErrorException)) MagickError(p->severity,p->reason,p->description); if ((p->severity >= WarningException) && (p->severity < ErrorException)) MagickWarning(p->severity,p->reason,p->description); } else if (i == MaxExceptions) MagickError(ResourceLimitError,"too many exceptions", "exception processing suspended"); p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *) exception->exceptions); } UnlockSemaphoreInfo(exception->semaphore); ClearMagickException(exception); }
168,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bt_status_t btif_storage_add_bonded_device(bt_bdaddr_t *remote_bd_addr, LINK_KEY link_key, uint8_t key_type, uint8_t pin_length) { bdstr_t bdstr; bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr)); int ret = btif_config_set_int(bdstr, "LinkKeyType", (int)key_type); ret &= btif_config_set_int(bdstr, "PinLength", (int)pin_length); ret &= btif_config_set_bin(bdstr, "LinkKey", link_key, sizeof(LINK_KEY)); /* write bonded info immediately */ btif_config_flush(); return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
bt_status_t btif_storage_add_bonded_device(bt_bdaddr_t *remote_bd_addr, LINK_KEY link_key, uint8_t key_type, uint8_t pin_length) { bdstr_t bdstr; bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr)); int ret = btif_config_set_int(bdstr, "LinkKeyType", (int)key_type); ret &= btif_config_set_int(bdstr, "PinLength", (int)pin_length); ret &= btif_config_set_bin(bdstr, "LinkKey", link_key, sizeof(LINK_KEY)); if (is_restricted_mode()) { BTIF_TRACE_WARNING("%s: '%s' pairing will be removed if unrestricted", __func__, bdstr); btif_config_set_int(bdstr, "Restricted", 1); } /* write bonded info immediately */ btif_config_flush(); return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; }
173,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; TIFFSwabArrayOfShort(wp, wc); horAcc16(tif, cp0, cc); } 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
swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc) { uint16* wp = (uint16*) cp0; tmsize_t wc = cc / 2; TIFFSwabArrayOfShort(wp, wc); return horAcc16(tif, cp0, cc); }
166,888
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void StorageHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_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 StorageHandler::SetRenderer(RenderProcessHost* process_host, void StorageHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { RenderProcessHost* process = RenderProcessHost::FromID(process_host_id); storage_partition_ = process ? process->GetStoragePartition() : nullptr; }
172,774
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline bool shouldSetStrutOnBlock(const LayoutBlockFlow& block, const RootInlineBox& lineBox, LayoutUnit lineLogicalOffset, int lineIndex, LayoutUnit remainingLogicalHeight) { bool wantsStrutOnBlock = false; if (!block.style()->hasAutoOrphans() && block.style()->orphans() >= lineIndex) { wantsStrutOnBlock = true; } else if (lineBox == block.firstRootBox() && lineLogicalOffset == block.borderAndPaddingBefore()) { LayoutUnit lineHeight = lineBox.lineBottomWithLeading() - lineBox.lineTopWithLeading(); LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, lineLogicalOffset); LayoutUnit pageLogicalHeightAtNewOffset = block.pageLogicalHeightForOffset(lineLogicalOffset + remainingLogicalHeight); if (totalLogicalHeight < pageLogicalHeightAtNewOffset) wantsStrutOnBlock = true; } if (!wantsStrutOnBlock || block.isOutOfFlowPositioned()) return false; LayoutBlock* containingBlock = block.containingBlock(); return containingBlock && containingBlock->isLayoutBlockFlow(); } Commit Message: Consistently check if a block can handle pagination strut propagation. https://codereview.chromium.org/1360753002 got it right for inline child layout, but did nothing for block child layout. BUG=329421 R=jchaffraix@chromium.org,leviw@chromium.org Review URL: https://codereview.chromium.org/1387553002 Cr-Commit-Position: refs/heads/master@{#352429} CWE ID: CWE-22
static inline bool shouldSetStrutOnBlock(const LayoutBlockFlow& block, const RootInlineBox& lineBox, LayoutUnit lineLogicalOffset, int lineIndex, LayoutUnit remainingLogicalHeight) { bool wantsStrutOnBlock = false; if (!block.style()->hasAutoOrphans() && block.style()->orphans() >= lineIndex) { wantsStrutOnBlock = true; } else if (lineBox == block.firstRootBox() && lineLogicalOffset == block.borderAndPaddingBefore()) { LayoutUnit lineHeight = lineBox.lineBottomWithLeading() - lineBox.lineTopWithLeading(); LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, lineLogicalOffset); LayoutUnit pageLogicalHeightAtNewOffset = block.pageLogicalHeightForOffset(lineLogicalOffset + remainingLogicalHeight); if (totalLogicalHeight < pageLogicalHeightAtNewOffset) wantsStrutOnBlock = true; } return wantsStrutOnBlock && block.allowsPaginationStrut(); }
171,694
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: psf_close (SF_PRIVATE *psf) { uint32_t k ; int error = 0 ; if (psf->codec_close) { error = psf->codec_close (psf) ; /* To prevent it being called in psf->container_close(). */ psf->codec_close = NULL ; } ; if (psf->container_close) error = psf->container_close (psf) ; error = psf_fclose (psf) ; psf_close_rsrc (psf) ; /* For an ISO C compliant implementation it is ok to free a NULL pointer. */ free (psf->container_data) ; free (psf->codec_data) ; free (psf->interleave) ; free (psf->dither) ; free (psf->peak_info) ; free (psf->broadcast_16k) ; free (psf->loop_info) ; free (psf->instrument) ; free (psf->cues) ; free (psf->channel_map) ; free (psf->format_desc) ; free (psf->strings.storage) ; if (psf->wchunks.chunks) for (k = 0 ; k < psf->wchunks.used ; k++) free (psf->wchunks.chunks [k].data) ; free (psf->rchunks.chunks) ; free (psf->wchunks.chunks) ; free (psf->iterator) ; free (psf->cart_16k) ; memset (psf, 0, sizeof (SF_PRIVATE)) ; free (psf) ; return error ; } /* psf_close */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
psf_close (SF_PRIVATE *psf) { uint32_t k ; int error = 0 ; if (psf->codec_close) { error = psf->codec_close (psf) ; /* To prevent it being called in psf->container_close(). */ psf->codec_close = NULL ; } ; if (psf->container_close) error = psf->container_close (psf) ; error = psf_fclose (psf) ; psf_close_rsrc (psf) ; /* For an ISO C compliant implementation it is ok to free a NULL pointer. */ free (psf->header.ptr) ; free (psf->container_data) ; free (psf->codec_data) ; free (psf->interleave) ; free (psf->dither) ; free (psf->peak_info) ; free (psf->broadcast_16k) ; free (psf->loop_info) ; free (psf->instrument) ; free (psf->cues) ; free (psf->channel_map) ; free (psf->format_desc) ; free (psf->strings.storage) ; if (psf->wchunks.chunks) for (k = 0 ; k < psf->wchunks.used ; k++) free (psf->wchunks.chunks [k].data) ; free (psf->rchunks.chunks) ; free (psf->wchunks.chunks) ; free (psf->iterator) ; free (psf->cart_16k) ; memset (psf, 0, sizeof (SF_PRIVATE)) ; free (psf) ; return error ; } /* psf_close */
170,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ResourceTracker::UnrefResource(PP_Resource res) { DLOG_IF(ERROR, !CheckIdType(res, PP_ID_TYPE_RESOURCE)) << res << " is not a PP_Resource."; ResourceMap::iterator i = live_resources_.find(res); if (i != live_resources_.end()) { if (!--i->second.second) { Resource* to_release = i->second.first; PP_Instance instance = to_release->instance()->pp_instance(); to_release->LastPluginRefWasDeleted(false); instance_map_[instance]->resources.erase(res); live_resources_.erase(i); } return true; } else { return false; } } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ResourceTracker::UnrefResource(PP_Resource res) { DLOG_IF(ERROR, !CheckIdType(res, PP_ID_TYPE_RESOURCE)) << res << " is not a PP_Resource."; ResourceMap::iterator i = live_resources_.find(res); if (i != live_resources_.end()) { if (!--i->second.second) { Resource* to_release = i->second.first; PP_Instance instance = to_release->instance()->pp_instance(); to_release->LastPluginRefWasDeleted(); instance_map_[instance]->ref_resources.erase(res); live_resources_.erase(i); } return true; } else { return false; } }
170,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if (that->bit_depth == 16) { that->sample_depth = that->bit_depth = 8; if (that->red_sBIT > 8) that->red_sBIT = 8; if (that->green_sBIT > 8) that->green_sBIT = 8; if (that->blue_sBIT > 8) that->blue_sBIT = 8; if (that->alpha_sBIT > 8) that->alpha_sBIT = 8; /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this * configuration option is set. From 1.5.4 the flag is never set and the * 'scale' API (above) must be used. */ # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER >= 10504 # error PNG_READ_ACCURATE_SCALE should not be set # endif /* The strip 16 algorithm drops the low 8 bits rather than calculating * 1/257, so we need to adjust the permitted errors appropriately: * Notice that this is only relevant prior to the addition of the * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!) */ { PNG_CONST double d = (255-128.5)/65535; that->rede += d; that->greene += d; that->bluee += d; that->alphae += d; } # endif } this->next->mod(this->next, that, pp, display); } 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_strip_16_mod(PNG_CONST image_transform *this, image_transform_png_set_strip_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth == 16) { that->sample_depth = that->bit_depth = 8; if (that->red_sBIT > 8) that->red_sBIT = 8; if (that->green_sBIT > 8) that->green_sBIT = 8; if (that->blue_sBIT > 8) that->blue_sBIT = 8; if (that->alpha_sBIT > 8) that->alpha_sBIT = 8; /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this * configuration option is set. From 1.5.4 the flag is never set and the * 'scale' API (above) must be used. */ # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER >= 10504 # error PNG_READ_ACCURATE_SCALE should not be set # endif /* The strip 16 algorithm drops the low 8 bits rather than calculating * 1/257, so we need to adjust the permitted errors appropriately: * Notice that this is only relevant prior to the addition of the * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!) */ { const double d = (255-128.5)/65535; that->rede += d; that->greene += d; that->bluee += d; that->alphae += d; } # endif } this->next->mod(this->next, that, pp, display); }
173,649
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void UserSelectionScreen::OnBeforeUserRemoved(const AccountId& account_id) { for (user_manager::UserList::iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->GetAccountId() == account_id) { users_.erase(it); break; } } } 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::OnBeforeUserRemoved(const AccountId& account_id) { for (auto it = users_.cbegin(); it != users_.cend(); ++it) { if ((*it)->GetAccountId() == account_id) { users_.erase(it); break; } } }
172,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void EntrySync::remove(ExceptionState& exceptionState) const { RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create(); m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void EntrySync::remove(ExceptionState& exceptionState) const { VoidSyncCallbackHelper* helper = VoidSyncCallbackHelper::create(); m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); }
171,423
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); unlink(src); } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); fs_logger2("clone", dest); unlink(src); }
170,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Strgrow(Str x) { char *old = x->ptr; int newlen; newlen = x->length * 6 / 5; if (newlen == x->length) newlen += 2; x->ptr = GC_MALLOC_ATOMIC(newlen); x->area_size = newlen; bcopy((void *)old, (void *)x->ptr, x->length); GC_free(old); } Commit Message: Merge pull request #27 from kcwu/fix-strgrow Fix potential heap buffer corruption due to Strgrow CWE ID: CWE-119
Strgrow(Str x) { char *old = x->ptr; int newlen; newlen = x->area_size * 6 / 5; if (newlen == x->area_size) newlen += 2; x->ptr = GC_MALLOC_ATOMIC(newlen); x->area_size = newlen; bcopy((void *)old, (void *)x->ptr, x->length); GC_free(old); }
166,892
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DisconnectWindowLinux::Show(remoting::ChromotingHost* host, const std::string& username) { 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::Show(remoting::ChromotingHost* host, const std::string& username) { host_ = host; CreateWindow(); gtk_label_set_text(GTK_LABEL(user_label_), username.c_str()); gtk_window_present(GTK_WINDOW(disconnect_window_)); }
170,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: FileMetricsProviderTest() : create_large_files_(GetParam()), task_runner_(new base::TestSimpleTaskRunner()), thread_task_runner_handle_(task_runner_), statistics_recorder_( base::StatisticsRecorder::CreateTemporaryForTesting()), prefs_(new TestingPrefServiceSimple) { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName); FileMetricsProvider::SetTaskRunnerForTesting(task_runner_); base::GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <bcwhite@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
FileMetricsProviderTest() : create_large_files_(GetParam()), task_runner_(new base::TestSimpleTaskRunner()), thread_task_runner_handle_(task_runner_), statistics_recorder_( base::StatisticsRecorder::CreateTemporaryForTesting()), prefs_(new TestingPrefServiceSimple) { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName); FileMetricsProvider::SetTaskRunnerForTesting(task_runner_); }
172,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } Commit Message: Added check for out of bounds read (https://github.com/ImageMagick/ImageMagick/issues/108). CWE ID: CWE-125
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } }
168,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool net_tx_pkt_do_sw_fragmentation(struct NetTxPkt *pkt, NetClientState *nc) { struct iovec fragment[NET_MAX_FRAG_SG_LIST]; size_t fragment_len = 0; bool more_frags = false; /* some pointers for shorter code */ void *l2_iov_base, *l3_iov_base; size_t l2_iov_len, l3_iov_len; int src_idx = NET_TX_PKT_PL_START_FRAG, dst_idx; size_t src_offset = 0; size_t fragment_offset = 0; l2_iov_base = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base; l2_iov_len = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len; l3_iov_base = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base; l3_iov_len = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len; /* Copy headers */ fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_base = l2_iov_base; fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_len = l2_iov_len; fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_base = l3_iov_base; fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_len = l3_iov_len; /* Put as much data as possible and send */ do { fragment_len = net_tx_pkt_fetch_fragment(pkt, &src_idx, &src_offset, fragment, &dst_idx); more_frags = (fragment_offset + fragment_len < pkt->payload_len); eth_setup_ip4_fragmentation(l2_iov_base, l2_iov_len, l3_iov_base, l3_iov_len, fragment_len, fragment_offset, more_frags); eth_fix_ip4_checksum(l3_iov_base, l3_iov_len); net_tx_pkt_sendv(pkt, nc, fragment, dst_idx); fragment_offset += fragment_len; } while (more_frags); return true; } Commit Message: CWE ID: CWE-399
static bool net_tx_pkt_do_sw_fragmentation(struct NetTxPkt *pkt, NetClientState *nc) { struct iovec fragment[NET_MAX_FRAG_SG_LIST]; size_t fragment_len = 0; bool more_frags = false; /* some pointers for shorter code */ void *l2_iov_base, *l3_iov_base; size_t l2_iov_len, l3_iov_len; int src_idx = NET_TX_PKT_PL_START_FRAG, dst_idx; size_t src_offset = 0; size_t fragment_offset = 0; l2_iov_base = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base; l2_iov_len = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len; l3_iov_base = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base; l3_iov_len = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len; /* Copy headers */ fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_base = l2_iov_base; fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_len = l2_iov_len; fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_base = l3_iov_base; fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_len = l3_iov_len; /* Put as much data as possible and send */ do { fragment_len = net_tx_pkt_fetch_fragment(pkt, &src_idx, &src_offset, fragment, &dst_idx); more_frags = (fragment_offset + fragment_len < pkt->payload_len); eth_setup_ip4_fragmentation(l2_iov_base, l2_iov_len, l3_iov_base, l3_iov_len, fragment_len, fragment_offset, more_frags); eth_fix_ip4_checksum(l3_iov_base, l3_iov_len); net_tx_pkt_sendv(pkt, nc, fragment, dst_idx); fragment_offset += fragment_len; } while (fragment_len && more_frags); return true; }
164,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: _rsvg_io_get_file_path (const gchar * filename, const gchar * base_uri) { gchar *absolute_filename; if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) { absolute_filename = g_strdup (filename); } else { gchar *tmpcdir; gchar *base_filename; if (base_uri) { base_filename = g_filename_from_uri (base_uri, NULL, NULL); if (base_filename != NULL) { tmpcdir = g_path_get_dirname (base_filename); g_free (base_filename); } else return NULL; } else tmpcdir = g_get_current_dir (); absolute_filename = g_build_filename (tmpcdir, filename, NULL); g_free (tmpcdir); } return absolute_filename; } Commit Message: Fixed possible credentials leaking reported by Alex Birsan. CWE ID:
_rsvg_io_get_file_path (const gchar * filename, const gchar * base_uri) { gchar *absolute_filename; if (g_path_is_absolute (filename)) { absolute_filename = g_strdup (filename); } else { gchar *tmpcdir; gchar *base_filename; if (base_uri) { base_filename = g_filename_from_uri (base_uri, NULL, NULL); if (base_filename != NULL) { tmpcdir = g_path_get_dirname (base_filename); g_free (base_filename); } else return NULL; } else tmpcdir = g_get_current_dir (); absolute_filename = g_build_filename (tmpcdir, filename, NULL); g_free (tmpcdir); } return absolute_filename; }
170,157
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: do_async_error (IncrementData *data) { GError *error; error = g_error_new (MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "%s", "this method always loses"); dbus_g_method_return_error (data->context, error); g_free (data); return FALSE; } Commit Message: CWE ID: CWE-264
do_async_error (IncrementData *data)
165,082
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(id_, -1); }
170,836
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284
int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; }
167,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MediaMetadataRetriever::MediaMetadataRetriever() { ALOGV("constructor"); const sp<IMediaPlayerService>& service(getService()); if (service == 0) { ALOGE("failed to obtain MediaMetadataRetrieverService"); return; } sp<IMediaMetadataRetriever> retriever(service->createMetadataRetriever()); if (retriever == 0) { ALOGE("failed to create IMediaMetadataRetriever object from server"); } mRetriever = retriever; } Commit Message: Get service by value instead of reference to prevent a cleared service binder from being used. Bug: 26040840 Change-Id: Ifb5483c55b172d3553deb80dbe27f2204b86ecdb CWE ID: CWE-119
MediaMetadataRetriever::MediaMetadataRetriever() { ALOGV("constructor"); const sp<IMediaPlayerService> service(getService()); if (service == 0) { ALOGE("failed to obtain MediaMetadataRetrieverService"); return; } sp<IMediaMetadataRetriever> retriever(service->createMetadataRetriever()); if (retriever == 0) { ALOGE("failed to create IMediaMetadataRetriever object from server"); } mRetriever = retriever; }
173,911
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ShellWindowFrameView::Init(views::Widget* frame) { frame_ = frame; ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); close_button_ = new views::ImageButton(this); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia()); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia()); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia()); close_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE)); AddChildView(close_button_); #if defined(USE_ASH) aura::Window* window = frame->GetNativeWindow(); int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ? kResizeOutsideBoundsSizeTouch : kResizeOutsideBoundsSize; window->set_hit_test_bounds_override_outer( gfx::Insets(-outside_bounds, -outside_bounds, -outside_bounds, -outside_bounds)); window->set_hit_test_bounds_override_inner( gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize, kResizeInsideBoundsSize, kResizeInsideBoundsSize)); #endif } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 R=ben@chromium.org Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
void ShellWindowFrameView::Init(views::Widget* frame) { frame_ = frame; if (!is_frameless_) { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); close_button_ = new views::ImageButton(this); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia()); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia()); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia()); close_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE)); AddChildView(close_button_); } #if defined(USE_ASH) aura::Window* window = frame->GetNativeWindow(); int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ? kResizeOutsideBoundsSizeTouch : kResizeOutsideBoundsSize; window->set_hit_test_bounds_override_outer( gfx::Insets(-outside_bounds, -outside_bounds, -outside_bounds, -outside_bounds)); window->set_hit_test_bounds_override_inner( gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize, kResizeInsideBoundsSize, kResizeInsideBoundsSize)); #endif }
170,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Browser::TabDetachedAt(TabContents* contents, int index) { TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void Browser::TabDetachedAt(TabContents* contents, int index) { void Browser::TabDetachedAt(WebContents* contents, int index) { TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH); }
171,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; } Commit Message: Fix several ineffective integer overflow checks Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added several integer overflow checks. Unfortunately, those checks fail to take into account integer promotion rules and are thus themselves subject to an integer overflow. Cast the sizeof() operator to a uint64_t to force promotion while multiplying. Bug: 20139950 (cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32) Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b CWE ID: CWE-189
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = mTimeToSampleCount * 2 * (uint64_t)sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; }
173,339
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int Downmix_Reset(downmix_object_t *pDownmixer, bool init) { return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int Downmix_Reset(downmix_object_t *pDownmixer, bool init) { int Downmix_Reset(downmix_object_t *pDownmixer __unused, bool init __unused) { return 0; }
173,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() { DCHECK_EQ(read_type_, kReadAsArrayBuffer); if (array_buffer_result_) return array_buffer_result_; if (!raw_data_ || error_code_ != FileErrorCode::kOK) return nullptr; DOMArrayBuffer* result = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer()); if (finished_loading_) { array_buffer_result_ = result; AdjustReportedMemoryUsageToV8( -1 * static_cast<int64_t>(raw_data_->ByteLength())); raw_data_.reset(); } return result; } Commit Message: FileReader: Make a copy of the ArrayBuffer when returning partial results. This is to avoid accidentally ending up with multiple references to the same underlying ArrayBuffer. The extra performance overhead of this is minimal as usage of partial results is very rare anyway (as can be seen on https://www.chromestatus.com/metrics/feature/timeline/popularity/2158). Bug: 936448 Change-Id: Icd1081adc1c889829fe7fa4af9cf4440097e8854 Reviewed-on: https://chromium-review.googlesource.com/c/1492873 Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Reviewed-by: Adam Klein <adamk@chromium.org> Cr-Commit-Position: refs/heads/master@{#636251} CWE ID: CWE-416
DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() { DCHECK_EQ(read_type_, kReadAsArrayBuffer); if (array_buffer_result_) return array_buffer_result_; if (!raw_data_ || error_code_ != FileErrorCode::kOK) return nullptr; if (!finished_loading_) { return DOMArrayBuffer::Create( ArrayBuffer::Create(raw_data_->Data(), raw_data_->ByteLength())); } array_buffer_result_ = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer()); AdjustReportedMemoryUsageToV8(-1 * static_cast<int64_t>(raw_data_->ByteLength())); raw_data_.reset(); return array_buffer_result_; }
173,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& suggested_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); callback.Run(suggested_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")), content::DOWNLOAD_INTERRUPT_REASON_NONE); } Commit Message: Always mark content downloaded by devtools delegate as potentially dangerous Bug: 805445 Change-Id: I7051f519205e178db57e23320ab979f8fa9ce38b Reviewed-on: https://chromium-review.googlesource.com/894782 Commit-Queue: David Vallet <dvallet@chromium.org> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Cr-Commit-Position: refs/heads/master@{#533215} CWE ID:
void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& suggested_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); callback.Run(suggested_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")), content::DOWNLOAD_INTERRUPT_REASON_NONE); }
173,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(bm, nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, bm, alloc_size); } if (err) return -EFAULT; return sys_set_mempolicy(mode, nm, nr_bits+1); } Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <salls@cs.ucsb.edu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-388
COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(bm, nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, bm, alloc_size)) return -EFAULT; } return sys_set_mempolicy(mode, nm, nr_bits+1); }
168,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); 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()) < 0) errExit("chown"); if (chmod(dest, S_IRUSR | S_IWUSR) < 0) errExit("chmod"); unlink(src); } Commit Message: security fix CWE ID: CWE-269
static void copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user fs_logger2("clone", dest); unlink(src); }
170,096
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GestureProviderAura::OnGestureEvent( const GestureEventData& gesture) { GestureEventDetails details = gesture.details; if (gesture.type == ET_GESTURE_TAP) { int tap_count = 1; if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture)) tap_count = 1 + (previous_tap_->details.tap_count() % 3); details.set_tap_count(tap_count); if (!previous_tap_) previous_tap_.reset(new GestureEventData(gesture)); else *previous_tap_ = gesture; previous_tap_->details = details; } else if (gesture.type == ET_GESTURE_TAP_CANCEL) { previous_tap_.reset(); } scoped_ptr<ui::GestureEvent> event( new ui::GestureEvent(gesture.type, gesture.x, gesture.y, last_touch_event_flags_, gesture.time - base::TimeTicks(), details, 1 << gesture.motion_event_id)); if (!handling_event_) { client_->OnGestureEvent(event.get()); } else { pending_gestures_.push_back(event.release()); } } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GestureProviderAura::OnGestureEvent( const GestureEventData& gesture) { GestureEventDetails details = gesture.details; if (gesture.type == ET_GESTURE_TAP) { int tap_count = 1; if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture)) tap_count = 1 + (previous_tap_->details.tap_count() % 3); details.set_tap_count(tap_count); if (!previous_tap_) previous_tap_.reset(new GestureEventData(gesture)); else *previous_tap_ = gesture; previous_tap_->details = details; } else if (gesture.type == ET_GESTURE_TAP_CANCEL) { previous_tap_.reset(); } scoped_ptr<ui::GestureEvent> event( new ui::GestureEvent(gesture.type, gesture.x, gesture.y, last_touch_event_flags_, gesture.time - base::TimeTicks(), details, 1 << gesture.motion_event_id)); ui::LatencyInfo* gesture_latency = event->latency(); gesture_latency->CopyLatencyFrom( last_touch_event_latency_info_, ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT); gesture_latency->CopyLatencyFrom( last_touch_event_latency_info_, ui::INPUT_EVENT_LATENCY_UI_COMPONENT); gesture_latency->CopyLatencyFrom( last_touch_event_latency_info_, ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT); if (!handling_event_) { client_->OnGestureEvent(event.get()); } else { pending_gestures_.push_back(event.release()); } }
171,204