instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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 [email protected] 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int mm_flags, unsigned long vm_flags, struct task_struct *tsk) { struct vm_area_struct *vma; int fault; vma = find_vma(mm, addr); fault = VM_FAULT_BADMAP; if (unlikely(!vma)) goto out; if (unlikely(vma->vm_start > addr)) goto check_stack; /* * Ok, we have a good vm_area for this memory access, so we can handle * it. */ good_area: /* * Check that the permissions on the VMA allow for the fault which * occurred. */ if (!(vma->vm_flags & vm_flags)) { fault = VM_FAULT_BADACCESS; goto out; } return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags); check_stack: if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) goto good_area; out: return fault; } Commit Message: Revert "arm64: Introduce execute-only page access permissions" This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08. While the aim is increased security for --x memory maps, it does not protect against kernel level reads. Until SECCOMP is implemented for arm64, revert this patch to avoid giving a false idea of execute-only mappings. Signed-off-by: Catalin Marinas <[email protected]> CWE ID: CWE-19
static int __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int mm_flags, unsigned long vm_flags, struct task_struct *tsk) { struct vm_area_struct *vma; int fault; vma = find_vma(mm, addr); fault = VM_FAULT_BADMAP; if (unlikely(!vma)) goto out; if (unlikely(vma->vm_start > addr)) goto check_stack; /* * Ok, we have a good vm_area for this memory access, so we can handle * it. */ good_area: /* * Check that the permissions on the VMA allow for the fault which * occurred. If we encountered a write or exec fault, we must have * appropriate permissions, otherwise we allow any permission. */ if (!(vma->vm_flags & vm_flags)) { fault = VM_FAULT_BADACCESS; goto out; } return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags); check_stack: if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) goto good_area; out: return fault; }
167,583
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseElement(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; xmlParserNodeInfo node_info; int line, tlen; xmlNodePtr ret; int nsNr = ctxt->nsNr; if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR, "Excessive depth in document: %d use XML_PARSE_HUGE option\n", xmlParserMaxDepth); ctxt->instate = XML_PARSER_EOF; return; } /* Capture start position */ if (ctxt->record_info) { node_info.begin_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.begin_line = ctxt->input->line; } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); line = ctxt->input->line; #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) return; if (name == NULL) { spacePop(ctxt); return; } namePush(ctxt, name); ret = ctxt->node; #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match the element * type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } if (RAW == '>') { NEXT1; } else { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } /* * Parse the content of the element: */ xmlParseContent(ctxt); if (!IS_BYTE_CHAR(RAW)) { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED, "Premature end of data in tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); return; } /* * parse the end of tag: '</' should be here. */ if (ctxt->sax2) { xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen); namePop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, line); #endif /* LIBXML_SAX1_ENABLED */ /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseElement(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; xmlParserNodeInfo node_info; int line, tlen; xmlNodePtr ret; int nsNr = ctxt->nsNr; if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR, "Excessive depth in document: %d use XML_PARSE_HUGE option\n", xmlParserMaxDepth); ctxt->instate = XML_PARSER_EOF; return; } /* Capture start position */ if (ctxt->record_info) { node_info.begin_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.begin_line = ctxt->input->line; } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); line = ctxt->input->line; #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) return; if (name == NULL) { spacePop(ctxt); return; } namePush(ctxt, name); ret = ctxt->node; #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match the element * type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } if (RAW == '>') { NEXT1; } else { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } return; } /* * Parse the content of the element: */ xmlParseContent(ctxt); if (ctxt->instate == XML_PARSER_EOF) return; if (!IS_BYTE_CHAR(RAW)) { xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED, "Premature end of data in tag %s line %d\n", name, line, NULL); /* * end of parsing of this node. */ nodePop(ctxt); namePop(ctxt); spacePop(ctxt); if (nsNr != ctxt->nsNr) nsPop(ctxt, ctxt->nsNr - nsNr); return; } /* * parse the end of tag: '</' should be here. */ if (ctxt->sax2) { xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen); namePop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, line); #endif /* LIBXML_SAX1_ENABLED */ /* * Capture end position and add node */ if ( ret != NULL && ctxt->record_info ) { node_info.end_pos = ctxt->input->consumed + (CUR_PTR - ctxt->input->base); node_info.end_line = ctxt->input->line; node_info.node = ret; xmlParserAddNodeInfo(ctxt, &node_info); } }
171,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: scoped_ptr<GDataEntry> GDataDirectoryService::FromProtoString( const std::string& serialized_proto) { GDataEntryProto entry_proto; if (!entry_proto.ParseFromString(serialized_proto)) return scoped_ptr<GDataEntry>(); scoped_ptr<GDataEntry> entry; if (entry_proto.file_info().is_directory()) { entry.reset(new GDataDirectory(NULL, this)); if (!entry->FromProto(entry_proto)) { NOTREACHED() << "FromProto (directory) failed"; entry.reset(); } } else { scoped_ptr<GDataFile> file(new GDataFile(NULL, this)); if (file->FromProto(entry_proto)) { entry.reset(file.release()); } else { NOTREACHED() << "FromProto (file) failed"; } } return entry.Pass(); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
scoped_ptr<GDataEntry> GDataDirectoryService::FromProtoString( const std::string& serialized_proto) { GDataEntryProto entry_proto; if (!entry_proto.ParseFromString(serialized_proto)) return scoped_ptr<GDataEntry>(); scoped_ptr<GDataEntry> entry; if (entry_proto.file_info().is_directory()) { entry.reset(CreateGDataDirectory()); if (!entry->FromProto(entry_proto)) { NOTREACHED() << "FromProto (directory) failed"; entry.reset(); } } else { scoped_ptr<GDataFile> file(CreateGDataFile()); if (file->FromProto(entry_proto)) { entry.reset(file.release()); } else { NOTREACHED() << "FromProto (file) failed"; } } return entry.Pass(); }
171,488
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_EC unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); if (ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB); goto err; } /* Generate encoding of client key */ encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint); if (encoded_pt_len == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB); goto err; } EVP_PKEY_free(ckey); ckey = NULL; *len = encoded_pt_len; /* length of encoded point */ **p = *len; *p += 1; /* copy the point */ memcpy(*p, encodedPoint, *len); /* increment len to account for length field */ *len += 1; OPENSSL_free(encodedPoint); return 1; err: EVP_PKEY_free(ckey); return 0; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif } Commit Message: Fix missing NULL checks in CKE processing Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-476
static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_EC unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); if (ckey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); goto err; } if (ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB); goto err; } /* Generate encoding of client key */ encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint); if (encoded_pt_len == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB); goto err; } EVP_PKEY_free(ckey); ckey = NULL; *len = encoded_pt_len; /* length of encoded point */ **p = *len; *p += 1; /* copy the point */ memcpy(*p, encodedPoint, *len); /* increment len to account for length field */ *len += 1; OPENSSL_free(encodedPoint); return 1; err: EVP_PKEY_free(ckey); return 0; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif }
168,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) //error return true; //must assume done if (total < 0) return false; //assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); } 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 Segment::DoneParsing() const bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) // error return true; // must assume done if (total < 0) return false; // assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); }
174,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (request.url() != GURL(kSwappedOutURL) && GetContentClient()->renderer()->HandleNavigation(frame, request, type, default_policy, is_redirect)) { return WebKit::WebNavigationPolicyIgnore; } Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(frame, request)); if (is_swapped_out_) { if (request.url() != GURL(kSwappedOutURL)) { if (frame->parent() == NULL) { OpenURL(frame, request.url(), referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } return WebKit::WebNavigationPolicyIgnore; } return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool force_swap_due_to_flag = command_line.HasSwitch(switches::kEnableStrictSiteIsolation) || command_line.HasSwitch(switches::kSitePerProcess); if (force_swap_due_to_flag && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (!net::RegistryControlledDomainService::SameDomainOrHost(frame_url, url) || frame_url.scheme() != url.scheme()) { OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_request = renderer_preferences_.browser_handles_non_local_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (!browser_handles_request) { browser_handles_request = renderer_preferences_.browser_handles_all_top_level_requests && IsTopLevelNavigation(frame); } if (browser_handles_request) { page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool is_initial_navigation = page_id_ == -1; bool should_fork = HasWebUIScheme(url) || (cumulative_bindings & BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || (frame->isViewSourceModeEnabled() && type != WebKit::WebNavigationTypeReload); if (!should_fork && url.SchemeIs(chrome::kFileScheme)) { GURL source_url(old_url); if (is_initial_navigation && source_url.is_empty() && frame->opener()) source_url = frame->opener()->top()->document().url(); DCHECK(!source_url.is_empty()); should_fork = !source_url.SchemeIs(chrome::kFileScheme); } if (!should_fork) { should_fork = GetContentClient()->renderer()->ShouldFork( frame, url, request.httpMethod().utf8(), is_initial_navigation, &send_referrer); } if (should_fork) { OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; } Commit Message: Let the browser handle external navigations from DevTools. BUG=180555 Review URL: https://chromiumcodereview.appspot.com/12531004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@186793 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (request.url() != GURL(kSwappedOutURL) && GetContentClient()->renderer()->HandleNavigation(frame, request, type, default_policy, is_redirect)) { return WebKit::WebNavigationPolicyIgnore; } Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(frame, request)); if (is_swapped_out_) { if (request.url() != GURL(kSwappedOutURL)) { if (frame->parent() == NULL) { OpenURL(frame, request.url(), referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } return WebKit::WebNavigationPolicyIgnore; } return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool force_swap_due_to_flag = command_line.HasSwitch(switches::kEnableStrictSiteIsolation) || command_line.HasSwitch(switches::kSitePerProcess); if (force_swap_due_to_flag && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (!net::RegistryControlledDomainService::SameDomainOrHost(frame_url, url) || frame_url.scheme() != url.scheme()) { OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_request = renderer_preferences_.browser_handles_non_local_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (!browser_handles_request) { browser_handles_request = renderer_preferences_.browser_handles_all_top_level_requests && IsTopLevelNavigation(frame); } if (browser_handles_request) { page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; // All navigations to or from WebUI URLs or within WebUI-enabled // RenderProcesses must be handled by the browser process so that the // correct bindings and data sources can be registered. int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool is_initial_navigation = page_id_ == -1; bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) || (cumulative_bindings & BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || (frame->isViewSourceModeEnabled() && type != WebKit::WebNavigationTypeReload); if (!should_fork && url.SchemeIs(chrome::kFileScheme)) { GURL source_url(old_url); if (is_initial_navigation && source_url.is_empty() && frame->opener()) source_url = frame->opener()->top()->document().url(); DCHECK(!source_url.is_empty()); should_fork = !source_url.SchemeIs(chrome::kFileScheme); } if (!should_fork) { should_fork = GetContentClient()->renderer()->ShouldFork( frame, url, request.httpMethod().utf8(), is_initial_navigation, &send_referrer); } if (should_fork) { OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; }
171,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __init pf_init(void) { /* preliminary initialisation */ struct pf_unit *pf; int unit; if (disable) return -EINVAL; pf_init_units(); if (pf_detect()) return -ENODEV; pf_busy = 0; if (register_blkdev(major, name)) { for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) put_disk(pf->disk); return -EBUSY; } for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { struct gendisk *disk = pf->disk; if (!pf->present) continue; disk->private_data = pf; add_disk(disk); } return 0; } Commit Message: paride/pf: Fix potential NULL pointer dereference Syzkaller report this: pf: pf version 1.04, major 47, cluster 64, nice 0 pf: No ATAPI disk detected kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:pf_init+0x7af/0x1000 [pf] Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34 RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202 RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788 RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580 RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59 R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000 R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020 FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: ? 0xffffffffc1e50000 do_one_initcall+0xbc/0x47d init/main.c:901 do_init_module+0x1b5/0x547 kernel/module.c:3456 load_module+0x6405/0x8c10 kernel/module.c:3804 __do_sys_finit_module+0x162/0x190 kernel/module.c:3898 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003 RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp c ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp td glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace 7a818cf5f210d79e ]--- If alloc_disk fails in pf_init_units, pf->disk will be NULL, however in pf_detect and pf_exit, it's not check this before free.It may result a NULL pointer dereference. Also when register_blkdev failed, blk_cleanup_queue() and blk_mq_free_tag_set() should be called to free resources. Reported-by: Hulk Robot <[email protected]> Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-476
static int __init pf_init(void) { /* preliminary initialisation */ struct pf_unit *pf; int unit; if (disable) return -EINVAL; pf_init_units(); if (pf_detect()) return -ENODEV; pf_busy = 0; if (register_blkdev(major, name)) { for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { if (!pf->disk) continue; blk_cleanup_queue(pf->disk->queue); blk_mq_free_tag_set(&pf->tag_set); put_disk(pf->disk); } return -EBUSY; } for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { struct gendisk *disk = pf->disk; if (!pf->present) continue; disk->private_data = pf; add_disk(disk); } return 0; }
169,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); } Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and http://bugzilla.maptools.org/show_bug.cgi?id=2657 CWE ID: CWE-119
pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); }
168,414
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void QuotaManager::GetAvailableSpace(const AvailableSpaceCallback& callback) { if (is_incognito_) { callback.Run(kQuotaStatusOk, kIncognitoDefaultTemporaryQuota); return; } make_scoped_refptr(new AvailableSpaceQueryTask(this, callback))->Start(); } Commit Message: Wipe out QuotaThreadTask. This is a one of a series of refactoring patches for QuotaManager. http://codereview.chromium.org/10872054/ http://codereview.chromium.org/10917060/ BUG=139270 Review URL: https://chromiumcodereview.appspot.com/10919070 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154987 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void QuotaManager::GetAvailableSpace(const AvailableSpaceCallback& callback) { if (is_incognito_) { callback.Run(kQuotaStatusOk, kIncognitoDefaultTemporaryQuota); return; } PostTaskAndReplyWithResult( db_thread_, FROM_HERE, base::Bind(get_disk_space_fn_, profile_path_), base::Bind(&QuotaManager::DidGetAvailableSpace, weak_factory_.GetWeakPtr(), callback)); }
170,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR param) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: return internalSetBitrateParams( (const OMX_VIDEO_PARAM_BITRATETYPE *)param); case OMX_IndexParamVideoVp8: return internalSetVp8Params( (const OMX_VIDEO_PARAM_VP8TYPE *)param); case OMX_IndexParamVideoAndroidVp8Encoder: return internalSetAndroidVp8Params( (const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param); default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, param); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR param) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { const OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (const OMX_VIDEO_PARAM_BITRATETYPE*) param; if (!isValidOMXParam(bitRate)) { return OMX_ErrorBadParameter; } return internalSetBitrateParams(bitRate); } case OMX_IndexParamVideoVp8: { const OMX_VIDEO_PARAM_VP8TYPE *vp8Params = (const OMX_VIDEO_PARAM_VP8TYPE*) param; if (!isValidOMXParam(vp8Params)) { return OMX_ErrorBadParameter; } return internalSetVp8Params(vp8Params); } case OMX_IndexParamVideoAndroidVp8Encoder: { const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *vp8AndroidParams = (const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE*) param; if (!isValidOMXParam(vp8AndroidParams)) { return OMX_ErrorBadParameter; } return internalSetAndroidVp8Params(vp8AndroidParams); } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, param); } }
174,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void Predict(MB_PREDICTION_MODE mode) { mbptr_->mode_info_context->mbmi.mode = mode; REGISTER_STATE_CHECK(pred_fn_(mbptr_, data_ptr_[0] - kStride, data_ptr_[0] - 1, kStride, data_ptr_[0], kStride)); } 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 Predict(MB_PREDICTION_MODE mode) { mbptr_->mode_info_context->mbmi.mode = mode; ASM_REGISTER_STATE_CHECK(pred_fn_(mbptr_, data_ptr_[0] - kStride, data_ptr_[0] - 1, kStride, data_ptr_[0], kStride)); }
174,566
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DataReductionProxySettings::IsDataReductionProxyEnabled() const { if (base::FeatureList::IsEnabled(network::features::kNetworkService) && !params::IsEnabledWithNetworkService()) { return false; } return IsDataSaverEnabledByUser(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
bool DataReductionProxySettings::IsDataReductionProxyEnabled() const { if (base::FeatureList::IsEnabled(network::features::kNetworkService) && !params::IsEnabledWithNetworkService()) { return false; } return IsDataSaverEnabledByUser(GetOriginalProfilePrefs()); }
172,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InputMethodStatusConnection* ChromeOSMonitorInputMethodStatus( void* language_library, LanguageCurrentInputMethodMonitorFunction current_input_method_changed, LanguageRegisterImePropertiesFunction register_ime_properties, LanguageUpdateImePropertyFunction update_ime_property, LanguageConnectionChangeMonitorFunction connection_changed) { DLOG(INFO) << "MonitorInputMethodStatus"; return InputMethodStatusConnection::GetConnection( language_library, current_input_method_changed, register_ime_properties, update_ime_property, connection_changed); } 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
InputMethodStatusConnection* ChromeOSMonitorInputMethodStatus(
170,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ext4_free_io_end(ext4_io_end_t *io) { BUG_ON(!io); iput(io->inode); kfree(io); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static void ext4_free_io_end(ext4_io_end_t *io)
167,544
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190
int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size; if (pkg->body_size > RPC_PKG_MAX_BODY_SIZE) { return -1; } pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); if (send_buf == NULL) { return -1; } } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; }
169,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return) { XIDeviceInfo *info = NULL; xXIQueryDeviceReq *req; xXIQueryDeviceReq *req; xXIQueryDeviceReply reply; char *ptr; int i; char *buf; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1) goto error_unlocked; GetReq(XIQueryDevice, req); req->reqType = extinfo->codes->major_opcode; req->ReqType = X_XIQueryDevice; req->deviceid = deviceid; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; *ndevices_return = reply.num_devices; info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo)); if (!info) goto error; buf = Xmalloc(reply.length * 4); _XRead(dpy, buf, reply.length * 4); ptr = buf; /* info is a null-terminated array */ info[reply.num_devices].name = NULL; nclasses = wire->num_classes; ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); XIDeviceInfo *lib = &info[i]; xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr; lib->deviceid = wire->deviceid; lib->use = wire->use; lib->attachment = wire->attachment; Xfree(buf); ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); strncpy(lib->name, ptr, wire->name_len); ptr += ((wire->name_len + 3)/4) * 4; sz = size_classes((xXIAnyInfo*)ptr, nclasses); lib->classes = Xmalloc(sz); ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses); /* We skip over unused classes */ lib->num_classes = nclasses; } Commit Message: CWE ID: CWE-284
XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return) { XIDeviceInfo *info = NULL; xXIQueryDeviceReq *req; xXIQueryDeviceReq *req; xXIQueryDeviceReply reply; char *ptr; char *end; int i; char *buf; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1) goto error_unlocked; GetReq(XIQueryDevice, req); req->reqType = extinfo->codes->major_opcode; req->ReqType = X_XIQueryDevice; req->deviceid = deviceid; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (reply.length < INT_MAX / 4) { *ndevices_return = reply.num_devices; info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo)); } else { *ndevices_return = 0; info = NULL; } if (!info) goto error; buf = Xmalloc(reply.length * 4); _XRead(dpy, buf, reply.length * 4); ptr = buf; end = buf + reply.length * 4; /* info is a null-terminated array */ info[reply.num_devices].name = NULL; nclasses = wire->num_classes; ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); XIDeviceInfo *lib = &info[i]; xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr; if (ptr + sizeof(xXIDeviceInfo) > end) goto error_loop; lib->deviceid = wire->deviceid; lib->use = wire->use; lib->attachment = wire->attachment; Xfree(buf); ptr += sizeof(xXIDeviceInfo); if (ptr + wire->name_len > end) goto error_loop; lib->name = Xcalloc(wire->name_len + 1, 1); if (lib->name == NULL) goto error_loop; strncpy(lib->name, ptr, wire->name_len); lib->name[wire->name_len] = '\0'; ptr += ((wire->name_len + 3)/4) * 4; sz = size_classes((xXIAnyInfo*)ptr, nclasses); lib->classes = Xmalloc(sz); if (lib->classes == NULL) { Xfree(lib->name); goto error_loop; } ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses); /* We skip over unused classes */ lib->num_classes = nclasses; }
164,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) return; } 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
INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; if (ps_stream->u4_offset < ps_stream->u4_max_offset) { FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) } return; }
173,941
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CorePageLoadMetricsObserver::RecordTimingHistograms( const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { if (info.started_in_foreground && info.first_background_time) { const base::TimeDelta first_background_time = info.first_background_time.value(); if (!info.time_to_commit) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforeCommit, first_background_time); } else if (!timing.first_paint || timing.first_paint > first_background_time) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforePaint, first_background_time); } if (timing.parse_start && first_background_time >= timing.parse_start && (!timing.parse_stop || timing.parse_stop > first_background_time)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundDuringParse, first_background_time); } } if (failed_provisional_load_info_.error != net::OK) { DCHECK(failed_provisional_load_info_.interval); if (WasStartedInForegroundOptionalEventInForeground( failed_provisional_load_info_.interval, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFailedProvisionalLoad, failed_provisional_load_info_.interval.value()); } } if (!info.time_to_commit || timing.IsEmpty()) return; const base::TimeDelta time_to_commit = info.time_to_commit.value(); if (WasStartedInForegroundOptionalEventInForeground(info.time_to_commit, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramCommit, time_to_commit); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramCommit, time_to_commit); } if (timing.dom_content_loaded_event_start) { if (WasStartedInForegroundOptionalEventInForeground( timing.dom_content_loaded_event_start, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramDomContentLoaded, timing.dom_content_loaded_event_start.value()); PAGE_LOAD_HISTOGRAM(internal::kHistogramDomLoadingToDomContentLoaded, timing.dom_content_loaded_event_start.value() - timing.dom_loading.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramDomContentLoaded, timing.dom_content_loaded_event_start.value()); } } if (timing.load_event_start) { if (WasStartedInForegroundOptionalEventInForeground(timing.load_event_start, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramLoad, timing.load_event_start.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramLoad, timing.load_event_start.value()); } } if (timing.first_layout) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_layout, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstLayout, timing.first_layout.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstLayout, timing.first_layout.value()); } } if (timing.first_paint) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaint, timing.first_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaint, timing.first_paint.value()); } if (!info.started_in_foreground && info.first_foreground_time && timing.first_paint > info.first_foreground_time.value() && (!info.first_background_time || timing.first_paint < info.first_background_time.value())) { PAGE_LOAD_HISTOGRAM( internal::kHistogramForegroundToFirstPaint, timing.first_paint.value() - info.first_foreground_time.value()); } } if (timing.first_text_paint) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_text_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstTextPaint, timing.first_text_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstTextPaint, timing.first_text_paint.value()); } } if (timing.first_image_paint) { if (WasStartedInForegroundOptionalEventInForeground( timing.first_image_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstImagePaint, timing.first_image_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstImagePaint, timing.first_image_paint.value()); } } if (timing.first_contentful_paint) { if (WasStartedInForegroundOptionalEventInForeground( timing.first_contentful_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaint, timing.first_contentful_paint.value()); if (base::TimeTicks::IsHighResolution()) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintHigh, timing.first_contentful_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintLow, timing.first_contentful_paint.value()); } PAGE_LOAD_HISTOGRAM( internal::kHistogramParseStartToFirstContentfulPaint, timing.first_contentful_paint.value() - timing.parse_start.value()); PAGE_LOAD_HISTOGRAM( internal::kHistogramDomLoadingToFirstContentfulPaint, timing.first_contentful_paint.value() - timing.dom_loading.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstContentfulPaint, timing.first_contentful_paint.value()); } } if (timing.parse_start) { if (WasParseInForeground(timing.parse_start, timing.parse_stop, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramParseBlockedOnScriptLoad, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal::kHistogramParseBlockedOnScriptLoadDocumentWrite, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } else { PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoad, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } } if (timing.parse_stop) { base::TimeDelta parse_duration = timing.parse_stop.value() - timing.parse_start.value(); if (WasStartedInForegroundOptionalEventInForeground(timing.parse_stop, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramParseDuration, parse_duration); PAGE_LOAD_HISTOGRAM( internal::kHistogramParseBlockedOnScriptLoadParseComplete, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal:: kHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseDuration, parse_duration); PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoadParseComplete, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal:: kBackgroundHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } } if (info.started_in_foreground) { if (info.first_background_time) PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstBackground, info.first_background_time.value()); } else { if (info.first_foreground_time) PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstForeground, info.first_foreground_time.value()); } } Commit Message: Remove clock resolution page load histograms. These were temporary metrics intended to understand whether high/low resolution clocks adversely impact page load metrics. After collecting a few months of data it was determined that clock resolution doesn't adversely impact our metrics, and it that these histograms were no longer needed. BUG=394757 Review-Url: https://codereview.chromium.org/2155143003 Cr-Commit-Position: refs/heads/master@{#406143} CWE ID:
void CorePageLoadMetricsObserver::RecordTimingHistograms( const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { if (info.started_in_foreground && info.first_background_time) { const base::TimeDelta first_background_time = info.first_background_time.value(); if (!info.time_to_commit) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforeCommit, first_background_time); } else if (!timing.first_paint || timing.first_paint > first_background_time) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforePaint, first_background_time); } if (timing.parse_start && first_background_time >= timing.parse_start && (!timing.parse_stop || timing.parse_stop > first_background_time)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundDuringParse, first_background_time); } } if (failed_provisional_load_info_.error != net::OK) { DCHECK(failed_provisional_load_info_.interval); if (WasStartedInForegroundOptionalEventInForeground( failed_provisional_load_info_.interval, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFailedProvisionalLoad, failed_provisional_load_info_.interval.value()); } } if (!info.time_to_commit || timing.IsEmpty()) return; const base::TimeDelta time_to_commit = info.time_to_commit.value(); if (WasStartedInForegroundOptionalEventInForeground(info.time_to_commit, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramCommit, time_to_commit); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramCommit, time_to_commit); } if (timing.dom_content_loaded_event_start) { if (WasStartedInForegroundOptionalEventInForeground( timing.dom_content_loaded_event_start, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramDomContentLoaded, timing.dom_content_loaded_event_start.value()); PAGE_LOAD_HISTOGRAM(internal::kHistogramDomLoadingToDomContentLoaded, timing.dom_content_loaded_event_start.value() - timing.dom_loading.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramDomContentLoaded, timing.dom_content_loaded_event_start.value()); } } if (timing.load_event_start) { if (WasStartedInForegroundOptionalEventInForeground(timing.load_event_start, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramLoad, timing.load_event_start.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramLoad, timing.load_event_start.value()); } } if (timing.first_layout) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_layout, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstLayout, timing.first_layout.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstLayout, timing.first_layout.value()); } } if (timing.first_paint) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaint, timing.first_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaint, timing.first_paint.value()); } if (!info.started_in_foreground && info.first_foreground_time && timing.first_paint > info.first_foreground_time.value() && (!info.first_background_time || timing.first_paint < info.first_background_time.value())) { PAGE_LOAD_HISTOGRAM( internal::kHistogramForegroundToFirstPaint, timing.first_paint.value() - info.first_foreground_time.value()); } } if (timing.first_text_paint) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_text_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstTextPaint, timing.first_text_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstTextPaint, timing.first_text_paint.value()); } } if (timing.first_image_paint) { if (WasStartedInForegroundOptionalEventInForeground( timing.first_image_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstImagePaint, timing.first_image_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstImagePaint, timing.first_image_paint.value()); } } if (timing.first_contentful_paint) { if (WasStartedInForegroundOptionalEventInForeground( timing.first_contentful_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaint, timing.first_contentful_paint.value()); PAGE_LOAD_HISTOGRAM( internal::kHistogramParseStartToFirstContentfulPaint, timing.first_contentful_paint.value() - timing.parse_start.value()); PAGE_LOAD_HISTOGRAM( internal::kHistogramDomLoadingToFirstContentfulPaint, timing.first_contentful_paint.value() - timing.dom_loading.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstContentfulPaint, timing.first_contentful_paint.value()); } } if (timing.parse_start) { if (WasParseInForeground(timing.parse_start, timing.parse_stop, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramParseBlockedOnScriptLoad, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal::kHistogramParseBlockedOnScriptLoadDocumentWrite, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } else { PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoad, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } } if (timing.parse_stop) { base::TimeDelta parse_duration = timing.parse_stop.value() - timing.parse_start.value(); if (WasStartedInForegroundOptionalEventInForeground(timing.parse_stop, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramParseDuration, parse_duration); PAGE_LOAD_HISTOGRAM( internal::kHistogramParseBlockedOnScriptLoadParseComplete, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal:: kHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseDuration, parse_duration); PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoadParseComplete, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal:: kBackgroundHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } } if (info.started_in_foreground) { if (info.first_background_time) PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstBackground, info.first_background_time.value()); } else { if (info.first_foreground_time) PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstForeground, info.first_foreground_time.value()); } }
171,663
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC) { php_stream *tmpstream = NULL; databuf_t *data = NULL; char *ptr; int ch, lastch; size_t size, rcvd; size_t lines; char **ret = NULL; char **entry; char *text; if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory."); return NULL; } if (!ftp_type(ftp, FTPTYPE_ASCII)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (!ftp_putcmd(ftp, cmd, path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) { goto bail; } /* some servers don't open a ftp-data connection if the directory is empty */ if (ftp->resp == 226) { ftp->data = data_close(ftp, data); php_stream_close(tmpstream); return ecalloc(1, sizeof(char*)); } /* pull data buffer into tmpfile */ if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; lines = 0; lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1 || rcvd > ((size_t)(-1))-size) { goto bail; } php_stream_write(tmpstream, data->buf, rcvd); size += rcvd; for (ptr = data->buf; rcvd; rcvd--, ptr++) { if (*ptr == '\n' && lastch == '\r') { lines++; } else { size++; } lastch = *ptr; } lastch = *ptr; } } Commit Message: CWE ID: CWE-119
ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC) { php_stream *tmpstream = NULL; databuf_t *data = NULL; char *ptr; int ch, lastch; size_t size, rcvd; size_t lines; char **ret = NULL; char **entry; char *text; if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory."); return NULL; } if (!ftp_type(ftp, FTPTYPE_ASCII)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (!ftp_putcmd(ftp, cmd, path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) { goto bail; } /* some servers don't open a ftp-data connection if the directory is empty */ if (ftp->resp == 226) { ftp->data = data_close(ftp, data); php_stream_close(tmpstream); return ecalloc(1, sizeof(char*)); } /* pull data buffer into tmpfile */ if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; lines = 0; lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1 || rcvd > ((size_t)(-1))-size) { goto bail; } php_stream_write(tmpstream, data->buf, rcvd); size += rcvd; for (ptr = data->buf; rcvd; rcvd--, ptr++) { if (*ptr == '\n' && lastch == '\r') { lines++; } lastch = *ptr; } lastch = *ptr; } }
165,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int MSG_ReadBits( msg_t *msg, int bits ) { int value; int get; qboolean sgn; int i, nbits; value = 0; if ( bits < 0 ) { bits = -bits; sgn = qtrue; } else { sgn = qfalse; } if (msg->oob) { if(bits==8) { value = msg->data[msg->readcount]; msg->readcount += 1; msg->bit += 8; } else if(bits==16) { short temp; CopyLittleShort(&temp, &msg->data[msg->readcount]); value = temp; msg->readcount += 2; msg->bit += 16; } else if(bits==32) { CopyLittleLong(&value, &msg->data[msg->readcount]); msg->readcount += 4; msg->bit += 32; } else Com_Error(ERR_DROP, "can't read %d bits", bits); } else { nbits = 0; if (bits&7) { nbits = bits&7; for(i=0;i<nbits;i++) { value |= (Huff_getBit(msg->data, &msg->bit)<<i); } bits = bits - nbits; } if (bits) { for(i=0;i<bits;i+=8) { Huff_offsetReceive (msgHuff.decompressor.tree, &get, msg->data, &msg->bit); value |= (get<<(i+nbits)); } } msg->readcount = (msg->bit>>3)+1; } if ( sgn && bits > 0 && bits < 32 ) { if ( value & ( 1 << ( bits - 1 ) ) ) { value |= -1 ^ ( ( 1 << bits ) - 1 ); } } return value; } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119
int MSG_ReadBits( msg_t *msg, int bits ) { int value; int get; qboolean sgn; int i, nbits; if ( msg->readcount > msg->cursize ) { return 0; } value = 0; if ( bits < 0 ) { bits = -bits; sgn = qtrue; } else { sgn = qfalse; } if (msg->oob) { if (msg->readcount + (bits>>3) > msg->cursize) { msg->readcount = msg->cursize + 1; return 0; } if(bits==8) { value = msg->data[msg->readcount]; msg->readcount += 1; msg->bit += 8; } else if(bits==16) { short temp; CopyLittleShort(&temp, &msg->data[msg->readcount]); value = temp; msg->readcount += 2; msg->bit += 16; } else if(bits==32) { CopyLittleLong(&value, &msg->data[msg->readcount]); msg->readcount += 4; msg->bit += 32; } else Com_Error(ERR_DROP, "can't read %d bits", bits); } else { nbits = 0; if (bits&7) { nbits = bits&7; if (msg->bit + nbits > msg->cursize << 3) { msg->readcount = msg->cursize + 1; return 0; } for(i=0;i<nbits;i++) { value |= (Huff_getBit(msg->data, &msg->bit)<<i); } bits = bits - nbits; } if (bits) { for(i=0;i<bits;i+=8) { Huff_offsetReceive (msgHuff.decompressor.tree, &get, msg->data, &msg->bit, msg->cursize<<3); value |= (get<<(i+nbits)); if (msg->bit > msg->cursize<<3) { msg->readcount = msg->cursize + 1; return 0; } } } msg->readcount = (msg->bit>>3)+1; } if ( sgn && bits > 0 && bits < 32 ) { if ( value & ( 1 << ( bits - 1 ) ) ) { value |= -1 ^ ( ( 1 << bits ) - 1 ); } } return value; }
167,998
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ContextImpl::CreateFrame( fidl::InterfaceHandle<chromium::web::FrameObserver> observer, fidl::InterfaceRequest<chromium::web::Frame> frame_request) { auto web_contents = content::WebContents::Create( content::WebContents::CreateParams(browser_context_, nullptr)); frame_bindings_.AddBinding( std::make_unique<FrameImpl>(std::move(web_contents), observer.Bind()), std::move(frame_request)); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
void ContextImpl::CreateFrame( fidl::InterfaceRequest<chromium::web::Frame> frame_request) { auto web_contents = content::WebContents::Create( content::WebContents::CreateParams(browser_context_, nullptr)); frames_.insert(std::make_unique<FrameImpl>(std::move(web_contents), this, std::move(frame_request))); } void ContextImpl::DestroyFrame(FrameImpl* frame) { DCHECK(frames_.find(frame) != frames_.end()); frames_.erase(frames_.find(frame)); } FrameImpl* ContextImpl::GetFrameImplForTest( chromium::web::FramePtr* frame_ptr) { DCHECK(frame_ptr); // Find the FrameImpl whose channel is connected to |frame_ptr| by inspecting // the related_koids of active FrameImpls. zx_info_handle_basic_t handle_info; zx_status_t status = frame_ptr->channel().get_info( ZX_INFO_HANDLE_BASIC, &handle_info, sizeof(zx_info_handle_basic_t), nullptr, nullptr); ZX_CHECK(status == ZX_OK, status) << "zx_object_get_info"; zx_handle_t client_handle_koid = handle_info.koid; for (const std::unique_ptr<FrameImpl>& frame : frames_) { status = frame->GetBindingChannelForTest()->get_info( ZX_INFO_HANDLE_BASIC, &handle_info, sizeof(zx_info_handle_basic_t), nullptr, nullptr); ZX_CHECK(status == ZX_OK, status) << "zx_object_get_info"; if (client_handle_koid == handle_info.related_koid) return frame.get(); } return nullptr; }
172,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IOHandler::IOHandler(DevToolsIOContext* io_context) : DevToolsDomainHandler(IO::Metainfo::domainName), io_context_(io_context), process_host_(nullptr), weak_factory_(this) {} 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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
IOHandler::IOHandler(DevToolsIOContext* io_context) : DevToolsDomainHandler(IO::Metainfo::domainName), io_context_(io_context), browser_context_(nullptr), storage_partition_(nullptr), weak_factory_(this) {}
172,749
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: double AudioTrack::GetSamplingRate() const { return m_rate; } 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
double AudioTrack::GetSamplingRate() const while (i != j) { Track* const pTrack = *i++; delete pTrack; } delete[] m_trackEntries; }
174,352
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void TearDownTestCase() { vpx_free(source_data_); source_data_ = NULL; vpx_free(reference_data_); reference_data_ = NULL; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void TearDownTestCase() { vpx_free(source_data8_); source_data8_ = NULL; vpx_free(reference_data8_); reference_data8_ = NULL; vpx_free(second_pred8_); second_pred8_ = NULL; vpx_free(source_data16_); source_data16_ = NULL; vpx_free(reference_data16_); reference_data16_ = NULL; vpx_free(second_pred16_); second_pred16_ = NULL; }
174,579
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) { if (!(boundary_value >= 0 && boundary_value <= 100 && sample >= 0 && sample < boundary_value)) { frontend_host_->BadMessageRecieved(); return; } if (name == kDevToolsActionTakenHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else if (name == kDevToolsPanelShownHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else frontend_host_->BadMessageRecieved(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) { if (!frontend_host_) return; if (!(boundary_value >= 0 && boundary_value <= 100 && sample >= 0 && sample < boundary_value)) { frontend_host_->BadMessageRecieved(); return; } if (name == kDevToolsActionTakenHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else if (name == kDevToolsPanelShownHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else frontend_host_->BadMessageRecieved(); }
172,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string GetUploadData(const std::string& brand) { DCHECK(!brand.empty()); std::string data(kPostXml); const std::string placeholder("__BRANDCODE_PLACEHOLDER__"); size_t placeholder_pos = data.find(placeholder); DCHECK(placeholder_pos != std::string::npos); data.replace(placeholder_pos, placeholder.size(), brand); return data; } Commit Message: Use install_static::GetAppGuid instead of the hardcoded string in BrandcodeConfigFetcher. Bug: 769756 Change-Id: Ifdcb0a5145ffad1d563562e2b2ea2390ff074cdc Reviewed-on: https://chromium-review.googlesource.com/1213178 Reviewed-by: Dominic Battré <[email protected]> Commit-Queue: Vasilii Sukhanov <[email protected]> Cr-Commit-Position: refs/heads/master@{#590275} CWE ID: CWE-79
std::string GetUploadData(const std::string& brand) { std::string app_id(kDefaultAppID); #if defined(OS_WIN) app_id = install_static::UTF16ToUTF8(install_static::GetAppGuid()); #endif // defined(OS_WIN) DCHECK(!brand.empty()); return base::StringPrintf(kPostXml, app_id.c_str(), brand.c_str()); }
172,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ip_expire(unsigned long arg) { struct ipq *qp; struct net *net; qp = container_of((struct inet_frag_queue *) arg, struct ipq, q); net = container_of(qp->q.net, struct net, ipv4.frags); spin_lock(&qp->q.lock); if (qp->q.last_in & INET_FRAG_COMPLETE) goto out; ipq_kill(qp); IP_INC_STATS_BH(net, IPSTATS_MIB_REASMTIMEOUT); IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS); if ((qp->q.last_in & INET_FRAG_FIRST_IN) && qp->q.fragments != NULL) { struct sk_buff *head = qp->q.fragments; rcu_read_lock(); head->dev = dev_get_by_index_rcu(net, qp->iif); if (!head->dev) goto out_rcu_unlock; /* * Only search router table for the head fragment, * when defraging timeout at PRE_ROUTING HOOK. */ if (qp->user == IP_DEFRAG_CONNTRACK_IN && !skb_dst(head)) { const struct iphdr *iph = ip_hdr(head); int err = ip_route_input(head, iph->daddr, iph->saddr, iph->tos, head->dev); if (unlikely(err)) goto out_rcu_unlock; /* * Only an end host needs to send an ICMP * "Fragment Reassembly Timeout" message, per RFC792. */ if (skb_rtable(head)->rt_type != RTN_LOCAL) goto out_rcu_unlock; } /* Send an ICMP "Fragment Reassembly Timeout" message. */ icmp_send(head, ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, 0); out_rcu_unlock: rcu_read_unlock(); } out: spin_unlock(&qp->q.lock); ipq_put(qp); } Commit Message: net: ip_expire() must revalidate route Commit 4a94445c9a5c (net: Use ip_route_input_noref() in input path) added a bug in IP defragmentation handling, in case timeout is fired. When a frame is defragmented, we use last skb dst field when building final skb. Its dst is valid, since we are in rcu read section. But if a timeout occurs, we take first queued fragment to build one ICMP TIME EXCEEDED message. Problem is all queued skb have weak dst pointers, since we escaped RCU critical section after their queueing. icmp_send() might dereference a now freed (and possibly reused) part of memory. Calling skb_dst_drop() and ip_route_input_noref() to revalidate route is the only possible choice. Reported-by: Denys Fedoryshchenko <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static void ip_expire(unsigned long arg) { struct ipq *qp; struct net *net; qp = container_of((struct inet_frag_queue *) arg, struct ipq, q); net = container_of(qp->q.net, struct net, ipv4.frags); spin_lock(&qp->q.lock); if (qp->q.last_in & INET_FRAG_COMPLETE) goto out; ipq_kill(qp); IP_INC_STATS_BH(net, IPSTATS_MIB_REASMTIMEOUT); IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS); if ((qp->q.last_in & INET_FRAG_FIRST_IN) && qp->q.fragments != NULL) { struct sk_buff *head = qp->q.fragments; const struct iphdr *iph; int err; rcu_read_lock(); head->dev = dev_get_by_index_rcu(net, qp->iif); if (!head->dev) goto out_rcu_unlock; /* skb dst is stale, drop it, and perform route lookup again */ skb_dst_drop(head); iph = ip_hdr(head); err = ip_route_input_noref(head, iph->daddr, iph->saddr, iph->tos, head->dev); if (err) goto out_rcu_unlock; /* * Only an end host needs to send an ICMP * "Fragment Reassembly Timeout" message, per RFC792. */ if (qp->user == IP_DEFRAG_CONNTRACK_IN && skb_rtable(head)->rt_type != RTN_LOCAL) goto out_rcu_unlock; /* Send an ICMP "Fragment Reassembly Timeout" message. */ icmp_send(head, ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, 0); out_rcu_unlock: rcu_read_unlock(); } out: spin_unlock(&qp->q.lock); ipq_put(qp); }
165,873
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ContentSuggestionsNotifierService::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterIntegerPref( prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0); registry->RegisterStringPref(kNotificationIDWithinCategory, std::string()); } Commit Message: NTP: cap number of notifications/day 1 by default; Finch-configurable. BUG=689465 Review-Url: https://codereview.chromium.org/2691023002 Cr-Commit-Position: refs/heads/master@{#450389} CWE ID: CWE-399
void ContentSuggestionsNotifierService::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterIntegerPref( prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0); registry->RegisterIntegerPref(prefs::kContentSuggestionsNotificationsSentDay, 0); registry->RegisterIntegerPref( prefs::kContentSuggestionsNotificationsSentCount, 0); registry->RegisterStringPref(kNotificationIDWithinCategory, std::string()); }
172,038
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { struct svc_rqst *rqstp; struct task_struct *task; struct svc_pool *chosen_pool; int error = 0; unsigned int state = serv->sv_nrthreads-1; int node; if (pool == NULL) { /* The -1 assumes caller has done a svc_get() */ nrservs -= (serv->sv_nrthreads-1); } else { spin_lock_bh(&pool->sp_lock); nrservs -= pool->sp_nrthreads; spin_unlock_bh(&pool->sp_lock); } /* create new threads */ while (nrservs > 0) { nrservs--; chosen_pool = choose_pool(serv, pool, &state); node = svc_pool_map_get_node(chosen_pool->sp_id); rqstp = svc_prepare_thread(serv, chosen_pool, node); if (IS_ERR(rqstp)) { error = PTR_ERR(rqstp); break; } __module_get(serv->sv_ops->svo_module); task = kthread_create_on_node(serv->sv_ops->svo_function, rqstp, node, "%s", serv->sv_name); if (IS_ERR(task)) { error = PTR_ERR(task); module_put(serv->sv_ops->svo_module); svc_exit_thread(rqstp); break; } rqstp->rq_task = task; if (serv->sv_nrpools > 1) svc_pool_map_set_cpumask(task, chosen_pool->sp_id); svc_sock_update_bufs(serv); wake_up_process(task); } /* destroy old threads */ while (nrservs < 0 && (task = choose_victim(serv, pool, &state)) != NULL) { send_sig(SIGINT, task, 1); nrservs++; } return error; } 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
svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) /* create new threads */ static int svc_start_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { struct svc_rqst *rqstp; struct task_struct *task; struct svc_pool *chosen_pool; unsigned int state = serv->sv_nrthreads-1; int node; do { nrservs--; chosen_pool = choose_pool(serv, pool, &state); node = svc_pool_map_get_node(chosen_pool->sp_id); rqstp = svc_prepare_thread(serv, chosen_pool, node); if (IS_ERR(rqstp)) return PTR_ERR(rqstp); __module_get(serv->sv_ops->svo_module); task = kthread_create_on_node(serv->sv_ops->svo_function, rqstp, node, "%s", serv->sv_name); if (IS_ERR(task)) { module_put(serv->sv_ops->svo_module); svc_exit_thread(rqstp); return PTR_ERR(task); } rqstp->rq_task = task; if (serv->sv_nrpools > 1) svc_pool_map_set_cpumask(task, chosen_pool->sp_id); svc_sock_update_bufs(serv); wake_up_process(task); } while (nrservs > 0); return 0; } /* destroy old threads */ static int svc_signal_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { struct task_struct *task; unsigned int state = serv->sv_nrthreads-1; /* destroy old threads */ do { task = choose_victim(serv, pool, &state); if (task == NULL) break; send_sig(SIGINT, task, 1); nrservs++; } while (nrservs < 0); return 0; } /* * Create or destroy enough new threads to make the number * of threads the given number. If `pool' is non-NULL, applies * only to threads in that pool, otherwise round-robins between * all pools. Caller must ensure that mutual exclusion between this and * server startup or shutdown. * * Destroying threads relies on the service threads filling in * rqstp->rq_task, which only the nfs ones do. Assumes the serv * has been created using svc_create_pooled(). * * Based on code that used to be in nfsd_svc() but tweaked * to be pool-aware. */ int svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { if (pool == NULL) { /* The -1 assumes caller has done a svc_get() */ nrservs -= (serv->sv_nrthreads-1); } else { spin_lock_bh(&pool->sp_lock); nrservs -= pool->sp_nrthreads; spin_unlock_bh(&pool->sp_lock); } if (nrservs > 0) return svc_start_kthreads(serv, pool, nrservs); if (nrservs < 0) return svc_signal_kthreads(serv, pool, nrservs); return 0; }
168,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec; guint pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; guint8 *pd; int i, hex_lines, n, caplen = 0; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return FALSE; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return FALSE; } yy = mm = dd = hr = min = sec = csec = 0; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (empty_line(line)) { break; } if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers"); return FALSE; } caplen += n; } phdr->caplen = caplen; return TRUE; } Commit Message: Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12395 Change-Id: I43b458a73b0934e9a5c2c89d34eac5a8f21a7455 Reviewed-on: https://code.wireshark.org/review/15223 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-119
parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec, pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; guint8 *pd; int i, hex_lines, n, caplen = 0; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return FALSE; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return FALSE; } yy = mm = dd = hr = min = sec = csec = 0; } if (pkt_len < 0) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: packet header has a negative packet length"); return FALSE; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (empty_line(line)) { break; } if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers"); return FALSE; } caplen += n; } phdr->caplen = caplen; return TRUE; }
167,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx, const iw_byte *d, size_t d_len) { struct iw_exif_state e; iw_uint32 ifd; if(d_len<8) return; iw_zeromem(&e,sizeof(struct iw_exif_state)); e.d = d; e.d_len = d_len; e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG; ifd = iw_get_ui32_e(&d[4],e.endian); iwjpeg_scan_exif_ifd(rctx,&e,ifd); } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125
static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx, const iw_byte *d, size_t d_len) { struct iw_exif_state e; iw_uint32 ifd; if(d_len<8) return; iw_zeromem(&e,sizeof(struct iw_exif_state)); e.d = d; e.d_len = d_len; e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG; ifd = get_exif_ui32(&e, 4); iwjpeg_scan_exif_ifd(rctx,&e,ifd); }
168,115
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool InstallablePaymentAppCrawler::CompleteAndStorePaymentWebAppInfoIfValid( const GURL& method_manifest_url, const GURL& web_app_manifest_url, std::unique_ptr<WebAppInstallationInfo> app_info) { if (app_info == nullptr) return false; if (app_info->sw_js_url.empty() || !base::IsStringUTF8(app_info->sw_js_url)) { WarnIfPossible( "The installable payment app's js url is not a non-empty UTF8 string."); return false; } if (!GURL(app_info->sw_js_url).is_valid()) { GURL absolute_url = web_app_manifest_url.Resolve(app_info->sw_js_url); if (!absolute_url.is_valid()) { WarnIfPossible( "Failed to resolve the installable payment app's js url (" + app_info->sw_js_url + ")."); return false; } app_info->sw_js_url = absolute_url.spec(); } if (!GURL(app_info->sw_scope).is_valid()) { GURL absolute_scope = web_app_manifest_url.GetWithoutFilename().Resolve(app_info->sw_scope); if (!absolute_scope.is_valid()) { WarnIfPossible( "Failed to resolve the installable payment app's registration " "scope (" + app_info->sw_scope + ")."); return false; } app_info->sw_scope = absolute_scope.spec(); } std::string error_message; if (!content::PaymentAppProvider::GetInstance()->IsValidInstallablePaymentApp( web_app_manifest_url, GURL(app_info->sw_js_url), GURL(app_info->sw_scope), &error_message)) { WarnIfPossible(error_message); return false; } if (installable_apps_.find(method_manifest_url) != installable_apps_.end()) return false; installable_apps_[method_manifest_url] = std::move(app_info); return true; } Commit Message: [Payments] Restrict just-in-time payment handler to payment method domain and its subdomains Bug: 853937 Change-Id: I148b3d96950a9d90fa362e580e9593caa6b92a36 Reviewed-on: https://chromium-review.googlesource.com/1132116 Reviewed-by: Mathieu Perreault <[email protected]> Commit-Queue: Ganggui Tang <[email protected]> Cr-Commit-Position: refs/heads/master@{#573911} CWE ID:
bool InstallablePaymentAppCrawler::CompleteAndStorePaymentWebAppInfoIfValid( const GURL& method_manifest_url, const GURL& web_app_manifest_url, std::unique_ptr<WebAppInstallationInfo> app_info) { if (app_info == nullptr) return false; if (app_info->sw_js_url.empty() || !base::IsStringUTF8(app_info->sw_js_url)) { WarnIfPossible( "The installable payment app's js url is not a non-empty UTF8 string."); return false; } if (!GURL(app_info->sw_js_url).is_valid()) { GURL absolute_url = web_app_manifest_url.Resolve(app_info->sw_js_url); if (!absolute_url.is_valid()) { WarnIfPossible( "Failed to resolve the installable payment app's js url (" + app_info->sw_js_url + ")."); return false; } if (!net::registry_controlled_domains::SameDomainOrHost( method_manifest_url, absolute_url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { WarnIfPossible("Installable payment app's js url " + absolute_url.spec() + " is not allowed for the method " + method_manifest_url.spec()); return false; } app_info->sw_js_url = absolute_url.spec(); } if (!GURL(app_info->sw_scope).is_valid()) { GURL absolute_scope = web_app_manifest_url.GetWithoutFilename().Resolve(app_info->sw_scope); if (!absolute_scope.is_valid()) { WarnIfPossible( "Failed to resolve the installable payment app's registration " "scope (" + app_info->sw_scope + ")."); return false; } if (!net::registry_controlled_domains::SameDomainOrHost( method_manifest_url, absolute_scope, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { WarnIfPossible("Installable payment app's registration scope " + absolute_scope.spec() + " is not allowed for the method " + method_manifest_url.spec()); return false; } app_info->sw_scope = absolute_scope.spec(); } std::string error_message; if (!content::PaymentAppProvider::GetInstance()->IsValidInstallablePaymentApp( web_app_manifest_url, GURL(app_info->sw_js_url), GURL(app_info->sw_scope), &error_message)) { WarnIfPossible(error_message); return false; } if (installable_apps_.find(method_manifest_url) != installable_apps_.end()) return false; installable_apps_[method_manifest_url] = std::move(app_info); return true; }
172,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind()
167,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŧтҭ] > t;" "[ƅьҍв] > b; [ωшщ] > w; [мӎ] > m;" "п > n; [єҽҿ] > e; ґ > r; ғ > f; ҫ > c;" "ұ > y; [χҳӽӿ] > x;" #if defined(OS_WIN) "ӏ > i;" #else "ӏ > l;" #endif "ԃ > d; ԍ > g; ട > s"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Add more entries to the confusability mapping U+014B (ŋ) => n U+1004 (င) => c U+100c (ဌ) => g U+1042 (၂) => j U+1054 (ၔ) => e Bug: 811117,808316 Test: components_unittests -gtest_filter=*IDN* Change-Id: I29f73c48d665bd9070050bd7f0080563635b9c63 Reviewed-on: https://chromium-review.googlesource.com/919423 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Jungshik Shin <[email protected]> Cr-Commit-Position: refs/heads/master@{#536955} CWE ID:
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); // - {U+014B (ŋ), U+043F (п)} => n // - {U+0454 (є), U+04BD (ҽ), U+04BF (ҿ), U+1054 (ၔ)} => e // - {U+04AB (ҫ), U+1004 (င)} => c // - {U+050D (ԍ), U+100c (ဌ)} => g // - U+1042 (၂) => j extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭ] > t;" "[ƅьҍв] > b; [ωшщ] > w; [мӎ] > m;" "[єҽҿၔ] > e; ґ > r; ғ > f; [ҫင] > c;" "ұ > y; [χҳӽӿ] > x;" #if defined(OS_WIN) "ӏ > i;" #else "ӏ > l;" #endif "ԃ > d; [ԍဌ] > g; ട > s; ၂ > j"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
172,731
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static grub_err_t read_foo (struct grub_disk *disk, grub_disk_addr_t sector, grub_size_t size, char *buf) { if (disk != NULL) { const int blocksize = 512; // unhardcode 512 int ret; RIOBind *iob = disk->data; if (bio) iob = bio; ret = iob->read_at (iob->io, delta+(blocksize*sector), (ut8*)buf, size*blocksize); if (ret == -1) return 1; } else eprintf ("oops. no disk\n"); return 0; // 0 is ok } Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack CWE ID: CWE-119
static grub_err_t read_foo (struct grub_disk *disk, grub_disk_addr_t sector, grub_size_t size, char *buf) { if (!disk) { eprintf ("oops. no disk\n"); return 1; } const int blocksize = 512; // TODO unhardcode 512 RIOBind *iob = disk->data; if (bio) { iob = bio; } //printf ("io %p\n", file->root->iob.io); if (iob->read_at (iob->io, delta+(blocksize*sector), (ut8*)buf, size*blocksize) == -1) { return 1; } return 0; }
168,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Instance::HandleInputEvent(const pp::InputEvent& event) { pp::InputEvent event_device_res(event); { pp::MouseInputEvent mouse_event(event); if (!mouse_event.is_null()) { pp::Point point = mouse_event.GetPosition(); pp::Point movement = mouse_event.GetMovement(); ScalePoint(device_scale_, &point); ScalePoint(device_scale_, &movement); mouse_event = pp::MouseInputEvent( this, event.GetType(), event.GetTimeStamp(), event.GetModifiers(), mouse_event.GetButton(), point, mouse_event.GetClickCount(), movement); event_device_res = mouse_event; } } if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) { pp::MouseInputEvent mouse_event(event_device_res); pp::Point pos = mouse_event.GetPosition(); EnableAutoscroll(pos); UpdateCursor(CalculateAutoscroll(pos)); return true; } else { DisableAutoscroll(); } #ifdef ENABLE_THUMBNAILS if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE) thumbnails_.SlideOut(); if (thumbnails_.HandleEvent(event_device_res)) return true; #endif if (toolbar_->HandleEvent(event_device_res)) return true; #ifdef ENABLE_THUMBNAILS if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) { pp::MouseInputEvent mouse_event(event); pp::Point pt = mouse_event.GetPosition(); pp::Rect v_scrollbar_rc; v_scrollbar_->GetLocation(&v_scrollbar_rc); if (v_scrollbar_rc.Contains(pt) && (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) { thumbnails_.SlideIn(); } if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() && !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) && !thumbnails_.rect().Contains(pt)) { thumbnails_.SlideOut(); } } #endif pp::InputEvent offset_event(event_device_res); bool try_engine_first = true; switch (offset_event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: case PP_INPUTEVENT_TYPE_MOUSEUP: case PP_INPUTEVENT_TYPE_MOUSEMOVE: case PP_INPUTEVENT_TYPE_MOUSEENTER: case PP_INPUTEVENT_TYPE_MOUSELEAVE: { pp::MouseInputEvent mouse_event(event_device_res); pp::MouseInputEvent mouse_event_dip(event); pp::Point point = mouse_event.GetPosition(); point.set_x(point.x() - available_area_.x()); offset_event = pp::MouseInputEvent( this, event.GetType(), event.GetTimeStamp(), event.GetModifiers(), mouse_event.GetButton(), point, mouse_event.GetClickCount(), mouse_event.GetMovement()); if (!engine_->IsSelecting()) { if (!IsOverlayScrollbar() && !available_area_.Contains(mouse_event.GetPosition())) { try_engine_first = false; } else if (IsOverlayScrollbar()) { pp::Rect temp; if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) && temp.Contains(mouse_event_dip.GetPosition())) || (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) && temp.Contains(mouse_event_dip.GetPosition()))) { try_engine_first = false; } } } break; } default: break; } if (try_engine_first && engine_->HandleEvent(offset_event)) return true; if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) { pp::KeyboardInputEvent keyboard_event(event); bool no_h_scrollbar = !h_scrollbar_.get(); uint32_t key_code = keyboard_event.GetKeyCode(); bool page_down = no_h_scrollbar && key_code == ui::VKEY_RIGHT; bool page_up = no_h_scrollbar && key_code == ui::VKEY_LEFT; if (zoom_mode_ == ZOOM_FIT_TO_PAGE) { bool has_shift = keyboard_event.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY; bool key_is_space = key_code == ui::VKEY_SPACE; page_down |= key_is_space || key_code == ui::VKEY_NEXT; page_up |= (key_is_space && has_shift) || (key_code == ui::VKEY_PRIOR); } if (page_down) { int page = engine_->GetFirstVisiblePage(); if (engine_->GetPageRect(page).bottom() * zoom_ <= v_scrollbar_->GetValue()) page++; ScrollToPage(page + 1); UpdateCursor(PP_CURSORTYPE_POINTER); return true; } else if (page_up) { int page = engine_->GetFirstVisiblePage(); if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue()) page--; ScrollToPage(page); UpdateCursor(PP_CURSORTYPE_POINTER); return true; } } if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) { UpdateCursor(PP_CURSORTYPE_POINTER); return true; } if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) { UpdateCursor(PP_CURSORTYPE_POINTER); return true; } if (timer_pending_ && (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP || event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) { timer_factory_.CancelAll(); timer_pending_ = false; } else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && engine_->IsSelecting()) { bool set_timer = false; pp::MouseInputEvent mouse_event(event); if (v_scrollbar_.get() && (mouse_event.GetPosition().y() <= 0 || mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) { v_scrollbar_->ScrollBy( PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1); set_timer = true; } if (h_scrollbar_.get() && (mouse_event.GetPosition().x() <= 0 || mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) { h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE, mouse_event.GetPosition().x() >= 0 ? 1: -1); set_timer = true; } if (set_timer) { last_mouse_event_ = pp::MouseInputEvent(event); pp::CompletionCallback callback = timer_factory_.NewCallback(&Instance::OnTimerFired); pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback); timer_pending_ = true; } } if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN && event.GetModifiers() & kDefaultKeyModifier) { pp::KeyboardInputEvent keyboard_event(event); switch (keyboard_event.GetKeyCode()) { case 'A': engine_->SelectAll(); return true; } } return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN); } Commit Message: Let PDFium handle event when there is not yet a visible page. Speculative fix for 415307. CF will confirm. The stack trace for that bug indicates an attempt to index by -1, which is consistent with no visible page. BUG=415307 Review URL: https://codereview.chromium.org/560133004 Cr-Commit-Position: refs/heads/master@{#295421} CWE ID: CWE-119
bool Instance::HandleInputEvent(const pp::InputEvent& event) { pp::InputEvent event_device_res(event); { pp::MouseInputEvent mouse_event(event); if (!mouse_event.is_null()) { pp::Point point = mouse_event.GetPosition(); pp::Point movement = mouse_event.GetMovement(); ScalePoint(device_scale_, &point); ScalePoint(device_scale_, &movement); mouse_event = pp::MouseInputEvent( this, event.GetType(), event.GetTimeStamp(), event.GetModifiers(), mouse_event.GetButton(), point, mouse_event.GetClickCount(), movement); event_device_res = mouse_event; } } if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) { pp::MouseInputEvent mouse_event(event_device_res); pp::Point pos = mouse_event.GetPosition(); EnableAutoscroll(pos); UpdateCursor(CalculateAutoscroll(pos)); return true; } else { DisableAutoscroll(); } #ifdef ENABLE_THUMBNAILS if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE) thumbnails_.SlideOut(); if (thumbnails_.HandleEvent(event_device_res)) return true; #endif if (toolbar_->HandleEvent(event_device_res)) return true; #ifdef ENABLE_THUMBNAILS if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) { pp::MouseInputEvent mouse_event(event); pp::Point pt = mouse_event.GetPosition(); pp::Rect v_scrollbar_rc; v_scrollbar_->GetLocation(&v_scrollbar_rc); if (v_scrollbar_rc.Contains(pt) && (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) { thumbnails_.SlideIn(); } if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() && !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) && !thumbnails_.rect().Contains(pt)) { thumbnails_.SlideOut(); } } #endif pp::InputEvent offset_event(event_device_res); bool try_engine_first = true; switch (offset_event.GetType()) { case PP_INPUTEVENT_TYPE_MOUSEDOWN: case PP_INPUTEVENT_TYPE_MOUSEUP: case PP_INPUTEVENT_TYPE_MOUSEMOVE: case PP_INPUTEVENT_TYPE_MOUSEENTER: case PP_INPUTEVENT_TYPE_MOUSELEAVE: { pp::MouseInputEvent mouse_event(event_device_res); pp::MouseInputEvent mouse_event_dip(event); pp::Point point = mouse_event.GetPosition(); point.set_x(point.x() - available_area_.x()); offset_event = pp::MouseInputEvent( this, event.GetType(), event.GetTimeStamp(), event.GetModifiers(), mouse_event.GetButton(), point, mouse_event.GetClickCount(), mouse_event.GetMovement()); if (!engine_->IsSelecting()) { if (!IsOverlayScrollbar() && !available_area_.Contains(mouse_event.GetPosition())) { try_engine_first = false; } else if (IsOverlayScrollbar()) { pp::Rect temp; if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) && temp.Contains(mouse_event_dip.GetPosition())) || (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) && temp.Contains(mouse_event_dip.GetPosition()))) { try_engine_first = false; } } } break; } default: break; } if (try_engine_first && engine_->HandleEvent(offset_event)) return true; if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) { pp::KeyboardInputEvent keyboard_event(event); bool no_h_scrollbar = !h_scrollbar_.get(); uint32_t key_code = keyboard_event.GetKeyCode(); bool page_down = no_h_scrollbar && key_code == ui::VKEY_RIGHT; bool page_up = no_h_scrollbar && key_code == ui::VKEY_LEFT; if (zoom_mode_ == ZOOM_FIT_TO_PAGE) { bool has_shift = keyboard_event.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY; bool key_is_space = key_code == ui::VKEY_SPACE; page_down |= key_is_space || key_code == ui::VKEY_NEXT; page_up |= (key_is_space && has_shift) || (key_code == ui::VKEY_PRIOR); } if (page_down) { int page = engine_->GetFirstVisiblePage(); if (page == -1) return true; if (engine_->GetPageRect(page).bottom() * zoom_ <= v_scrollbar_->GetValue()) page++; ScrollToPage(page + 1); UpdateCursor(PP_CURSORTYPE_POINTER); return true; } else if (page_up) { int page = engine_->GetFirstVisiblePage(); if (page == -1) return true; if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue()) page--; ScrollToPage(page); UpdateCursor(PP_CURSORTYPE_POINTER); return true; } } if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) { UpdateCursor(PP_CURSORTYPE_POINTER); return true; } if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) { UpdateCursor(PP_CURSORTYPE_POINTER); return true; } if (timer_pending_ && (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP || event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) { timer_factory_.CancelAll(); timer_pending_ = false; } else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && engine_->IsSelecting()) { bool set_timer = false; pp::MouseInputEvent mouse_event(event); if (v_scrollbar_.get() && (mouse_event.GetPosition().y() <= 0 || mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) { v_scrollbar_->ScrollBy( PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1); set_timer = true; } if (h_scrollbar_.get() && (mouse_event.GetPosition().x() <= 0 || mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) { h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE, mouse_event.GetPosition().x() >= 0 ? 1: -1); set_timer = true; } if (set_timer) { last_mouse_event_ = pp::MouseInputEvent(event); pp::CompletionCallback callback = timer_factory_.NewCallback(&Instance::OnTimerFired); pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback); timer_pending_ = true; } } if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN && event.GetModifiers() & kDefaultKeyModifier) { pp::KeyboardInputEvent keyboard_event(event); switch (keyboard_event.GetKeyCode()) { case 'A': engine_->SelectAll(); return true; } } return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN); }
171,640
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) { if (mNativeWindow != NULL && portIndex == kPortIndexOutput) { return allocateOutputBuffersFromNativeWindow(); } if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) { ALOGE("protected output buffers must be stent to an ANativeWindow"); return PERMISSION_DENIED; } status_t err = OK; if ((mFlags & kStoreMetaDataInVideoBuffers) && portIndex == kPortIndexInput) { err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE); if (err != OK) { ALOGE("Storing meta data in video buffers is not supported"); return err; } } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } CODEC_LOGV("allocating %u buffers of size %u on %s port", def.nBufferCountActual, def.nBufferSize, portIndex == kPortIndexInput ? "input" : "output"); if (def.nBufferSize != 0 && def.nBufferCountActual > SIZE_MAX / def.nBufferSize) { return BAD_VALUE; } size_t totalSize = def.nBufferCountActual * def.nBufferSize; mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec"); for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) { sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize); CHECK(mem.get() != NULL); BufferInfo info; info.mData = NULL; info.mSize = def.nBufferSize; IOMX::buffer_id buffer; if (portIndex == kPortIndexInput && ((mQuirks & kRequiresAllocateBufferOnInputPorts) || (mFlags & kUseSecureInputBuffers))) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else if (portIndex == kPortIndexOutput && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else { err = mOMX->useBuffer(mNode, portIndex, mem, &buffer, mem->size()); } if (err != OK) { ALOGE("allocate_buffer_with_backup failed"); return err; } if (mem != NULL) { info.mData = mem->pointer(); } info.mBuffer = buffer; info.mStatus = OWNED_BY_US; info.mMem = mem; info.mMediaBuffer = NULL; if (portIndex == kPortIndexOutput) { LOG_ALWAYS_FATAL_IF((mOMXLivesLocally && (mQuirks & kRequiresAllocateBufferOnOutputPorts) && (mQuirks & kDefersOutputBufferAllocation)), "allocateBuffersOnPort cannot defer buffer allocation"); info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize); info.mMediaBuffer->setObserver(this); } mPortBuffers[portIndex].push(info); CODEC_LOGV("allocated buffer %u on %s port", buffer, portIndex == kPortIndexInput ? "input" : "output"); } if (portIndex == kPortIndexOutput) { sp<MetaData> meta = mSource->getFormat(); int32_t delay = 0; if (!meta->findInt32(kKeyEncoderDelay, &delay)) { delay = 0; } int32_t padding = 0; if (!meta->findInt32(kKeyEncoderPadding, &padding)) { padding = 0; } int32_t numchannels = 0; if (delay + padding) { if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) { size_t frameSize = numchannels * sizeof(int16_t); if (mSkipCutBuffer != NULL) { size_t prevbuffersize = mSkipCutBuffer->size(); if (prevbuffersize != 0) { ALOGW("Replacing SkipCutBuffer holding %zu bytes", prevbuffersize); } } mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize); } } } if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) { Vector<MediaBuffer *> buffers; for (size_t i = 0; i < def.nBufferCountActual; ++i) { const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i); MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize); buffers.push(mbuf); } status_t err = mSource->setBuffers(buffers); if (err != OK) { for (size_t i = 0; i < def.nBufferCountActual; ++i) { buffers.editItemAt(i)->release(); } buffers.clear(); CODEC_LOGE( "Codec requested to use secure input buffers but " "upstream source didn't support that."); return err; } } return OK; } Commit Message: OMXCodec: check IMemory::pointer() before using allocation Bug: 29421811 Change-Id: I0a73ba12bae4122f1d89fc92e5ea4f6a96cd1ed1 CWE ID: CWE-284
status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) { if (mNativeWindow != NULL && portIndex == kPortIndexOutput) { return allocateOutputBuffersFromNativeWindow(); } if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) { ALOGE("protected output buffers must be stent to an ANativeWindow"); return PERMISSION_DENIED; } status_t err = OK; if ((mFlags & kStoreMetaDataInVideoBuffers) && portIndex == kPortIndexInput) { err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE); if (err != OK) { ALOGE("Storing meta data in video buffers is not supported"); return err; } } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } CODEC_LOGV("allocating %u buffers of size %u on %s port", def.nBufferCountActual, def.nBufferSize, portIndex == kPortIndexInput ? "input" : "output"); if (def.nBufferSize != 0 && def.nBufferCountActual > SIZE_MAX / def.nBufferSize) { return BAD_VALUE; } size_t totalSize = def.nBufferCountActual * def.nBufferSize; mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec"); for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) { sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize); if (mem == NULL || mem->pointer() == NULL) { return NO_MEMORY; } BufferInfo info; info.mData = NULL; info.mSize = def.nBufferSize; IOMX::buffer_id buffer; if (portIndex == kPortIndexInput && ((mQuirks & kRequiresAllocateBufferOnInputPorts) || (mFlags & kUseSecureInputBuffers))) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else if (portIndex == kPortIndexOutput && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else { err = mOMX->useBuffer(mNode, portIndex, mem, &buffer, mem->size()); } if (err != OK) { ALOGE("allocate_buffer_with_backup failed"); return err; } if (mem != NULL) { info.mData = mem->pointer(); } info.mBuffer = buffer; info.mStatus = OWNED_BY_US; info.mMem = mem; info.mMediaBuffer = NULL; if (portIndex == kPortIndexOutput) { LOG_ALWAYS_FATAL_IF((mOMXLivesLocally && (mQuirks & kRequiresAllocateBufferOnOutputPorts) && (mQuirks & kDefersOutputBufferAllocation)), "allocateBuffersOnPort cannot defer buffer allocation"); info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize); info.mMediaBuffer->setObserver(this); } mPortBuffers[portIndex].push(info); CODEC_LOGV("allocated buffer %u on %s port", buffer, portIndex == kPortIndexInput ? "input" : "output"); } if (portIndex == kPortIndexOutput) { sp<MetaData> meta = mSource->getFormat(); int32_t delay = 0; if (!meta->findInt32(kKeyEncoderDelay, &delay)) { delay = 0; } int32_t padding = 0; if (!meta->findInt32(kKeyEncoderPadding, &padding)) { padding = 0; } int32_t numchannels = 0; if (delay + padding) { if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) { size_t frameSize = numchannels * sizeof(int16_t); if (mSkipCutBuffer != NULL) { size_t prevbuffersize = mSkipCutBuffer->size(); if (prevbuffersize != 0) { ALOGW("Replacing SkipCutBuffer holding %zu bytes", prevbuffersize); } } mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize); } } } if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) { Vector<MediaBuffer *> buffers; for (size_t i = 0; i < def.nBufferCountActual; ++i) { const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i); MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize); buffers.push(mbuf); } status_t err = mSource->setBuffers(buffers); if (err != OK) { for (size_t i = 0; i < def.nBufferCountActual; ++i) { buffers.editItemAt(i)->release(); } buffers.clear(); CODEC_LOGE( "Codec requested to use secure input buffers but " "upstream source didn't support that."); return err; } } return OK; }
173,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct dst_entry *inet6_csk_route_req(const struct sock *sk, struct flowi6 *fl6, const struct request_sock *req, u8 proto) { struct inet_request_sock *ireq = inet_rsk(req); const struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = proto; fl6->daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(fl6, np->opt, &final); fl6->saddr = ireq->ir_v6_loc_addr; fl6->flowi6_oif = ireq->ir_iif; fl6->flowi6_mark = ireq->ir_mark; fl6->fl6_dport = ireq->ir_rmt_port; fl6->fl6_sport = htons(ireq->ir_num); security_req_classify_flow(req, flowi6_to_flowi(fl6)); dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (IS_ERR(dst)) return NULL; return dst; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
struct dst_entry *inet6_csk_route_req(const struct sock *sk, struct flowi6 *fl6, const struct request_sock *req, u8 proto) { struct inet_request_sock *ireq = inet_rsk(req); const struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = proto; fl6->daddr = ireq->ir_v6_rmt_addr; rcu_read_lock(); final_p = fl6_update_dst(fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); fl6->saddr = ireq->ir_v6_loc_addr; fl6->flowi6_oif = ireq->ir_iif; fl6->flowi6_mark = ireq->ir_mark; fl6->fl6_dport = ireq->ir_rmt_port; fl6->fl6_sport = htons(ireq->ir_num); security_req_classify_flow(req, flowi6_to_flowi(fl6)); dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (IS_ERR(dst)) return NULL; return dst; }
167,332
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutofillManager::OnQueryFormFieldAutofillImpl( int query_id, const FormData& form, const FormFieldData& field, const gfx::RectF& transformed_box, bool autoselect_first_suggestion) { external_delegate_->OnQuery(query_id, form, field, transformed_box); std::vector<Suggestion> suggestions; SuggestionsContext context; GetAvailableSuggestions(form, field, &suggestions, &context); if (context.is_autofill_available) { switch (context.suppress_reason) { case SuppressReason::kNotSuppressed: break; case SuppressReason::kCreditCardsAblation: enable_ablation_logging_ = true; autocomplete_history_manager_->CancelPendingQuery(); external_delegate_->OnSuggestionsReturned(query_id, suggestions, autoselect_first_suggestion); return; case SuppressReason::kAutocompleteOff: return; } if (!suggestions.empty()) { if (context.is_filling_credit_card) { AutofillMetrics::LogIsQueriedCreditCardFormSecure( context.is_context_secure); } if (!has_logged_address_suggestions_count_ && !context.section_has_autofilled_field) { AutofillMetrics::LogAddressSuggestionsCount(suggestions.size()); has_logged_address_suggestions_count_ = true; } } } if (suggestions.empty() && !ShouldShowCreditCardSigninPromo(form, field) && field.should_autocomplete && !(context.focused_field && (IsCreditCardExpirationType( context.focused_field->Type().GetStorableType()) || context.focused_field->Type().html_type() == HTML_TYPE_UNRECOGNIZED || context.focused_field->Type().GetStorableType() == CREDIT_CARD_NUMBER || context.focused_field->Type().GetStorableType() == CREDIT_CARD_VERIFICATION_CODE))) { autocomplete_history_manager_->OnGetAutocompleteSuggestions( query_id, field.name, field.value, field.form_control_type); return; } autocomplete_history_manager_->CancelPendingQuery(); external_delegate_->OnSuggestionsReturned(query_id, suggestions, autoselect_first_suggestion, context.is_all_server_suggestions); } Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections. Since Autofill does not fill field by field anymore, this simplifying and deduping of suggestions is not useful anymore. Bug: 858820 Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b Reviewed-on: https://chromium-review.googlesource.com/1128255 Reviewed-by: Roger McFarlane <[email protected]> Commit-Queue: Sebastien Seguin-Gagnon <[email protected]> Cr-Commit-Position: refs/heads/master@{#573315} CWE ID:
void AutofillManager::OnQueryFormFieldAutofillImpl( int query_id, const FormData& form, const FormFieldData& field, const gfx::RectF& transformed_box, bool autoselect_first_suggestion) { external_delegate_->OnQuery(query_id, form, field, transformed_box); std::vector<Suggestion> suggestions; SuggestionsContext context; GetAvailableSuggestions(form, field, &suggestions, &context); if (context.is_autofill_available) { switch (context.suppress_reason) { case SuppressReason::kNotSuppressed: break; case SuppressReason::kCreditCardsAblation: enable_ablation_logging_ = true; autocomplete_history_manager_->CancelPendingQuery(); external_delegate_->OnSuggestionsReturned(query_id, suggestions, autoselect_first_suggestion); return; case SuppressReason::kAutocompleteOff: return; } if (!suggestions.empty()) { if (context.is_filling_credit_card) { AutofillMetrics::LogIsQueriedCreditCardFormSecure( context.is_context_secure); } if (!has_logged_address_suggestions_count_) { AutofillMetrics::LogAddressSuggestionsCount(suggestions.size()); has_logged_address_suggestions_count_ = true; } } } if (suggestions.empty() && !ShouldShowCreditCardSigninPromo(form, field) && field.should_autocomplete && !(context.focused_field && (IsCreditCardExpirationType( context.focused_field->Type().GetStorableType()) || context.focused_field->Type().html_type() == HTML_TYPE_UNRECOGNIZED || context.focused_field->Type().GetStorableType() == CREDIT_CARD_NUMBER || context.focused_field->Type().GetStorableType() == CREDIT_CARD_VERIFICATION_CODE))) { autocomplete_history_manager_->OnGetAutocompleteSuggestions( query_id, field.name, field.value, field.form_control_type); return; } autocomplete_history_manager_->CancelPendingQuery(); external_delegate_->OnSuggestionsReturned(query_id, suggestions, autoselect_first_suggestion, context.is_all_server_suggestions); }
173,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) { SetState(STATE_NORMAL); ui::MouseEvent synthetic_event( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); NotifyClick(synthetic_event); return true; } Commit Message: Custom buttons should only handle accelerators when focused. BUG=541415 Review URL: https://codereview.chromium.org/1437523005 Cr-Commit-Position: refs/heads/master@{#360130} CWE ID: CWE-254
bool CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) { // Should only handle accelerators when active. However, only top level // widgets can be active, so for child widgets check if they are focused // instead. if ((IsChildWidget() && !FocusInChildWidget()) || (!IsChildWidget() && !GetWidget()->IsActive())) { return false; } SetState(STATE_NORMAL); ui::MouseEvent synthetic_event( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); NotifyClick(synthetic_event); return true; }
172,236
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx) { struct srp_tsk_mgmt *srp_tsk; struct se_cmd *cmd; struct se_session *sess = ch->sess; uint64_t unpacked_lun; uint32_t tag = 0; int tcm_tmr; int rc; BUG_ON(!send_ioctx); srp_tsk = recv_ioctx->ioctx.buf; cmd = &send_ioctx->cmd; pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld" " cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func, srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess); srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT); send_ioctx->cmd.tag = srp_tsk->tag; tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func); if (tcm_tmr < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED; goto fail; } unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun, sizeof(srp_tsk->lun)); if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) { rc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag); if (rc < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_DOES_NOT_EXIST; goto fail; } tag = srp_tsk->task_tag; } rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun, srp_tsk, tcm_tmr, GFP_KERNEL, tag, TARGET_SCF_ACK_KREF); if (rc != 0) { send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED; goto fail; } return; fail: transport_send_check_condition_and_sense(cmd, 0, 0); // XXX: } Commit Message: IB/srpt: Simplify srpt_handle_tsk_mgmt() Let the target core check task existence instead of the SRP target driver. Additionally, let the target core check the validity of the task management request instead of the ib_srpt driver. This patch fixes the following kernel crash: BUG: unable to handle kernel NULL pointer dereference at 0000000000000001 IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt] Oops: 0002 [#1] SMP Call Trace: [<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt] [<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt] [<ffffffff8109726f>] kthread+0xcf/0xe0 [<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0 Signed-off-by: Bart Van Assche <[email protected]> Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr") Tested-by: Alex Estrin <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Cc: Nicholas Bellinger <[email protected]> Cc: Sagi Grimberg <[email protected]> Cc: stable <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-476
static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx) { struct srp_tsk_mgmt *srp_tsk; struct se_cmd *cmd; struct se_session *sess = ch->sess; uint64_t unpacked_lun; int tcm_tmr; int rc; BUG_ON(!send_ioctx); srp_tsk = recv_ioctx->ioctx.buf; cmd = &send_ioctx->cmd; pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld" " cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func, srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess); srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT); send_ioctx->cmd.tag = srp_tsk->tag; tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func); unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun, sizeof(srp_tsk->lun)); rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun, srp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag, TARGET_SCF_ACK_KREF); if (rc != 0) { send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED; goto fail; } return; fail: transport_send_check_condition_and_sense(cmd, 0, 0); // XXX: }
167,000
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebMediaPlayerMS::DidGetOpaqueResponseFromServiceWorker() const { DCHECK(thread_checker_.CalledOnValidThread()); return false; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
bool WebMediaPlayerMS::DidGetOpaqueResponseFromServiceWorker() const { bool WebMediaPlayerMS::WouldTaintOrigin() const { DCHECK(thread_checker_.CalledOnValidThread()); return false; }
172,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltStrPaddingFunction (xmlXPathParserContextPtr ctxt, int nargs) { int number, str_len = 0; xmlChar *str = NULL, *ret = NULL, *tmp; if ((nargs < 1) || (nargs > 2)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 2) { str = xmlXPathPopString(ctxt); str_len = xmlUTF8Strlen(str); } if (str_len == 0) { if (str != NULL) xmlFree(str); str = xmlStrdup((const xmlChar *) " "); str_len = 1; } number = (int) xmlXPathPopNumber(ctxt); if (number <= 0) { xmlXPathReturnEmptyString(ctxt); xmlFree(str); return; } while (number >= str_len) { ret = xmlStrncat(ret, str, str_len); number -= str_len; } tmp = xmlUTF8Strndup (str, number); ret = xmlStrcat(ret, tmp); if (tmp != NULL) xmlFree (tmp); xmlXPathReturnString(ctxt, ret); if (str != NULL) xmlFree(str); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltStrPaddingFunction (xmlXPathParserContextPtr ctxt, int nargs) { int number, str_len = 0, str_size = 0; xmlChar *str = NULL, *ret = NULL; if ((nargs < 1) || (nargs > 2)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 2) { str = xmlXPathPopString(ctxt); str_len = xmlUTF8Strlen(str); str_size = xmlStrlen(str); } if (str_len == 0) { if (str != NULL) xmlFree(str); str = xmlStrdup((const xmlChar *) " "); str_len = 1; str_size = 1; } number = (int) xmlXPathPopNumber(ctxt); if (number <= 0) { xmlXPathReturnEmptyString(ctxt); xmlFree(str); return; } while (number >= str_len) { ret = xmlStrncat(ret, str, str_size); number -= str_len; } if (number > 0) { str_size = xmlUTF8Strsize(str, number); ret = xmlStrncat(ret, str, str_size); } xmlXPathReturnString(ctxt, ret); if (str != NULL) xmlFree(str); }
173,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1608 CWE ID: CWE-125
MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); }
169,605
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DirectoryEntrySync::removeRecursively(ExceptionState& exceptionState) { RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create(); m_fileSystem->removeRecursively(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 DirectoryEntrySync::removeRecursively(ExceptionState& exceptionState) { VoidSyncCallbackHelper* helper = VoidSyncCallbackHelper::create(); m_fileSystem->removeRecursively(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); }
171,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain <= 0) { /* 2.0.34: EOF is incorrect. We use 0 for * errors and EOF, just like fileGetbuf, * which is a simple fread() wrapper. * TBB. Original bug report: Daniel Cowgill. */ return 0; /* NOT EOF */ } rlen = remain; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; } 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 [email protected]. CVE-2016-6911 CWE ID: CWE-125
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; if (dp->pos < 0 || dp->pos >= dp->realSize) { return 0; } remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain <= 0) { return 0; } rlen = remain; } if (dp->pos + rlen > dp->realSize) { rlen = dp->realSize - dp->pos; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; }
168,821
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) { const xmlChar *elemName; const xmlChar *attrName; xmlEnumerationPtr tree; if (CMP9(CUR_PTR, '<', '!', 'A', 'T', 'T', 'L', 'I', 'S', 'T')) { xmlParserInputPtr input = ctxt->input; SKIP(9); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '<!ATTLIST'\n"); } SKIP_BLANKS; elemName = xmlParseName(ctxt); if (elemName == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "ATTLIST: no name for Element\n"); return; } SKIP_BLANKS; GROW; while (RAW != '>') { const xmlChar *check = CUR_PTR; int type; int def; xmlChar *defaultValue = NULL; GROW; tree = NULL; attrName = xmlParseName(ctxt); if (attrName == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "ATTLIST: no name for Attribute\n"); break; } GROW; if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute name\n"); break; } SKIP_BLANKS; type = xmlParseAttributeType(ctxt, &tree); if (type <= 0) { break; } GROW; if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute type\n"); if (tree != NULL) xmlFreeEnumeration(tree); break; } SKIP_BLANKS; def = xmlParseDefaultDecl(ctxt, &defaultValue); if (def <= 0) { if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL)) xmlAttrNormalizeSpace(defaultValue, defaultValue); GROW; if (RAW != '>') { if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute default value\n"); if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } SKIP_BLANKS; } if (check == CUR_PTR) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "in xmlParseAttributeListDecl\n"); if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->attributeDecl != NULL)) ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName, type, def, defaultValue, tree); else if (tree != NULL) xmlFreeEnumeration(tree); if ((ctxt->sax2) && (defaultValue != NULL) && (def != XML_ATTRIBUTE_IMPLIED) && (def != XML_ATTRIBUTE_REQUIRED)) { xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue); } if (ctxt->sax2) { xmlAddSpecialAttr(ctxt, elemName, attrName, type); } if (defaultValue != NULL) xmlFree(defaultValue); GROW; } if (RAW == '>') { if (input != ctxt->input) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Attribute list declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; } } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) { const xmlChar *elemName; const xmlChar *attrName; xmlEnumerationPtr tree; if (CMP9(CUR_PTR, '<', '!', 'A', 'T', 'T', 'L', 'I', 'S', 'T')) { xmlParserInputPtr input = ctxt->input; SKIP(9); if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after '<!ATTLIST'\n"); } SKIP_BLANKS; elemName = xmlParseName(ctxt); if (elemName == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "ATTLIST: no name for Element\n"); return; } SKIP_BLANKS; GROW; while ((RAW != '>') && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; int type; int def; xmlChar *defaultValue = NULL; GROW; tree = NULL; attrName = xmlParseName(ctxt); if (attrName == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "ATTLIST: no name for Attribute\n"); break; } GROW; if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute name\n"); break; } SKIP_BLANKS; type = xmlParseAttributeType(ctxt, &tree); if (type <= 0) { break; } GROW; if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute type\n"); if (tree != NULL) xmlFreeEnumeration(tree); break; } SKIP_BLANKS; def = xmlParseDefaultDecl(ctxt, &defaultValue); if (def <= 0) { if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL)) xmlAttrNormalizeSpace(defaultValue, defaultValue); GROW; if (RAW != '>') { if (!IS_BLANK_CH(CUR)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after the attribute default value\n"); if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } SKIP_BLANKS; } if (check == CUR_PTR) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "in xmlParseAttributeListDecl\n"); if (defaultValue != NULL) xmlFree(defaultValue); if (tree != NULL) xmlFreeEnumeration(tree); break; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->attributeDecl != NULL)) ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName, type, def, defaultValue, tree); else if (tree != NULL) xmlFreeEnumeration(tree); if ((ctxt->sax2) && (defaultValue != NULL) && (def != XML_ATTRIBUTE_IMPLIED) && (def != XML_ATTRIBUTE_REQUIRED)) { xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue); } if (ctxt->sax2) { xmlAddSpecialAttr(ctxt, elemName, attrName, type); } if (defaultValue != NULL) xmlFree(defaultValue); GROW; } if (RAW == '>') { if (input != ctxt->input) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Attribute list declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; } } }
171,272
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void inet6_destroy_sock(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct ipv6_txoptions *opt; /* Release rx options */ skb = xchg(&np->pktoptions, NULL); if (skb) kfree_skb(skb); skb = xchg(&np->rxpmtu, NULL); if (skb) kfree_skb(skb); /* Free flowlabels */ fl6_free_socklist(sk); /* Free tx options */ opt = xchg(&np->opt, NULL); if (opt) sock_kfree_s(sk, opt, opt->tot_len); } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
void inet6_destroy_sock(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct ipv6_txoptions *opt; /* Release rx options */ skb = xchg(&np->pktoptions, NULL); if (skb) kfree_skb(skb); skb = xchg(&np->rxpmtu, NULL); if (skb) kfree_skb(skb); /* Free flowlabels */ fl6_free_socklist(sk); /* Free tx options */ opt = xchg((__force struct ipv6_txoptions **)&np->opt, NULL); if (opt) { atomic_sub(opt->tot_len, &sk->sk_omem_alloc); txopt_put(opt); } }
167,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PreconnectManager::Start(const GURL& url, std::vector<PreconnectRequest> requests) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const std::string host = url.host(); if (preresolve_info_.find(host) != preresolve_info_.end()) return; auto iterator_and_whether_inserted = preresolve_info_.emplace( host, std::make_unique<PreresolveInfo>(url, requests.size())); PreresolveInfo* info = iterator_and_whether_inserted.first->second.get(); for (auto request_it = requests.begin(); request_it != requests.end(); ++request_it) { DCHECK(request_it->origin.GetOrigin() == request_it->origin); PreresolveJobId job_id = preresolve_jobs_.Add( std::make_unique<PreresolveJob>(std::move(*request_it), info)); queued_jobs_.push_back(job_id); } TryToLaunchPreresolveJobs(); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PreconnectManager::Start(const GURL& url, std::vector<PreconnectRequest> requests) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const std::string host = url.host(); if (preresolve_info_.find(host) != preresolve_info_.end()) return; auto iterator_and_whether_inserted = preresolve_info_.emplace( host, std::make_unique<PreresolveInfo>(url, requests.size())); PreresolveInfo* info = iterator_and_whether_inserted.first->second.get(); for (auto request_it = requests.begin(); request_it != requests.end(); ++request_it) { PreresolveJobId job_id = preresolve_jobs_.Add( std::make_unique<PreresolveJob>(std::move(*request_it), info)); queued_jobs_.push_back(job_id); } TryToLaunchPreresolveJobs(); }
172,377
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } Commit Message: CWE ID: CWE-310
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *buf_in=NULL; int ret= -1,i,inl; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
164,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void calc_coeff(double mu[4], const int index[4], int prefilter, double r2, double mul) { double mul2 = mul * mul, mul3 = mul2 * mul; double kernel[] = { (5204 + 2520 * mul + 1092 * mul2 + 3280 * mul3) / 12096, (2943 - 210 * mul - 273 * mul2 - 2460 * mul3) / 12096, ( 486 - 924 * mul - 546 * mul2 + 984 * mul3) / 12096, ( 17 - 126 * mul + 273 * mul2 - 164 * mul3) / 12096, }; double mat_freq[13]; memcpy(mat_freq, kernel, sizeof(kernel)); memset(mat_freq + 4, 0, sizeof(mat_freq) - sizeof(kernel)); int n = 6; coeff_filter(mat_freq, n, kernel); for (int k = 0; k < 2 * prefilter; ++k) coeff_blur121(mat_freq, ++n); double vec_freq[13]; n = index[3] + prefilter + 3; calc_gauss(vec_freq, n, r2); memset(vec_freq + n + 1, 0, sizeof(vec_freq) - (n + 1) * sizeof(vec_freq[0])); n -= 3; coeff_filter(vec_freq, n, kernel); for (int k = 0; k < prefilter; ++k) coeff_blur121(vec_freq, --n); double mat[4][4]; calc_matrix(mat, mat_freq, index); double vec[4]; for (int i = 0; i < 4; ++i) vec[i] = mat_freq[0] - mat_freq[index[i]] - vec_freq[0] + vec_freq[index[i]]; for (int i = 0; i < 4; ++i) { double res = 0; for (int j = 0; j < 4; ++j) res += mat[i][j] * vec[j]; mu[i] = FFMAX(0, res); } } Commit Message: Fix blur coefficient calculation buffer overflow Found by fuzzer test case id:000082,sig:11,src:002579,op:havoc,rep:8. Correctness should be checked, but this fixes the overflow for good. CWE ID: CWE-119
static void calc_coeff(double mu[4], const int index[4], int prefilter, double r2, double mul) { double mul2 = mul * mul, mul3 = mul2 * mul; double kernel[] = { (5204 + 2520 * mul + 1092 * mul2 + 3280 * mul3) / 12096, (2943 - 210 * mul - 273 * mul2 - 2460 * mul3) / 12096, ( 486 - 924 * mul - 546 * mul2 + 984 * mul3) / 12096, ( 17 - 126 * mul + 273 * mul2 - 164 * mul3) / 12096, }; double mat_freq[14]; memcpy(mat_freq, kernel, sizeof(kernel)); memset(mat_freq + 4, 0, sizeof(mat_freq) - sizeof(kernel)); int n = 6; coeff_filter(mat_freq, n, kernel); for (int k = 0; k < 2 * prefilter; ++k) coeff_blur121(mat_freq, ++n); double vec_freq[13]; n = index[3] + prefilter + 3; calc_gauss(vec_freq, n, r2); memset(vec_freq + n + 1, 0, sizeof(vec_freq) - (n + 1) * sizeof(vec_freq[0])); n -= 3; coeff_filter(vec_freq, n, kernel); for (int k = 0; k < prefilter; ++k) coeff_blur121(vec_freq, --n); double mat[4][4]; calc_matrix(mat, mat_freq, index); double vec[4]; for (int i = 0; i < 4; ++i) vec[i] = mat_freq[0] - mat_freq[index[i]] - vec_freq[0] + vec_freq[index[i]]; for (int i = 0; i < 4; ++i) { double res = 0; for (int j = 0; j < 4; ++j) res += mat[i][j] * vec[j]; mu[i] = FFMAX(0, res); } }
168,775
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; } Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team) git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-120
LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; char buf[32]; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); memset(buf,0,32); if(str){ strncpy(buf,str,31); openmpt_free_string(str); } if(buff){ strncpy(buff,buf,32); } return (unsigned int)strlen(buf); }
169,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); } Commit Message: disallow creation (of empty files) in read-only mode; reported by Michal Zalewski, feedback & ok deraadt@ CWE ID: CWE-269
process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT|O_TRUNC)) != 0)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); }
167,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01, GetQuantumPixels(quantum_info),&count); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Fixed memory leak reported in #456. CWE ID: CWE-772
static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01, GetQuantumPixels(quantum_info),&count); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,123
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mv_read_header(AVFormatContext *avctx) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; AVStream *ast = NULL, *vst = NULL; //initialization to suppress warning int version, i; int ret; avio_skip(pb, 4); version = avio_rb16(pb); if (version == 2) { uint64_t timestamp; int v; avio_skip(pb, 22); /* allocate audio track first to prevent unnecessary seeking * (audio packet always precede video packet for a given frame) */ ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); avpriv_set_pts_info(vst, 64, 1, 15); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; vst->avg_frame_rate = av_inv_q(vst->time_base); vst->nb_frames = avio_rb32(pb); v = avio_rb32(pb); switch (v) { case 1: vst->codecpar->codec_id = AV_CODEC_ID_MVC1; break; case 2: vst->codecpar->format = AV_PIX_FMT_ARGB; vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; break; default: avpriv_request_sample(avctx, "Video compression %i", v); break; } vst->codecpar->codec_tag = 0; vst->codecpar->width = avio_rb32(pb); vst->codecpar->height = avio_rb32(pb); avio_skip(pb, 12); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; ast->nb_frames = vst->nb_frames; ast->codecpar->sample_rate = avio_rb32(pb); if (ast->codecpar->sample_rate <= 0) { av_log(avctx, AV_LOG_ERROR, "Invalid sample rate %d\n", ast->codecpar->sample_rate); return AVERROR_INVALIDDATA; } avpriv_set_pts_info(ast, 33, 1, ast->codecpar->sample_rate); if (set_channels(avctx, ast, avio_rb32(pb)) < 0) return AVERROR_INVALIDDATA; v = avio_rb32(pb); if (v == AUDIO_FORMAT_SIGNED) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression (format %i)", v); } avio_skip(pb, 12); var_read_metadata(avctx, "title", 0x80); var_read_metadata(avctx, "comment", 0x100); avio_skip(pb, 0x80); timestamp = 0; for (i = 0; i < vst->nb_frames; i++) { uint32_t pos = avio_rb32(pb); uint32_t asize = avio_rb32(pb); uint32_t vsize = avio_rb32(pb); avio_skip(pb, 8); av_add_index_entry(ast, pos, timestamp, asize, 0, AVINDEX_KEYFRAME); av_add_index_entry(vst, pos + asize, i, vsize, 0, AVINDEX_KEYFRAME); timestamp += asize / (ast->codecpar->channels * 2); } } else if (!version && avio_rb16(pb) == 3) { avio_skip(pb, 4); if ((ret = read_table(avctx, NULL, parse_global_var)) < 0) return ret; if (mv->nb_audio_tracks > 1) { avpriv_request_sample(avctx, "Multiple audio streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_audio_tracks) { ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; if ((read_table(avctx, ast, parse_audio_var)) < 0) return ret; if (mv->acompression == 100 && mv->aformat == AUDIO_FORMAT_SIGNED && ast->codecpar->bits_per_coded_sample == 16) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression %i (format %i, sr %i)", mv->acompression, mv->aformat, ast->codecpar->bits_per_coded_sample); ast->codecpar->codec_id = AV_CODEC_ID_NONE; } if (ast->codecpar->channels <= 0) { av_log(avctx, AV_LOG_ERROR, "No valid channel count found.\n"); return AVERROR_INVALIDDATA; } } if (mv->nb_video_tracks > 1) { avpriv_request_sample(avctx, "Multiple video streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_video_tracks) { vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; if ((ret = read_table(avctx, vst, parse_video_var))<0) return ret; } if (mv->nb_audio_tracks) read_index(pb, ast); if (mv->nb_video_tracks) read_index(pb, vst); } else { avpriv_request_sample(avctx, "Version %i", version); return AVERROR_PATCHWELCOME; } return 0; } Commit Message: avformat/mvdec: Fix DoS due to lack of eof check Fixes: loop.mv Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int mv_read_header(AVFormatContext *avctx) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; AVStream *ast = NULL, *vst = NULL; //initialization to suppress warning int version, i; int ret; avio_skip(pb, 4); version = avio_rb16(pb); if (version == 2) { uint64_t timestamp; int v; avio_skip(pb, 22); /* allocate audio track first to prevent unnecessary seeking * (audio packet always precede video packet for a given frame) */ ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); avpriv_set_pts_info(vst, 64, 1, 15); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; vst->avg_frame_rate = av_inv_q(vst->time_base); vst->nb_frames = avio_rb32(pb); v = avio_rb32(pb); switch (v) { case 1: vst->codecpar->codec_id = AV_CODEC_ID_MVC1; break; case 2: vst->codecpar->format = AV_PIX_FMT_ARGB; vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; break; default: avpriv_request_sample(avctx, "Video compression %i", v); break; } vst->codecpar->codec_tag = 0; vst->codecpar->width = avio_rb32(pb); vst->codecpar->height = avio_rb32(pb); avio_skip(pb, 12); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; ast->nb_frames = vst->nb_frames; ast->codecpar->sample_rate = avio_rb32(pb); if (ast->codecpar->sample_rate <= 0) { av_log(avctx, AV_LOG_ERROR, "Invalid sample rate %d\n", ast->codecpar->sample_rate); return AVERROR_INVALIDDATA; } avpriv_set_pts_info(ast, 33, 1, ast->codecpar->sample_rate); if (set_channels(avctx, ast, avio_rb32(pb)) < 0) return AVERROR_INVALIDDATA; v = avio_rb32(pb); if (v == AUDIO_FORMAT_SIGNED) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression (format %i)", v); } avio_skip(pb, 12); var_read_metadata(avctx, "title", 0x80); var_read_metadata(avctx, "comment", 0x100); avio_skip(pb, 0x80); timestamp = 0; for (i = 0; i < vst->nb_frames; i++) { uint32_t pos = avio_rb32(pb); uint32_t asize = avio_rb32(pb); uint32_t vsize = avio_rb32(pb); if (avio_feof(pb)) return AVERROR_INVALIDDATA; avio_skip(pb, 8); av_add_index_entry(ast, pos, timestamp, asize, 0, AVINDEX_KEYFRAME); av_add_index_entry(vst, pos + asize, i, vsize, 0, AVINDEX_KEYFRAME); timestamp += asize / (ast->codecpar->channels * 2); } } else if (!version && avio_rb16(pb) == 3) { avio_skip(pb, 4); if ((ret = read_table(avctx, NULL, parse_global_var)) < 0) return ret; if (mv->nb_audio_tracks > 1) { avpriv_request_sample(avctx, "Multiple audio streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_audio_tracks) { ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; if ((read_table(avctx, ast, parse_audio_var)) < 0) return ret; if (mv->acompression == 100 && mv->aformat == AUDIO_FORMAT_SIGNED && ast->codecpar->bits_per_coded_sample == 16) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression %i (format %i, sr %i)", mv->acompression, mv->aformat, ast->codecpar->bits_per_coded_sample); ast->codecpar->codec_id = AV_CODEC_ID_NONE; } if (ast->codecpar->channels <= 0) { av_log(avctx, AV_LOG_ERROR, "No valid channel count found.\n"); return AVERROR_INVALIDDATA; } } if (mv->nb_video_tracks > 1) { avpriv_request_sample(avctx, "Multiple video streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_video_tracks) { vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; if ((ret = read_table(avctx, vst, parse_video_var))<0) return ret; } if (mv->nb_audio_tracks) read_index(pb, ast); if (mv->nb_video_tracks) read_index(pb, vst); } else { avpriv_request_sample(avctx, "Version %i", version); return AVERROR_PATCHWELCOME; } return 0; }
167,777
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused) { ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d", fd, offset, length, priority); Mutex::Autolock lock(&mLock); sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length); mSamples.add(sample->sampleID(), sample); doLoad(sample); return sample->sampleID(); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused) { ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d", fd, offset, length, priority);
173,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system, ScriptContext* context, Dispatcher* dispatcher, RequestSender* request_sender, V8SchemaRegistry* v8_schema_registry) { module_system->RegisterNativeHandler( "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context))); module_system->RegisterNativeHandler( "lazy_background_page", scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context))); module_system->RegisterNativeHandler( "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context))); module_system->RegisterNativeHandler("schema_registry", v8_schema_registry->AsNativeHandler()); module_system->RegisterNativeHandler( "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context))); module_system->RegisterNativeHandler( "test_features", scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context))); module_system->RegisterNativeHandler( "test_native_handler", scoped_ptr<NativeHandler>(new TestNativeHandler(context))); module_system->RegisterNativeHandler( "user_gestures", scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context))); module_system->RegisterNativeHandler( "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context))); module_system->RegisterNativeHandler( "v8_context", scoped_ptr<NativeHandler>(new V8ContextNativeHandler(context))); module_system->RegisterNativeHandler( "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context))); module_system->RegisterNativeHandler( "messaging_natives", scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context))); module_system->RegisterNativeHandler( "apiDefinitions", scoped_ptr<NativeHandler>( new ApiDefinitionsNatives(dispatcher, context))); module_system->RegisterNativeHandler( "sendRequest", scoped_ptr<NativeHandler>( new SendRequestNatives(request_sender, context))); module_system->RegisterNativeHandler( "setIcon", scoped_ptr<NativeHandler>(new SetIconNatives(context))); module_system->RegisterNativeHandler( "activityLogger", scoped_ptr<NativeHandler>(new APIActivityLogger(context))); module_system->RegisterNativeHandler( "renderFrameObserverNatives", scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context))); module_system->RegisterNativeHandler( "file_system_natives", scoped_ptr<NativeHandler>(new FileSystemNatives(context))); module_system->RegisterNativeHandler( "app_window_natives", scoped_ptr<NativeHandler>(new AppWindowCustomBindings(context))); module_system->RegisterNativeHandler( "blob_natives", scoped_ptr<NativeHandler>(new BlobNativeHandler(context))); module_system->RegisterNativeHandler( "context_menus", scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context))); module_system->RegisterNativeHandler( "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context))); module_system->RegisterNativeHandler( "document_natives", scoped_ptr<NativeHandler>(new DocumentCustomBindings(context))); module_system->RegisterNativeHandler( "guest_view_internal", scoped_ptr<NativeHandler>( new GuestViewInternalCustomBindings(context))); module_system->RegisterNativeHandler( "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context))); module_system->RegisterNativeHandler( "id_generator", scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context))); module_system->RegisterNativeHandler( "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context))); module_system->RegisterNativeHandler( "display_source", scoped_ptr<NativeHandler>(new DisplaySourceCustomBindings(context))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system, ScriptContext* context, Dispatcher* dispatcher, RequestSender* request_sender, V8SchemaRegistry* v8_schema_registry) { module_system->RegisterNativeHandler( "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context))); module_system->RegisterNativeHandler( "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context))); module_system->RegisterNativeHandler("schema_registry", v8_schema_registry->AsNativeHandler()); module_system->RegisterNativeHandler( "test_features", scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context))); module_system->RegisterNativeHandler( "test_native_handler", scoped_ptr<NativeHandler>(new TestNativeHandler(context))); module_system->RegisterNativeHandler( "user_gestures", scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context))); module_system->RegisterNativeHandler( "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context))); module_system->RegisterNativeHandler( "v8_context", scoped_ptr<NativeHandler>(new V8ContextNativeHandler(context))); module_system->RegisterNativeHandler( "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context))); module_system->RegisterNativeHandler( "messaging_natives", scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context))); module_system->RegisterNativeHandler( "apiDefinitions", scoped_ptr<NativeHandler>( new ApiDefinitionsNatives(dispatcher, context))); module_system->RegisterNativeHandler( "sendRequest", scoped_ptr<NativeHandler>( new SendRequestNatives(request_sender, context))); module_system->RegisterNativeHandler( "setIcon", scoped_ptr<NativeHandler>(new SetIconNatives(context))); module_system->RegisterNativeHandler( "activityLogger", scoped_ptr<NativeHandler>(new APIActivityLogger(context))); module_system->RegisterNativeHandler( "renderFrameObserverNatives", scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context))); module_system->RegisterNativeHandler( "file_system_natives", scoped_ptr<NativeHandler>(new FileSystemNatives(context))); module_system->RegisterNativeHandler( "app_window_natives", scoped_ptr<NativeHandler>(new AppWindowCustomBindings(context))); module_system->RegisterNativeHandler( "blob_natives", scoped_ptr<NativeHandler>(new BlobNativeHandler(context))); module_system->RegisterNativeHandler( "context_menus", scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context))); module_system->RegisterNativeHandler( "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context))); module_system->RegisterNativeHandler( "document_natives", scoped_ptr<NativeHandler>(new DocumentCustomBindings(context))); module_system->RegisterNativeHandler( "guest_view_internal", scoped_ptr<NativeHandler>( new GuestViewInternalCustomBindings(context))); module_system->RegisterNativeHandler( "id_generator", scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context))); module_system->RegisterNativeHandler( "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context))); module_system->RegisterNativeHandler( "display_source", scoped_ptr<NativeHandler>(new DisplaySourceCustomBindings(context))); }
172,247
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ssl_check_for_safari(SSL *s, const unsigned char *data, const unsigned char *limit) { unsigned short type, size; static const unsigned char kSafariExtensionsBlock[] = { 0x00, 0x0a, /* elliptic_curves extension */ 0x00, 0x08, /* 8 bytes */ 0x00, 0x06, /* 6 bytes of curve ids */ 0x00, 0x17, /* P-256 */ 0x00, 0x18, /* P-384 */ 0x00, 0x19, /* P-521 */ 0x00, 0x0b, /* ec_point_formats */ 0x00, 0x02, /* 2 bytes */ 0x01, /* 1 point format */ 0x00, /* uncompressed */ }; /* The following is only present in TLS 1.2 */ static const unsigned char kSafariTLS12ExtensionsBlock[] = { 0x00, 0x0d, /* signature_algorithms */ 0x00, 0x0c, /* 12 bytes */ 0x00, 0x0a, /* 10 bytes */ 0x05, 0x01, /* SHA-384/RSA */ 0x04, 0x01, /* SHA-256/RSA */ 0x02, 0x01, /* SHA-1/RSA */ 0x04, 0x03, /* SHA-256/ECDSA */ 0x02, 0x03, /* SHA-1/ECDSA */ }; if (data >= (limit - 2)) return; data += 2; if (data > (limit - 4)) return; n2s(data, type); n2s(data, size); if (type != TLSEXT_TYPE_server_name) return; if (data + size > limit) return; data += size; if (TLS1_get_client_version(s) >= TLS1_2_VERSION) { const size_t len1 = sizeof(kSafariExtensionsBlock); const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock); if (data + len1 + len2 != limit) return; if (memcmp(data, kSafariExtensionsBlock, len1) != 0) return; if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0) return; } else { const size_t len = sizeof(kSafariExtensionsBlock); if (data + len != limit) return; if (memcmp(data, kSafariExtensionsBlock, len) != 0) return; } s->s3->is_probably_safari = 1; } Commit Message: CWE ID: CWE-190
static void ssl_check_for_safari(SSL *s, const unsigned char *data, const unsigned char *limit) { unsigned short type, size; static const unsigned char kSafariExtensionsBlock[] = { 0x00, 0x0a, /* elliptic_curves extension */ 0x00, 0x08, /* 8 bytes */ 0x00, 0x06, /* 6 bytes of curve ids */ 0x00, 0x17, /* P-256 */ 0x00, 0x18, /* P-384 */ 0x00, 0x19, /* P-521 */ 0x00, 0x0b, /* ec_point_formats */ 0x00, 0x02, /* 2 bytes */ 0x01, /* 1 point format */ 0x00, /* uncompressed */ }; /* The following is only present in TLS 1.2 */ static const unsigned char kSafariTLS12ExtensionsBlock[] = { 0x00, 0x0d, /* signature_algorithms */ 0x00, 0x0c, /* 12 bytes */ 0x00, 0x0a, /* 10 bytes */ 0x05, 0x01, /* SHA-384/RSA */ 0x04, 0x01, /* SHA-256/RSA */ 0x02, 0x01, /* SHA-1/RSA */ 0x04, 0x03, /* SHA-256/ECDSA */ 0x02, 0x03, /* SHA-1/ECDSA */ }; if (limit - data <= 2) return; data += 2; if (limit - data < 4) return; n2s(data, type); n2s(data, size); if (type != TLSEXT_TYPE_server_name) return; if (limit - data < size) return; data += size; if (TLS1_get_client_version(s) >= TLS1_2_VERSION) { const size_t len1 = sizeof(kSafariExtensionsBlock); const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock); if (limit - data != (int)(len1 + len2)) return; if (memcmp(data, kSafariExtensionsBlock, len1) != 0) return; if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0) return; } else { const size_t len = sizeof(kSafariExtensionsBlock); if (limit - data != (int)(len)) return; if (memcmp(data, kSafariExtensionsBlock, len) != 0) return; } s->s3->is_probably_safari = 1; }
165,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_attr_rmtval_set( struct xfs_da_args *args) { struct xfs_inode *dp = args->dp; struct xfs_mount *mp = dp->i_mount; struct xfs_bmbt_irec map; xfs_dablk_t lblkno; xfs_fileoff_t lfileoff = 0; __uint8_t *src = args->value; int blkcnt; int valuelen; int nmap; int error; int offset = 0; trace_xfs_attr_rmtval_set(args); /* * Find a "hole" in the attribute address space large enough for * us to drop the new attribute's value into. Because CRC enable * attributes have headers, we can't just do a straight byte to FSB * conversion and have to take the header space into account. */ blkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff, XFS_ATTR_FORK); if (error) return error; args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff; args->rmtblkcnt = blkcnt; /* * Roll through the "value", allocating blocks on disk as required. */ while (blkcnt > 0) { int committed; /* * Allocate a single extent, up to the size of the value. */ xfs_bmap_init(args->flist, args->firstblock); nmap = 1; error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno, blkcnt, XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA, args->firstblock, args->total, &map, &nmap, args->flist); if (!error) { error = xfs_bmap_finish(&args->trans, args->flist, &committed); } if (error) { ASSERT(committed); args->trans = NULL; xfs_bmap_cancel(args->flist); return(error); } /* * bmap_finish() may have committed the last trans and started * a new one. We need the inode to be in all transactions. */ if (committed) xfs_trans_ijoin(args->trans, dp, 0); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; /* * Start the next trans in the chain. */ error = xfs_trans_roll(&args->trans, dp); if (error) return (error); } /* * Roll through the "value", copying the attribute value to the * already-allocated blocks. Blocks are written synchronously * so that we can know they are all on disk before we turn off * the INCOMPLETE flag. */ lblkno = args->rmtblkno; blkcnt = args->rmtblkcnt; valuelen = args->valuelen; while (valuelen > 0) { struct xfs_buf *bp; xfs_daddr_t dblkno; int dblkcnt; ASSERT(blkcnt > 0); xfs_bmap_init(args->flist, args->firstblock); nmap = 1; error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno, blkcnt, &map, &nmap, XFS_BMAPI_ATTRFORK); if (error) return(error); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock), dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount); bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0); if (!bp) return ENOMEM; bp->b_ops = &xfs_attr3_rmt_buf_ops; xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset, &valuelen, &src); error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */ xfs_buf_relse(bp); if (error) return error; /* roll attribute extent map forwards */ lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; } ASSERT(valuelen == 0); return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19
xfs_attr_rmtval_set( struct xfs_da_args *args) { struct xfs_inode *dp = args->dp; struct xfs_mount *mp = dp->i_mount; struct xfs_bmbt_irec map; xfs_dablk_t lblkno; xfs_fileoff_t lfileoff = 0; __uint8_t *src = args->value; int blkcnt; int valuelen; int nmap; int error; int offset = 0; trace_xfs_attr_rmtval_set(args); /* * Find a "hole" in the attribute address space large enough for * us to drop the new attribute's value into. Because CRC enable * attributes have headers, we can't just do a straight byte to FSB * conversion and have to take the header space into account. */ blkcnt = xfs_attr3_rmt_blocks(mp, args->rmtvaluelen); error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff, XFS_ATTR_FORK); if (error) return error; args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff; args->rmtblkcnt = blkcnt; /* * Roll through the "value", allocating blocks on disk as required. */ while (blkcnt > 0) { int committed; /* * Allocate a single extent, up to the size of the value. */ xfs_bmap_init(args->flist, args->firstblock); nmap = 1; error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno, blkcnt, XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA, args->firstblock, args->total, &map, &nmap, args->flist); if (!error) { error = xfs_bmap_finish(&args->trans, args->flist, &committed); } if (error) { ASSERT(committed); args->trans = NULL; xfs_bmap_cancel(args->flist); return(error); } /* * bmap_finish() may have committed the last trans and started * a new one. We need the inode to be in all transactions. */ if (committed) xfs_trans_ijoin(args->trans, dp, 0); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; /* * Start the next trans in the chain. */ error = xfs_trans_roll(&args->trans, dp); if (error) return (error); } /* * Roll through the "value", copying the attribute value to the * already-allocated blocks. Blocks are written synchronously * so that we can know they are all on disk before we turn off * the INCOMPLETE flag. */ lblkno = args->rmtblkno; blkcnt = args->rmtblkcnt; valuelen = args->rmtvaluelen; while (valuelen > 0) { struct xfs_buf *bp; xfs_daddr_t dblkno; int dblkcnt; ASSERT(blkcnt > 0); xfs_bmap_init(args->flist, args->firstblock); nmap = 1; error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno, blkcnt, &map, &nmap, XFS_BMAPI_ATTRFORK); if (error) return(error); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock), dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount); bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0); if (!bp) return ENOMEM; bp->b_ops = &xfs_attr3_rmt_buf_ops; xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset, &valuelen, &src); error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */ xfs_buf_relse(bp); if (error) return error; /* roll attribute extent map forwards */ lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; } ASSERT(valuelen == 0); return 0; }
166,740
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void fillWidgetStates(AXObject& axObject, protocol::Array<AXProperty>& properties) { AccessibilityRole role = axObject.roleValue(); if (roleAllowsChecked(role)) { AccessibilityButtonState checked = axObject.checkboxOrRadioValue(); switch (checked) { case ButtonStateOff: properties.addItem( createProperty(AXWidgetStatesEnum::Checked, createValue("false", AXValueTypeEnum::Tristate))); break; case ButtonStateOn: properties.addItem( createProperty(AXWidgetStatesEnum::Checked, createValue("true", AXValueTypeEnum::Tristate))); break; case ButtonStateMixed: properties.addItem( createProperty(AXWidgetStatesEnum::Checked, createValue("mixed", AXValueTypeEnum::Tristate))); break; } } AccessibilityExpanded expanded = axObject.isExpanded(); switch (expanded) { case ExpandedUndefined: break; case ExpandedCollapsed: properties.addItem(createProperty( AXWidgetStatesEnum::Expanded, createBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined))); break; case ExpandedExpanded: properties.addItem(createProperty( AXWidgetStatesEnum::Expanded, createBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined))); break; } if (role == ToggleButtonRole) { if (!axObject.isPressed()) { properties.addItem( createProperty(AXWidgetStatesEnum::Pressed, createValue("false", AXValueTypeEnum::Tristate))); } else { const AtomicString& pressedAttr = axObject.getAttribute(HTMLNames::aria_pressedAttr); if (equalIgnoringCase(pressedAttr, "mixed")) properties.addItem( createProperty(AXWidgetStatesEnum::Pressed, createValue("mixed", AXValueTypeEnum::Tristate))); else properties.addItem( createProperty(AXWidgetStatesEnum::Pressed, createValue("true", AXValueTypeEnum::Tristate))); } } if (roleAllowsSelected(role)) { properties.addItem( createProperty(AXWidgetStatesEnum::Selected, createBooleanValue(axObject.isSelected()))); } if (roleAllowsModal(role)) { properties.addItem(createProperty(AXWidgetStatesEnum::Modal, createBooleanValue(axObject.isModal()))); } } 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
void fillWidgetStates(AXObject& axObject, protocol::Array<AXProperty>& properties) { AccessibilityRole role = axObject.roleValue(); if (roleAllowsChecked(role)) { AccessibilityButtonState checked = axObject.checkboxOrRadioValue(); switch (checked) { case ButtonStateOff: properties.addItem( createProperty(AXWidgetStatesEnum::Checked, createValue("false", AXValueTypeEnum::Tristate))); break; case ButtonStateOn: properties.addItem( createProperty(AXWidgetStatesEnum::Checked, createValue("true", AXValueTypeEnum::Tristate))); break; case ButtonStateMixed: properties.addItem( createProperty(AXWidgetStatesEnum::Checked, createValue("mixed", AXValueTypeEnum::Tristate))); break; } } AccessibilityExpanded expanded = axObject.isExpanded(); switch (expanded) { case ExpandedUndefined: break; case ExpandedCollapsed: properties.addItem(createProperty( AXWidgetStatesEnum::Expanded, createBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined))); break; case ExpandedExpanded: properties.addItem(createProperty( AXWidgetStatesEnum::Expanded, createBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined))); break; } if (role == ToggleButtonRole) { if (!axObject.isPressed()) { properties.addItem( createProperty(AXWidgetStatesEnum::Pressed, createValue("false", AXValueTypeEnum::Tristate))); } else { const AtomicString& pressedAttr = axObject.getAttribute(HTMLNames::aria_pressedAttr); if (equalIgnoringASCIICase(pressedAttr, "mixed")) properties.addItem( createProperty(AXWidgetStatesEnum::Pressed, createValue("mixed", AXValueTypeEnum::Tristate))); else properties.addItem( createProperty(AXWidgetStatesEnum::Pressed, createValue("true", AXValueTypeEnum::Tristate))); } } if (roleAllowsSelected(role)) { properties.addItem( createProperty(AXWidgetStatesEnum::Selected, createBooleanValue(axObject.isSelected()))); } if (roleAllowsModal(role)) { properties.addItem(createProperty(AXWidgetStatesEnum::Modal, createBooleanValue(axObject.isModal()))); } }
171,934
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int install_thread_keyring_to_cred(struct cred *new) { struct key *keyring; keyring = keyring_alloc("_tid", new->uid, new->gid, new, KEY_POS_ALL | KEY_USR_VIEW, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); new->thread_keyring = keyring; return 0; } Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings This fixes CVE-2017-7472. Running the following program as an unprivileged user exhausts kernel memory by leaking thread keyrings: #include <keyutils.h> int main() { for (;;) keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING); } Fix it by only creating a new thread keyring if there wasn't one before. To make things more consistent, make install_thread_keyring_to_cred() and install_process_keyring_to_cred() both return 0 if the corresponding keyring is already present. Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials") Cc: [email protected] # 2.6.29+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID: CWE-404
int install_thread_keyring_to_cred(struct cred *new) { struct key *keyring; if (new->thread_keyring) return 0; keyring = keyring_alloc("_tid", new->uid, new->gid, new, KEY_POS_ALL | KEY_USR_VIEW, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); new->thread_keyring = keyring; return 0; }
168,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool CanCapture(const Extension& extension, const GURL& url) { return extension.permissions_data()->CanCaptureVisiblePage( url, kTabId, nullptr /*error*/); } Commit Message: Call CanCaptureVisiblePage in page capture API. Currently the pageCapture permission allows access to arbitrary local files and chrome:// pages which can be a security concern. In order to address this, the page capture API needs to be changed similar to the captureVisibleTab API. The API will now only allow extensions to capture otherwise-restricted URLs if the user has granted activeTab. In addition, file:// URLs are only capturable with the "Allow on file URLs" option enabled. Bug: 893087 Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624 Reviewed-on: https://chromium-review.googlesource.com/c/1330689 Commit-Queue: Bettina Dea <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Varun Khaneja <[email protected]> Cr-Commit-Position: refs/heads/master@{#615248} CWE ID: CWE-20
bool CanCapture(const Extension& extension, const GURL& url) { bool CanCapture(const Extension& extension, const GURL& url, extensions::CaptureRequirement capture_requirement) { return extension.permissions_data()->CanCaptureVisiblePage( url, kTabId, nullptr /*error*/, capture_requirement); }
173,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltNumberFormatGetMultipleLevel(xsltTransformContextPtr context, xmlNodePtr node, xsltCompMatchPtr countPat, xsltCompMatchPtr fromPat, double *array, int max, xmlDocPtr doc, xmlNodePtr elem) { int amount = 0; int cnt; xmlNodePtr ancestor; xmlNodePtr preceding; xmlXPathParserContextPtr parser; context->xpathCtxt->node = node; parser = xmlXPathNewParserContext(NULL, context->xpathCtxt); if (parser) { /* ancestor-or-self::*[count] */ for (ancestor = node; (ancestor != NULL) && (ancestor->type != XML_DOCUMENT_NODE); ancestor = xmlXPathNextAncestor(parser, ancestor)) { if ((fromPat != NULL) && xsltTestCompMatchList(context, ancestor, fromPat)) break; /* for */ if ((countPat == NULL && node->type == ancestor->type && xmlStrEqual(node->name, ancestor->name)) || xsltTestCompMatchList(context, ancestor, countPat)) { /* count(preceding-sibling::*) */ cnt = 0; for (preceding = ancestor; preceding != NULL; preceding = xmlXPathNextPrecedingSibling(parser, preceding)) { if (countPat == NULL) { if ((preceding->type == ancestor->type) && xmlStrEqual(preceding->name, ancestor->name)){ if ((preceding->ns == ancestor->ns) || ((preceding->ns != NULL) && (ancestor->ns != NULL) && (xmlStrEqual(preceding->ns->href, ancestor->ns->href) ))) cnt++; } } else { if (xsltTestCompMatchList(context, preceding, countPat)) cnt++; } } array[amount++] = (double)cnt; if (amount >= max) break; /* for */ } } xmlXPathFreeParserContext(parser); } return amount; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltNumberFormatGetMultipleLevel(xsltTransformContextPtr context, xmlNodePtr node, xsltCompMatchPtr countPat, xsltCompMatchPtr fromPat, double *array, int max) { int amount = 0; int cnt; xmlNodePtr ancestor; xmlNodePtr preceding; xmlXPathParserContextPtr parser; context->xpathCtxt->node = node; parser = xmlXPathNewParserContext(NULL, context->xpathCtxt); if (parser) { /* ancestor-or-self::*[count] */ for (ancestor = node; (ancestor != NULL) && (ancestor->type != XML_DOCUMENT_NODE); ancestor = xmlXPathNextAncestor(parser, ancestor)) { if ((fromPat != NULL) && xsltTestCompMatchList(context, ancestor, fromPat)) break; /* for */ if (xsltTestCompMatchCount(context, ancestor, countPat, node)) { /* count(preceding-sibling::*) */ cnt = 1; for (preceding = xmlXPathNextPrecedingSibling(parser, ancestor); preceding != NULL; preceding = xmlXPathNextPrecedingSibling(parser, preceding)) { if (xsltTestCompMatchCount(context, preceding, countPat, node)) cnt++; } array[amount++] = (double)cnt; if (amount >= max) break; /* for */ } } xmlXPathFreeParserContext(parser); } return amount; }
173,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); } Commit Message: Prevent arithmetic overflow on bounds check CWE ID: CWE-125
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) > end - len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); }
170,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (IS_ERR_OR_NULL(mp)) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); if (mnt->mnt.mnt_flags & MNT_UMOUNT) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { hlist_add_head(&p->mnt_umount.s_list, &unmounted); umount_mnt(p); } } else umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); } Commit Message: mnt: Update detach_mounts to leave mounts connected Now that it is possible to lazily unmount an entire mount tree and leave the individual mounts connected to each other add a new flag UMOUNT_CONNECTED to umount_tree to force this behavior and use this flag in detach_mounts. This closes a bug where the deletion of a file or directory could trigger an unmount and reveal data under a mount point. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-200
void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (IS_ERR_OR_NULL(mp)) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); if (mnt->mnt.mnt_flags & MNT_UMOUNT) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { hlist_add_head(&p->mnt_umount.s_list, &unmounted); umount_mnt(p); } } else umount_tree(mnt, UMOUNT_CONNECTED); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); }
167,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int nlmsg_populate_mdb_fill(struct sk_buff *skb, struct net_device *dev, struct br_mdb_entry *entry, u32 pid, u32 seq, int type, unsigned int flags) { struct nlmsghdr *nlh; struct br_port_msg *bpm; struct nlattr *nest, *nest2; nlh = nlmsg_put(skb, pid, seq, type, sizeof(*bpm), NLM_F_MULTI); if (!nlh) return -EMSGSIZE; bpm = nlmsg_data(nlh); bpm->family = AF_BRIDGE; bpm->ifindex = dev->ifindex; nest = nla_nest_start(skb, MDBA_MDB); if (nest == NULL) goto cancel; nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY); if (nest2 == NULL) goto end; if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(*entry), entry)) goto end; nla_nest_end(skb, nest2); nla_nest_end(skb, nest); return nlmsg_end(skb, nlh); end: nla_nest_end(skb, nest); cancel: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } Commit Message: bridge: fix mdb info leaks The bridging code discloses heap and stack bytes via the RTM_GETMDB netlink interface and via the notify messages send to group RTNLGRP_MDB afer a successful add/del. Fix both cases by initializing all unset members/padding bytes with memset(0). Cc: Stephen Hemminger <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int nlmsg_populate_mdb_fill(struct sk_buff *skb, struct net_device *dev, struct br_mdb_entry *entry, u32 pid, u32 seq, int type, unsigned int flags) { struct nlmsghdr *nlh; struct br_port_msg *bpm; struct nlattr *nest, *nest2; nlh = nlmsg_put(skb, pid, seq, type, sizeof(*bpm), NLM_F_MULTI); if (!nlh) return -EMSGSIZE; bpm = nlmsg_data(nlh); memset(bpm, 0, sizeof(*bpm)); bpm->family = AF_BRIDGE; bpm->ifindex = dev->ifindex; nest = nla_nest_start(skb, MDBA_MDB); if (nest == NULL) goto cancel; nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY); if (nest2 == NULL) goto end; if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(*entry), entry)) goto end; nla_nest_end(skb, nest2); nla_nest_end(skb, nest); return nlmsg_end(skb, nlh); end: nla_nest_end(skb, nest); cancel: nlmsg_cancel(skb, nlh); return -EMSGSIZE; }
166,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps || siz->numcomps > 16384) { return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) { jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp); jas_free(siz->comps); return -1; } if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) { jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp); jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; } Commit Message: Ensure that not all tiles lie outside the image area. CWE ID: CWE-20
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps || siz->numcomps > 16384) { return -1; } if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) { jas_eprintf("all tiles are outside the image area\n"); return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) { jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp); jas_free(siz->comps); return -1; } if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) { jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp); jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; }
168,736
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PluginInfoMessageFilter::Context::GrantAccess( const ChromeViewHostMsg_GetPluginInfo_Status& status, const FilePath& path) const { if (status.value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed || status.value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay) { ChromePluginServiceFilter::GetInstance()->AuthorizePlugin( render_process_id_, path); } } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
void PluginInfoMessageFilter::Context::GrantAccess( void PluginInfoMessageFilter::Context::MaybeGrantAccess( const ChromeViewHostMsg_GetPluginInfo_Status& status, const FilePath& path) const { if (status.value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed || status.value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay) { ChromePluginServiceFilter::GetInstance()->AuthorizePlugin( render_process_id_, path); } }
171,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); }
167,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k) { void *result; size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; DCL_LOCK_STATE; if (SMALL_OBJ(lb)) return(GC_generic_malloc((word)lb, k)); lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); LOCK(); result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; if (0 == result) { GC_oom_func oom_fn = GC_oom_fn; UNLOCK(); return((*oom_fn)(lb)); } else { UNLOCK(); if (init && !GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } return(result); } } Commit Message: Fix allocation size overflows due to rounding. * malloc.c (GC_generic_malloc): Check if the allocation size is rounded to a smaller value. * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. CWE ID: CWE-189
GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k) { void *result; size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; DCL_LOCK_STATE; if (SMALL_OBJ(lb)) return(GC_generic_malloc((word)lb, k)); lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); if (lb_rounded < lb) return((*GC_get_oom_fn())(lb)); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); LOCK(); result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; if (0 == result) { GC_oom_func oom_fn = GC_oom_fn; UNLOCK(); return((*oom_fn)(lb)); } else { UNLOCK(); if (init && !GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } return(result); } }
169,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static EAS_RESULT PushcdlStack (EAS_U32 *pStack, EAS_INT *pStackPtr, EAS_U32 value) { /* stack overflow, return an error */ if (*pStackPtr >= CDL_STACK_SIZE) return EAS_ERROR_FILE_FORMAT; /* push the value onto the stack */ *pStackPtr = *pStackPtr + 1; pStack[*pStackPtr] = value; return EAS_SUCCESS; } Commit Message: eas_mdls: fix OOB read. Bug: 34031018 Change-Id: I8d373c905f64286b23ec819bdbee51368b12e85a CWE ID: CWE-119
static EAS_RESULT PushcdlStack (EAS_U32 *pStack, EAS_INT *pStackPtr, EAS_U32 value) { /* stack overflow, return an error */ if (*pStackPtr >= (CDL_STACK_SIZE - 1)) { ALOGE("b/34031018, stackPtr(%d)", *pStackPtr); android_errorWriteLog(0x534e4554, "34031018"); return EAS_ERROR_FILE_FORMAT; } /* push the value onto the stack */ *pStackPtr = *pStackPtr + 1; pStack[*pStackPtr] = value; return EAS_SUCCESS; }
174,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else tty_encode_baud_rate(tty, baud, baud); edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); } Commit Message: USB: serial: io_ti: fix div-by-zero in set_termios Fix a division-by-zero in set_termios when debugging is enabled and a high-enough speed has been requested so that the divisor value becomes zero. Instead of just fixing the offending debug statement, cap the baud rate at the base as a zero divisor value also appears to crash the firmware. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <[email protected]> # 2.6.12 Reviewed-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-369
static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else { /* Avoid a zero divisor. */ baud = min(baud, 461550); tty_encode_baud_rate(tty, baud, baud); } edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); }
169,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void fanout_release(struct sock *sk) { struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f; f = po->fanout; if (!f) return; mutex_lock(&fanout_mutex); po->fanout = NULL; if (atomic_dec_and_test(&f->sk_ref)) { list_del(&f->list); dev_remove_pack(&f->prot_hook); fanout_release_data(f); kfree(f); } mutex_unlock(&fanout_mutex); if (po->rollover) kfree_rcu(po->rollover, rcu); } Commit Message: packet: fix races in fanout_add() Multiple threads can call fanout_add() at the same time. We need to grab fanout_mutex earlier to avoid races that could lead to one thread freeing po->rollover that was set by another thread. Do the same in fanout_release(), for peace of mind, and to help us finding lockdep issues earlier. Fixes: dc99f600698d ("packet: Add fanout support.") Fixes: 0648ab70afe6 ("packet: rollover prepare: per-socket state") Signed-off-by: Eric Dumazet <[email protected]> Cc: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static void fanout_release(struct sock *sk) { struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f; mutex_lock(&fanout_mutex); f = po->fanout; if (f) { po->fanout = NULL; if (atomic_dec_and_test(&f->sk_ref)) { list_del(&f->list); dev_remove_pack(&f->prot_hook); fanout_release_data(f); kfree(f); } if (po->rollover) kfree_rcu(po->rollover, rcu); } mutex_unlock(&fanout_mutex); }
168,347
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack;; */ struct seg *stack = NULL; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal -1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled){ _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx;wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } efree(stack); done: im->alphaBlendingFlag = alphablending_bak; } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack;; */ struct seg *stack = NULL; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal -1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled){ _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx;wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } efree(stack); done: im->alphaBlendingFlag = alphablending_bak; }
167,128
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ProfileImplIOData::LazyInitializeInternal( ProfileParams* profile_params) const { clear_local_state_on_exit_ = profile_params->clear_local_state_on_exit; ChromeURLRequestContext* main_context = main_request_context(); ChromeURLRequestContext* extensions_context = extensions_request_context(); media_request_context_ = new ChromeURLRequestContext; IOThread* const io_thread = profile_params->io_thread; IOThread::Globals* const io_thread_globals = io_thread->globals(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool record_mode = chrome::kRecordModeEnabled && command_line.HasSwitch(switches::kRecordMode); bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode); ApplyProfileParamsToContext(main_context); ApplyProfileParamsToContext(media_request_context_); ApplyProfileParamsToContext(extensions_context); if (http_server_properties_manager_.get()) http_server_properties_manager_->InitializeOnIOThread(); main_context->set_transport_security_state(transport_security_state()); media_request_context_->set_transport_security_state( transport_security_state()); extensions_context->set_transport_security_state(transport_security_state()); main_context->set_net_log(io_thread->net_log()); media_request_context_->set_net_log(io_thread->net_log()); extensions_context->set_net_log(io_thread->net_log()); main_context->set_network_delegate(network_delegate()); media_request_context_->set_network_delegate(network_delegate()); main_context->set_http_server_properties(http_server_properties()); media_request_context_->set_http_server_properties(http_server_properties()); main_context->set_host_resolver( io_thread_globals->host_resolver.get()); media_request_context_->set_host_resolver( io_thread_globals->host_resolver.get()); main_context->set_cert_verifier( io_thread_globals->cert_verifier.get()); media_request_context_->set_cert_verifier( io_thread_globals->cert_verifier.get()); main_context->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); media_request_context_->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); main_context->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); media_request_context_->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); main_context->set_proxy_service(proxy_service()); media_request_context_->set_proxy_service(proxy_service()); scoped_refptr<net::CookieStore> cookie_store = NULL; net::OriginBoundCertService* origin_bound_cert_service = NULL; if (record_mode || playback_mode) { cookie_store = new net::CookieMonster( NULL, profile_params->cookie_monster_delegate); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(NULL)); } if (!cookie_store) { DCHECK(!lazy_params_->cookie_path.empty()); scoped_refptr<SQLitePersistentCookieStore> cookie_db = new SQLitePersistentCookieStore( lazy_params_->cookie_path, lazy_params_->restore_old_session_cookies); cookie_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); cookie_store = new net::CookieMonster(cookie_db.get(), profile_params->cookie_monster_delegate); if (command_line.HasSwitch(switches::kEnableRestoreSessionState)) cookie_store->GetCookieMonster()->SetPersistSessionCookies(true); } net::CookieMonster* extensions_cookie_store = new net::CookieMonster( new SQLitePersistentCookieStore( lazy_params_->extensions_cookie_path, lazy_params_->restore_old_session_cookies), NULL); const char* schemes[] = {chrome::kChromeDevToolsScheme, chrome::kExtensionScheme}; extensions_cookie_store->SetCookieableSchemes(schemes, 2); main_context->set_cookie_store(cookie_store); media_request_context_->set_cookie_store(cookie_store); extensions_context->set_cookie_store(extensions_cookie_store); if (!origin_bound_cert_service) { DCHECK(!lazy_params_->origin_bound_cert_path.empty()); scoped_refptr<SQLiteOriginBoundCertStore> origin_bound_cert_db = new SQLiteOriginBoundCertStore(lazy_params_->origin_bound_cert_path); origin_bound_cert_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(origin_bound_cert_db.get())); } set_origin_bound_cert_service(origin_bound_cert_service); main_context->set_origin_bound_cert_service(origin_bound_cert_service); media_request_context_->set_origin_bound_cert_service( origin_bound_cert_service); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( net::DISK_CACHE, lazy_params_->cache_path, lazy_params_->cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpCache* main_cache = new net::HttpCache( main_context->host_resolver(), main_context->cert_verifier(), main_context->origin_bound_cert_service(), main_context->transport_security_state(), main_context->proxy_service(), "", // pass empty ssl_session_cache_shard to share the SSL session cache main_context->ssl_config_service(), main_context->http_auth_handler_factory(), main_context->network_delegate(), main_context->http_server_properties(), main_context->net_log(), main_backend); net::HttpCache::DefaultBackend* media_backend = new net::HttpCache::DefaultBackend( net::MEDIA_CACHE, lazy_params_->media_cache_path, lazy_params_->media_cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpNetworkSession* main_network_session = main_cache->GetSession(); net::HttpCache* media_cache = new net::HttpCache(main_network_session, media_backend); if (record_mode || playback_mode) { main_cache->set_mode( record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK); } main_http_factory_.reset(main_cache); media_http_factory_.reset(media_cache); main_context->set_http_transaction_factory(main_cache); media_request_context_->set_http_transaction_factory(media_cache); ftp_factory_.reset( new net::FtpNetworkLayer(io_thread_globals->host_resolver.get())); main_context->set_ftp_transaction_factory(ftp_factory_.get()); main_context->set_chrome_url_data_manager_backend( chrome_url_data_manager_backend()); main_context->set_job_factory(job_factory()); media_request_context_->set_job_factory(job_factory()); extensions_context->set_job_factory(job_factory()); job_factory()->AddInterceptor( new chrome_browser_net::ConnectInterceptor(predictor_.get())); lazy_params_.reset(); } Commit Message: Give the media context an ftp job factory; prevent a browser crash. BUG=112983 TEST=none Review URL: http://codereview.chromium.org/9372002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@121378 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void ProfileImplIOData::LazyInitializeInternal( ProfileParams* profile_params) const { clear_local_state_on_exit_ = profile_params->clear_local_state_on_exit; ChromeURLRequestContext* main_context = main_request_context(); ChromeURLRequestContext* extensions_context = extensions_request_context(); media_request_context_ = new ChromeURLRequestContext; IOThread* const io_thread = profile_params->io_thread; IOThread::Globals* const io_thread_globals = io_thread->globals(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool record_mode = chrome::kRecordModeEnabled && command_line.HasSwitch(switches::kRecordMode); bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode); ApplyProfileParamsToContext(main_context); ApplyProfileParamsToContext(media_request_context_); ApplyProfileParamsToContext(extensions_context); if (http_server_properties_manager_.get()) http_server_properties_manager_->InitializeOnIOThread(); main_context->set_transport_security_state(transport_security_state()); media_request_context_->set_transport_security_state( transport_security_state()); extensions_context->set_transport_security_state(transport_security_state()); main_context->set_net_log(io_thread->net_log()); media_request_context_->set_net_log(io_thread->net_log()); extensions_context->set_net_log(io_thread->net_log()); main_context->set_network_delegate(network_delegate()); media_request_context_->set_network_delegate(network_delegate()); main_context->set_http_server_properties(http_server_properties()); media_request_context_->set_http_server_properties(http_server_properties()); main_context->set_host_resolver( io_thread_globals->host_resolver.get()); media_request_context_->set_host_resolver( io_thread_globals->host_resolver.get()); main_context->set_cert_verifier( io_thread_globals->cert_verifier.get()); media_request_context_->set_cert_verifier( io_thread_globals->cert_verifier.get()); main_context->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); media_request_context_->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); main_context->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); media_request_context_->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); main_context->set_proxy_service(proxy_service()); media_request_context_->set_proxy_service(proxy_service()); scoped_refptr<net::CookieStore> cookie_store = NULL; net::OriginBoundCertService* origin_bound_cert_service = NULL; if (record_mode || playback_mode) { cookie_store = new net::CookieMonster( NULL, profile_params->cookie_monster_delegate); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(NULL)); } if (!cookie_store) { DCHECK(!lazy_params_->cookie_path.empty()); scoped_refptr<SQLitePersistentCookieStore> cookie_db = new SQLitePersistentCookieStore( lazy_params_->cookie_path, lazy_params_->restore_old_session_cookies); cookie_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); cookie_store = new net::CookieMonster(cookie_db.get(), profile_params->cookie_monster_delegate); if (command_line.HasSwitch(switches::kEnableRestoreSessionState)) cookie_store->GetCookieMonster()->SetPersistSessionCookies(true); } net::CookieMonster* extensions_cookie_store = new net::CookieMonster( new SQLitePersistentCookieStore( lazy_params_->extensions_cookie_path, lazy_params_->restore_old_session_cookies), NULL); const char* schemes[] = {chrome::kChromeDevToolsScheme, chrome::kExtensionScheme}; extensions_cookie_store->SetCookieableSchemes(schemes, 2); main_context->set_cookie_store(cookie_store); media_request_context_->set_cookie_store(cookie_store); extensions_context->set_cookie_store(extensions_cookie_store); if (!origin_bound_cert_service) { DCHECK(!lazy_params_->origin_bound_cert_path.empty()); scoped_refptr<SQLiteOriginBoundCertStore> origin_bound_cert_db = new SQLiteOriginBoundCertStore(lazy_params_->origin_bound_cert_path); origin_bound_cert_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(origin_bound_cert_db.get())); } set_origin_bound_cert_service(origin_bound_cert_service); main_context->set_origin_bound_cert_service(origin_bound_cert_service); media_request_context_->set_origin_bound_cert_service( origin_bound_cert_service); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( net::DISK_CACHE, lazy_params_->cache_path, lazy_params_->cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpCache* main_cache = new net::HttpCache( main_context->host_resolver(), main_context->cert_verifier(), main_context->origin_bound_cert_service(), main_context->transport_security_state(), main_context->proxy_service(), "", // pass empty ssl_session_cache_shard to share the SSL session cache main_context->ssl_config_service(), main_context->http_auth_handler_factory(), main_context->network_delegate(), main_context->http_server_properties(), main_context->net_log(), main_backend); net::HttpCache::DefaultBackend* media_backend = new net::HttpCache::DefaultBackend( net::MEDIA_CACHE, lazy_params_->media_cache_path, lazy_params_->media_cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpNetworkSession* main_network_session = main_cache->GetSession(); net::HttpCache* media_cache = new net::HttpCache(main_network_session, media_backend); if (record_mode || playback_mode) { main_cache->set_mode( record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK); } main_http_factory_.reset(main_cache); media_http_factory_.reset(media_cache); main_context->set_http_transaction_factory(main_cache); media_request_context_->set_http_transaction_factory(media_cache); ftp_factory_.reset( new net::FtpNetworkLayer(io_thread_globals->host_resolver.get())); main_context->set_ftp_transaction_factory(ftp_factory_.get()); media_request_context_->set_ftp_transaction_factory(ftp_factory_.get()); main_context->set_chrome_url_data_manager_backend( chrome_url_data_manager_backend()); main_context->set_job_factory(job_factory()); media_request_context_->set_job_factory(job_factory()); extensions_context->set_job_factory(job_factory()); job_factory()->AddInterceptor( new chrome_browser_net::ConnectInterceptor(predictor_.get())); lazy_params_.reset(); }
171,005
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftHEVC::onQueueFilled(OMX_U32 portIndex) { UNUSED(portIndex); if (mSignalledError) { return; } if (mOutputPortSettingsChange != NONE) { return; } if (NULL == mCodecCtx) { if (OK != initDecoder()) { return; } } if (outputBufferWidth() != mStride) { /* Set the run-time (dynamic) parameters */ mStride = outputBufferWidth(); setParams(mStride); } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); /* If input EOS is seen and decoder is not in flush mode, * set the decoder in flush mode. * There can be a case where EOS is sent along with last picture data * In that case, only after decoding that input data, decoder has to be * put in flush. This case is handled here */ if (mReceivedEOS && !mIsInFlush) { setFlushMode(); } while (!outQueue.empty()) { BufferInfo *inInfo; OMX_BUFFERHEADERTYPE *inHeader; BufferInfo *outInfo; OMX_BUFFERHEADERTYPE *outHeader; size_t timeStampIx; inInfo = NULL; inHeader = NULL; if (!mIsInFlush) { if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } else { break; } } outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; outHeader->nFlags = 0; outHeader->nTimeStamp = 0; outHeader->nOffset = 0; if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { mReceivedEOS = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inHeader = NULL; setFlushMode(); } } /* Get a free slot in timestamp array to hold input timestamp */ { size_t i; timeStampIx = 0; for (i = 0; i < MAX_TIME_STAMPS; i++) { if (!mTimeStampsValid[i]) { timeStampIx = i; break; } } if (inHeader != NULL) { mTimeStampsValid[timeStampIx] = true; mTimeStamps[timeStampIx] = inHeader->nTimeStamp; } } { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; WORD32 timeDelay, timeTaken; size_t sizeY, sizeUV; if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { ALOGE("Decoder arg setup failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } GETTIME(&mTimeStart, NULL); /* Compute time elapsed between end of previous decode() * to start of current decode() */ TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); IV_API_CALL_STATUS_T status; status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); GETTIME(&mTimeEnd, NULL); /* Compute time taken for decode() */ TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay, s_dec_op.u4_num_bytes_consumed); if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { mFlushNeeded = true; } if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { /* If the input did not contain picture data, then ignore * the associated timestamp */ mTimeStampsValid[timeStampIx] = false; } if (mChangingResolution && !s_dec_op.u4_output_present) { mChangingResolution = false; resetDecoder(); resetPlugin(); continue; } if (resChanged) { mChangingResolution = true; if (mFlushNeeded) { setFlushMode(); } continue; } if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { uint32_t width = s_dec_op.u4_pic_wd; uint32_t height = s_dec_op.u4_pic_ht; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { resetDecoder(); return; } } if (s_dec_op.u4_output_present) { outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts]; mTimeStampsValid[s_dec_op.u4_ts] = false; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } else { /* If in flush mode and no output is returned by the codec, * then come out of flush mode */ mIsInFlush = false; /* If EOS was recieved on input port and there is no output * from the codec, then signal EOS on output port */ if (mReceivedEOS) { outHeader->nFilledLen = 0; outHeader->nFlags |= OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; resetPlugin(); } } } if (inHeader != NULL) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } } Commit Message: SoftHEVC: Exit gracefully in case of decoder errors Exit for error in allocation and unsupported resolutions Bug: 28816956 Change-Id: Ieb830bedeb3a7431d1d21a024927df630f7eda1e CWE ID: CWE-172
void SoftHEVC::onQueueFilled(OMX_U32 portIndex) { UNUSED(portIndex); if (mSignalledError) { return; } if (mOutputPortSettingsChange != NONE) { return; } if (NULL == mCodecCtx) { if (OK != initDecoder()) { ALOGE("Failed to initialize decoder"); notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL); mSignalledError = true; return; } } if (outputBufferWidth() != mStride) { /* Set the run-time (dynamic) parameters */ mStride = outputBufferWidth(); setParams(mStride); } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); /* If input EOS is seen and decoder is not in flush mode, * set the decoder in flush mode. * There can be a case where EOS is sent along with last picture data * In that case, only after decoding that input data, decoder has to be * put in flush. This case is handled here */ if (mReceivedEOS && !mIsInFlush) { setFlushMode(); } while (!outQueue.empty()) { BufferInfo *inInfo; OMX_BUFFERHEADERTYPE *inHeader; BufferInfo *outInfo; OMX_BUFFERHEADERTYPE *outHeader; size_t timeStampIx; inInfo = NULL; inHeader = NULL; if (!mIsInFlush) { if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } else { break; } } outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; outHeader->nFlags = 0; outHeader->nTimeStamp = 0; outHeader->nOffset = 0; if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { mReceivedEOS = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inHeader = NULL; setFlushMode(); } } /* Get a free slot in timestamp array to hold input timestamp */ { size_t i; timeStampIx = 0; for (i = 0; i < MAX_TIME_STAMPS; i++) { if (!mTimeStampsValid[i]) { timeStampIx = i; break; } } if (inHeader != NULL) { mTimeStampsValid[timeStampIx] = true; mTimeStamps[timeStampIx] = inHeader->nTimeStamp; } } { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; WORD32 timeDelay, timeTaken; size_t sizeY, sizeUV; if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { ALOGE("Decoder arg setup failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } GETTIME(&mTimeStart, NULL); /* Compute time elapsed between end of previous decode() * to start of current decode() */ TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); IV_API_CALL_STATUS_T status; status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); bool unsupportedResolution = (IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED == (s_dec_op.u4_error_code & 0xFF)); /* Check for unsupported dimensions */ if (unsupportedResolution) { ALOGE("Unsupported resolution : %dx%d", mWidth, mHeight); notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL); mSignalledError = true; return; } bool allocationFailed = (IVD_MEM_ALLOC_FAILED == (s_dec_op.u4_error_code & 0xFF)); if (allocationFailed) { ALOGE("Allocation failure in decoder"); notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL); mSignalledError = true; return; } bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); GETTIME(&mTimeEnd, NULL); /* Compute time taken for decode() */ TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay, s_dec_op.u4_num_bytes_consumed); if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { mFlushNeeded = true; } if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { /* If the input did not contain picture data, then ignore * the associated timestamp */ mTimeStampsValid[timeStampIx] = false; } if (mChangingResolution && !s_dec_op.u4_output_present) { mChangingResolution = false; resetDecoder(); resetPlugin(); continue; } if (resChanged) { mChangingResolution = true; if (mFlushNeeded) { setFlushMode(); } continue; } if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { uint32_t width = s_dec_op.u4_pic_wd; uint32_t height = s_dec_op.u4_pic_ht; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { resetDecoder(); return; } } if (s_dec_op.u4_output_present) { outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts]; mTimeStampsValid[s_dec_op.u4_ts] = false; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } else { /* If in flush mode and no output is returned by the codec, * then come out of flush mode */ mIsInFlush = false; /* If EOS was recieved on input port and there is no output * from the codec, then signal EOS on output port */ if (mReceivedEOS) { outHeader->nFilledLen = 0; outHeader->nFlags |= OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; resetPlugin(); } } } if (inHeader != NULL) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } }
173,517
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nfs4_xdr_enc_getacl(struct rpc_rqst *req, struct xdr_stream *xdr, struct nfs_getaclargs *args) { struct compound_hdr hdr = { .minorversion = nfs4_xdr_minorversion(&args->seq_args), }; uint32_t replen; encode_compound_hdr(xdr, req, &hdr); encode_sequence(xdr, &args->seq_args, &hdr); encode_putfh(xdr, args->fh, &hdr); replen = hdr.replen + op_decode_hdr_maxsz + nfs4_fattr_bitmap_maxsz + 1; encode_getattr_two(xdr, FATTR4_WORD0_ACL, 0, &hdr); xdr_inline_pages(&req->rq_rcv_buf, replen << 2, args->acl_pages, args->acl_pgbase, args->acl_len); encode_nops(&hdr); } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: [email protected] Signed-off-by: Andy Adamson <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-189
static void nfs4_xdr_enc_getacl(struct rpc_rqst *req, struct xdr_stream *xdr, struct nfs_getaclargs *args) { struct compound_hdr hdr = { .minorversion = nfs4_xdr_minorversion(&args->seq_args), }; uint32_t replen; encode_compound_hdr(xdr, req, &hdr); encode_sequence(xdr, &args->seq_args, &hdr); encode_putfh(xdr, args->fh, &hdr); replen = hdr.replen + op_decode_hdr_maxsz + 1; encode_getattr_two(xdr, FATTR4_WORD0_ACL, 0, &hdr); xdr_inline_pages(&req->rq_rcv_buf, replen << 2, args->acl_pages, args->acl_pgbase, args->acl_len); xdr_set_scratch_buffer(xdr, page_address(args->acl_scratch), PAGE_SIZE); encode_nops(&hdr); }
165,721
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FrameImpl::FrameImpl(std::unique_ptr<content::WebContents> web_contents, chromium::web::FrameObserverPtr observer) : web_contents_(std::move(web_contents)), observer_(std::move(observer)) { Observe(web_contents.get()); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
FrameImpl::FrameImpl(std::unique_ptr<content::WebContents> web_contents, ContextImpl* context, fidl::InterfaceRequest<chromium::web::Frame> frame_request) : web_contents_(std::move(web_contents)), context_(context), binding_(this, std::move(frame_request)) { binding_.set_error_handler([this]() { context_->DestroyFrame(this); }); Observe(web_contents_.get()); }
172,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record) : manifest_url_(manifest_url), #if defined(OS_WIN) process_launched_by_broker_(false), #elif defined(OS_LINUX) wait_for_nacl_gdb_(false), #endif reply_msg_(NULL), #if defined(OS_WIN) debug_exception_handler_requested_(false), #endif internal_(new NaClInternal()), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), enable_exception_handling_(false), off_the_record_(off_the_record) { process_.reset(content::BrowserChildProcessHost::Create( content::PROCESS_TYPE_NACL_LOADER, this)); process_->SetName(net::FormatUrl(manifest_url_, std::string())); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNaClExceptionHandling) || getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) { enable_exception_handling_ = true; } enable_ipc_proxy_ = CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNaClIPCProxy); } 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 [email protected] 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
NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record) : manifest_url_(manifest_url), #if defined(OS_WIN) process_launched_by_broker_(false), #elif defined(OS_LINUX) wait_for_nacl_gdb_(false), #endif reply_msg_(NULL), #if defined(OS_WIN) debug_exception_handler_requested_(false), #endif internal_(new NaClInternal()), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), enable_exception_handling_(false), off_the_record_(off_the_record) { process_.reset(content::BrowserChildProcessHost::Create( content::PROCESS_TYPE_NACL_LOADER, this)); process_->SetName(net::FormatUrl(manifest_url_, std::string())); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNaClExceptionHandling) || getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) { enable_exception_handling_ = true; } }
170,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
int perf_event_refresh(struct perf_event *event, int refresh) static int _perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); _perf_event_enable(event); return 0; }
166,987
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; } Commit Message: CWE ID: CWE-200
xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->options -= XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; }
164,728
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t* buf, int buf_size) { int size, i; uint8_t *ppcm[4] = {0}; if (buf_size < DV_PROFILE_BYTES || !(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) || buf_size < c->sys->frame_size) { return -1; /* Broken frame, or not enough data */ } /* Queueing audio packet */ /* FIXME: in case of no audio/bad audio we have to do something */ size = dv_extract_audio_info(c, buf); for (i = 0; i < c->ach; i++) { c->audio_pkt[i].size = size; c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate; ppcm[i] = c->audio_buf[i]; } dv_extract_audio(buf, ppcm, c->sys); /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ if (buf[1] & 0x0C) { c->audio_pkt[2].size = c->audio_pkt[3].size = 0; } else { c->audio_pkt[0].size = c->audio_pkt[1].size = 0; c->abytes += size; } } else { c->abytes += size; } Commit Message: CWE ID: CWE-119
int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t* buf, int buf_size) { int size, i; uint8_t *ppcm[4] = {0}; if (buf_size < DV_PROFILE_BYTES || !(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) || buf_size < c->sys->frame_size) { return -1; /* Broken frame, or not enough data */ } /* Queueing audio packet */ /* FIXME: in case of no audio/bad audio we have to do something */ size = dv_extract_audio_info(c, buf); for (i = 0; i < c->ach; i++) { c->audio_pkt[i].size = size; c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate; ppcm[i] = c->audio_buf[i]; } if (c->ach) dv_extract_audio(buf, ppcm, c->sys); /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ if (buf[1] & 0x0C) { c->audio_pkt[2].size = c->audio_pkt[3].size = 0; } else { c->audio_pkt[0].size = c->audio_pkt[1].size = 0; c->abytes += size; } } else { c->abytes += size; }
165,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian, const unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8 ) | (buffer[0])); return((unsigned int) (value & 0xffffffff)); } value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); return((unsigned int) (value & 0xffffffff)); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian, const unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; return(value & 0xffffffff); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; return(value & 0xffffffff); }
169,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AXLayoutObject::supportsARIADragging() const { const AtomicString& grabbed = getAttribute(aria_grabbedAttr); return equalIgnoringCase(grabbed, "true") || equalIgnoringCase(grabbed, "false"); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXLayoutObject::supportsARIADragging() const { const AtomicString& grabbed = getAttribute(aria_grabbedAttr); return equalIgnoringASCIICase(grabbed, "true") || equalIgnoringASCIICase(grabbed, "false"); }
171,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: file_ms_alloc(int flags) { struct magic_set *ms; size_t i, len; if ((ms = CAST(struct magic_set *, calloc((size_t)1, sizeof(struct magic_set)))) == NULL) return NULL; if (magic_setflags(ms, flags) == -1) { errno = EINVAL; goto free; } ms->o.buf = ms->o.pbuf = NULL; len = (ms->c.len = 10) * sizeof(*ms->c.li); if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL) goto free; ms->event_flags = 0; ms->error = -1; for (i = 0; i < MAGIC_SETS; i++) ms->mlist[i] = NULL; ms->file = "unknown"; ms->line = 0; ms->indir_max = FILE_INDIR_MAX; ms->name_max = FILE_NAME_MAX; ms->elf_shnum_max = FILE_ELF_SHNUM_MAX; ms->elf_phnum_max = FILE_ELF_PHNUM_MAX; return ms; free: free(ms); return NULL; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
file_ms_alloc(int flags) { struct magic_set *ms; size_t i, len; if ((ms = CAST(struct magic_set *, calloc((size_t)1, sizeof(struct magic_set)))) == NULL) return NULL; if (magic_setflags(ms, flags) == -1) { errno = EINVAL; goto free; } ms->o.buf = ms->o.pbuf = NULL; len = (ms->c.len = 10) * sizeof(*ms->c.li); if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL) goto free; ms->event_flags = 0; ms->error = -1; for (i = 0; i < MAGIC_SETS; i++) ms->mlist[i] = NULL; ms->file = "unknown"; ms->line = 0; ms->indir_max = FILE_INDIR_MAX; ms->name_max = FILE_NAME_MAX; ms->elf_shnum_max = FILE_ELF_SHNUM_MAX; ms->elf_phnum_max = FILE_ELF_PHNUM_MAX; ms->elf_notes_max = FILE_ELF_NOTES_MAX; return ms; free: free(ms); return NULL; }
166,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: error::Error GLES2DecoderImpl::HandleDrawElements( uint32 immediate_data_size, const gles2::DrawElements& c) { if (!bound_element_array_buffer_ || bound_element_array_buffer_->IsDeleted()) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: No element array buffer bound"); return error::kNoError; } GLenum mode = c.mode; GLsizei count = c.count; GLenum type = c.type; int32 offset = c.index_offset; if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0"); return error::kNoError; } if (offset < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0"); return error::kNoError; } if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM"); return error::kNoError; } if (!validators_->index_type.IsValid(type)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawElements")) { return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed; if (!bound_element_array_buffer_->GetMaxValueForRange( offset, count, type, &max_vertex_accessed)) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: range out of bounds for buffer"); return error::kNoError; } if (IsDrawValid(max_vertex_accessed)) { bool simulated_attrib_0 = SimulateAttrib0(max_vertex_accessed); bool simulated_fixed_attribs = false; if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) { bool textures_set = SetBlackTextureForNonRenderableTextures(); ApplyDirtyState(); const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset); glDrawElements(mode, count, type, indices); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements."; return error::kLostContext; } } return error::kNoError; } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 [email protected] Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
error::Error GLES2DecoderImpl::HandleDrawElements( uint32 immediate_data_size, const gles2::DrawElements& c) { if (!bound_element_array_buffer_ || bound_element_array_buffer_->IsDeleted()) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: No element array buffer bound"); return error::kNoError; } GLenum mode = c.mode; GLsizei count = c.count; GLenum type = c.type; int32 offset = c.index_offset; if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0"); return error::kNoError; } if (offset < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0"); return error::kNoError; } if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM"); return error::kNoError; } if (!validators_->index_type.IsValid(type)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawElements")) { return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed; if (!bound_element_array_buffer_->GetMaxValueForRange( offset, count, type, &max_vertex_accessed)) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: range out of bounds for buffer"); return error::kNoError; } if (IsDrawValid(max_vertex_accessed)) { bool simulated_attrib_0 = false; if (!SimulateAttrib0(max_vertex_accessed, &simulated_attrib_0)) { return error::kNoError; } bool simulated_fixed_attribs = false; if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) { bool textures_set = SetBlackTextureForNonRenderableTextures(); ApplyDirtyState(); const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset); glDrawElements(mode, count, type, indices); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements."; return error::kLostContext; } } return error::kNoError; }
170,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int skt_read(int fd, void *p, size_t len) { int read; struct pollfd pfd; struct timespec ts; FNLOG(); ts_log("skt_read recv", len, NULL); if ((read = recv(fd, p, len, MSG_NOSIGNAL)) == -1) { ERROR("write failed with errno=%d\n", errno); return -1; } return read; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int skt_read(int fd, void *p, size_t len) { int read; struct pollfd pfd; struct timespec ts; FNLOG(); ts_log("skt_read recv", len, NULL); if ((read = TEMP_FAILURE_RETRY(recv(fd, p, len, MSG_NOSIGNAL))) == -1) { ERROR("write failed with errno=%d\n", errno); return -1; } return read; }
173,428
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int net_get(int s, void *arg, int *len) { struct net_hdr nh; int plen; if (net_read_exact(s, &nh, sizeof(nh)) == -1) { return -1; } plen = ntohl(nh.nh_len); if (!(plen <= *len)) printf("PLEN %d type %d len %d\n", plen, nh.nh_type, *len); assert(plen <= *len); /* XXX */ *len = plen; if ((*len) && (net_read_exact(s, arg, *len) == -1)) { return -1; } return nh.nh_type; } Commit Message: OSdep: Fixed segmentation fault that happens with a malicious server sending a negative length (Closes #16 on GitHub). git-svn-id: http://svn.aircrack-ng.org/trunk@2419 28c6078b-6c39-48e3-add9-af49d547ecab CWE ID: CWE-20
int net_get(int s, void *arg, int *len) { struct net_hdr nh; int plen; if (net_read_exact(s, &nh, sizeof(nh)) == -1) { return -1; } plen = ntohl(nh.nh_len); if (!(plen <= *len)) printf("PLEN %d type %d len %d\n", plen, nh.nh_type, *len); assert(plen <= *len && plen > 0); /* XXX */ *len = plen; if ((*len) && (net_read_exact(s, arg, *len) == -1)) { return -1; } return nh.nh_type; }
168,912
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_add(PNG_CONST image_transform **this, unsigned int max, png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { for (;;) /* until we manage to add something */ { png_uint_32 mask; image_transform *list; /* Find the next counter value, if the counter is zero this is the start * of the list. This routine always returns the current counter (not the * next) so it returns 0 at the end and expects 0 at the beginning. */ if (counter == 0) /* first time */ { image_transform_reset_count(); if (max <= 1) counter = 1; else counter = random_32(); } else /* advance the counter */ { switch (max) { case 0: ++counter; break; case 1: counter <<= 1; break; default: counter = random_32(); break; } } /* Now add all these items, if possible */ *this = &image_transform_end; list = image_transform_first; mask = 1; /* Go through the whole list adding anything that the counter selects: */ while (list != &image_transform_end) { if ((counter & mask) != 0 && list->enable && (max == 0 || list->local_use < max)) { /* Candidate to add: */ if (list->add(list, this, colour_type, bit_depth) || max == 0) { /* Added, so add to the name too. */ *pos = safecat(name, sizeof_name, *pos, " +"); *pos = safecat(name, sizeof_name, *pos, list->name); } else { /* Not useful and max>0, so remove it from *this: */ *this = list->next; list->next = 0; /* And, since we know it isn't useful, stop it being added again * in this run: */ list->local_use = max; } } mask <<= 1; list = list->list; } /* Now if anything was added we have something to do. */ if (*this != &image_transform_end) return counter; /* Nothing added, but was there anything in there to add? */ if (!image_transform_test_counter(counter, max)) return 0; } } 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_add(PNG_CONST image_transform **this, unsigned int max, image_transform_add(const image_transform **this, unsigned int max, png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { for (;;) /* until we manage to add something */ { png_uint_32 mask; image_transform *list; /* Find the next counter value, if the counter is zero this is the start * of the list. This routine always returns the current counter (not the * next) so it returns 0 at the end and expects 0 at the beginning. */ if (counter == 0) /* first time */ { image_transform_reset_count(); if (max <= 1) counter = 1; else counter = random_32(); } else /* advance the counter */ { switch (max) { case 0: ++counter; break; case 1: counter <<= 1; break; default: counter = random_32(); break; } } /* Now add all these items, if possible */ *this = &image_transform_end; list = image_transform_first; mask = 1; /* Go through the whole list adding anything that the counter selects: */ while (list != &image_transform_end) { if ((counter & mask) != 0 && list->enable && (max == 0 || list->local_use < max)) { /* Candidate to add: */ if (list->add(list, this, colour_type, bit_depth) || max == 0) { /* Added, so add to the name too. */ *pos = safecat(name, sizeof_name, *pos, " +"); *pos = safecat(name, sizeof_name, *pos, list->name); } else { /* Not useful and max>0, so remove it from *this: */ *this = list->next; list->next = 0; /* And, since we know it isn't useful, stop it being added again * in this run: */ list->local_use = max; } } mask <<= 1; list = list->list; } /* Now if anything was added we have something to do. */ if (*this != &image_transform_end) return counter; /* Nothing added, but was there anything in there to add? */ if (!image_transform_test_counter(counter, max)) return 0; } }
173,619
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error) { guint32 val; GArray *array; array = g_array_new (FALSE, TRUE, sizeof (guint32)); while (reqlen > 0) { val = 42; g_array_append_val (array, val); val = 26; g_array_append_val (array, val); reqlen--; } val = 2; g_array_append_val (array, val); *ret = array; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error)
165,118
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); int status; len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) //error or underflow return status; if (status > 0) //interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) //we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) int status; //#ifdef _DEBUG // long long total, available; // status = pReader->Length(&total, &available); // assert(status >= 0); // assert((total < 0) || (available <= total)); // assert(pos < available); // assert((available - pos) >= 1); //assume here max u-int len is 8 //#endif len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) // error or underflow return status; if (status > 0) // interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } //#ifdef _DEBUG // assert((available - pos) >= len); //#endif long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; }
174,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ax25_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; ax25_cb *ax25; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; switch (sock->type) { case SOCK_DGRAM: if (protocol == 0 || protocol == PF_AX25) protocol = AX25_P_TEXT; break; case SOCK_SEQPACKET: switch (protocol) { case 0: case PF_AX25: /* For CLX */ protocol = AX25_P_TEXT; break; case AX25_P_SEGMENT: #ifdef CONFIG_INET case AX25_P_ARP: case AX25_P_IP: #endif #ifdef CONFIG_NETROM case AX25_P_NETROM: #endif #ifdef CONFIG_ROSE case AX25_P_ROSE: #endif return -ESOCKTNOSUPPORT; #ifdef CONFIG_NETROM_MODULE case AX25_P_NETROM: if (ax25_protocol_is_registered(AX25_P_NETROM)) return -ESOCKTNOSUPPORT; break; #endif #ifdef CONFIG_ROSE_MODULE case AX25_P_ROSE: if (ax25_protocol_is_registered(AX25_P_ROSE)) return -ESOCKTNOSUPPORT; #endif default: break; } break; case SOCK_RAW: break; default: return -ESOCKTNOSUPPORT; } sk = sk_alloc(net, PF_AX25, GFP_ATOMIC, &ax25_proto, kern); if (sk == NULL) return -ENOMEM; ax25 = ax25_sk(sk)->cb = ax25_create_cb(); if (!ax25) { sk_free(sk); return -ENOMEM; } sock_init_data(sock, sk); sk->sk_destruct = ax25_free_sock; sock->ops = &ax25_proto_ops; sk->sk_protocol = protocol; ax25->sk = sk; return 0; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int ax25_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; ax25_cb *ax25; if (protocol < 0 || protocol > SK_PROTOCOL_MAX) return -EINVAL; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; switch (sock->type) { case SOCK_DGRAM: if (protocol == 0 || protocol == PF_AX25) protocol = AX25_P_TEXT; break; case SOCK_SEQPACKET: switch (protocol) { case 0: case PF_AX25: /* For CLX */ protocol = AX25_P_TEXT; break; case AX25_P_SEGMENT: #ifdef CONFIG_INET case AX25_P_ARP: case AX25_P_IP: #endif #ifdef CONFIG_NETROM case AX25_P_NETROM: #endif #ifdef CONFIG_ROSE case AX25_P_ROSE: #endif return -ESOCKTNOSUPPORT; #ifdef CONFIG_NETROM_MODULE case AX25_P_NETROM: if (ax25_protocol_is_registered(AX25_P_NETROM)) return -ESOCKTNOSUPPORT; break; #endif #ifdef CONFIG_ROSE_MODULE case AX25_P_ROSE: if (ax25_protocol_is_registered(AX25_P_ROSE)) return -ESOCKTNOSUPPORT; #endif default: break; } break; case SOCK_RAW: break; default: return -ESOCKTNOSUPPORT; } sk = sk_alloc(net, PF_AX25, GFP_ATOMIC, &ax25_proto, kern); if (sk == NULL) return -ENOMEM; ax25 = ax25_sk(sk)->cb = ax25_create_cb(); if (!ax25) { sk_free(sk); return -ENOMEM; } sock_init_data(sock, sk); sk->sk_destruct = ax25_free_sock; sock->ops = &ax25_proto_ops; sk->sk_protocol = protocol; ax25->sk = sk; return 0; }
166,562
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AudioOutputAuthorizationHandler::GetDeviceParameters( AuthorizationCompletedCallback cb, const std::string& raw_device_id) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!raw_device_id.empty()); base::PostTaskAndReplyWithResult( audio_manager_->GetTaskRunner(), FROM_HERE, base::Bind(&GetDeviceParametersOnDeviceThread, base::Unretained(audio_manager_), raw_device_id), base::Bind(&AudioOutputAuthorizationHandler::DeviceParametersReceived, weak_factory_.GetWeakPtr(), std::move(cb), false, raw_device_id)); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID:
void AudioOutputAuthorizationHandler::GetDeviceParameters( AuthorizationCompletedCallback cb, const std::string& raw_device_id) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!raw_device_id.empty()); audio_system_->GetOutputStreamParameters( raw_device_id, base::Bind(&AudioOutputAuthorizationHandler::DeviceParametersReceived, weak_factory_.GetWeakPtr(), std::move(cb), false, raw_device_id)); }
171,981
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScriptPromise BluetoothRemoteGATTCharacteristic::getDescriptorsImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, const String& descriptor) { if (!getGatt()->connected()) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kGATTServerNotConnected)); } if (!getGatt()->device()->isValidCharacteristic( m_characteristic->instance_id)) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kInvalidCharacteristic)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); getGatt()->AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); WTF::Optional<String> uuid = WTF::nullopt; if (!descriptor.isEmpty()) uuid = descriptor; service->RemoteCharacteristicGetDescriptors( m_characteristic->instance_id, quantity, uuid, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTCharacteristic::GetDescriptorsCallback, wrapPersistent(this), m_characteristic->instance_id, quantity, wrapPersistent(resolver)))); return promise; } Commit Message: Allow serialization of empty bluetooth uuids. This change allows the passing WTF::Optional<String> types as bluetooth.mojom.UUID optional parameter without needing to ensure the passed object isn't empty. BUG=None R=juncai, dcheng Review-Url: https://codereview.chromium.org/2646613003 Cr-Commit-Position: refs/heads/master@{#445809} CWE ID: CWE-119
ScriptPromise BluetoothRemoteGATTCharacteristic::getDescriptorsImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, const String& descriptorsUUID) { if (!getGatt()->connected()) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kGATTServerNotConnected)); } if (!getGatt()->device()->isValidCharacteristic( m_characteristic->instance_id)) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kInvalidCharacteristic)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); getGatt()->AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); service->RemoteCharacteristicGetDescriptors( m_characteristic->instance_id, quantity, descriptorsUUID, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTCharacteristic::GetDescriptorsCallback, wrapPersistent(this), m_characteristic->instance_id, quantity, wrapPersistent(resolver)))); return promise; }
172,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int _make_decode_table(codebook *s,char *lengthlist,long quantvals, oggpack_buffer *opb,int maptype){ int i; ogg_uint32_t *work; if (!lengthlist) return 1; if(s->dec_nodeb==4){ /* Over-allocate by using s->entries instead of used_entries. * This means that we can use s->entries to enforce size in * _make_words without messing up length list looping. * This probably wastes a bit of space, but it shouldn't * impact behavior or size too much. */ s->dec_table=_ogg_malloc((s->entries*2+1)*sizeof(*work)); if (!s->dec_table) return 1; /* +1 (rather than -2) is to accommodate 0 and 1 sized books, which are specialcased to nodeb==4 */ if(_make_words(lengthlist,s->entries, s->dec_table,quantvals,s,opb,maptype))return 1; return 0; } if (s->used_entries > INT_MAX/2 || s->used_entries*2 > INT_MAX/((long) sizeof(*work)) - 1) return 1; /* Overallocate as above */ work=calloc((s->entries*2+1),sizeof(*work)); if (!work) return 1; if(_make_words(lengthlist,s->entries,work,quantvals,s,opb,maptype)) goto error_out; if (s->used_entries > INT_MAX/(s->dec_leafw+1)) goto error_out; if (s->dec_nodeb && s->used_entries * (s->dec_leafw+1) > INT_MAX/s->dec_nodeb) goto error_out; s->dec_table=_ogg_malloc((s->used_entries*(s->dec_leafw+1)-2)* s->dec_nodeb); if (!s->dec_table) goto error_out; if(s->dec_leafw==1){ switch(s->dec_nodeb){ case 1: for(i=0;i<s->used_entries*2-2;i++) ((unsigned char *)s->dec_table)[i]=(unsigned char) (((work[i] & 0x80000000UL) >> 24) | work[i]); break; case 2: for(i=0;i<s->used_entries*2-2;i++) ((ogg_uint16_t *)s->dec_table)[i]=(ogg_uint16_t) (((work[i] & 0x80000000UL) >> 16) | work[i]); break; } }else{ /* more complex; we have to do a two-pass repack that updates the node indexing. */ long top=s->used_entries*3-2; if(s->dec_nodeb==1){ unsigned char *out=(unsigned char *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i] & 0xff; out[top+3]=work[i+1] & 0xff; }else{ top-=3; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i+1] & 0xff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } }else{ ogg_uint16_t *out=(ogg_uint16_t *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i] & 0xffff; out[top+3]=work[i+1] & 0xffff; }else{ top-=3; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xffff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i+1] & 0xffff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } } } free(work); return 0; error_out: free(work); return 1; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static int _make_decode_table(codebook *s,char *lengthlist,long quantvals, oggpack_buffer *opb,int maptype){ int i; ogg_uint32_t *work; if (!lengthlist) return 1; if(s->dec_nodeb==4){ /* Over-allocate by using s->entries instead of used_entries. * This means that we can use s->entries to enforce size in * _make_words without messing up length list looping. * This probably wastes a bit of space, but it shouldn't * impact behavior or size too much. */ s->dec_table=_ogg_malloc((s->entries*2+1)*sizeof(*work)); if (!s->dec_table) return 1; /* +1 (rather than -2) is to accommodate 0 and 1 sized books, which are specialcased to nodeb==4 */ if(_make_words(lengthlist,s->entries, s->dec_table,quantvals,s,opb,maptype))return 1; return 0; } if (s->used_entries > INT_MAX/2 || s->used_entries*2 > INT_MAX/((long) sizeof(*work)) - 1) return 1; /* Overallocate as above */ work=calloc((s->entries*2+1),sizeof(*work)); if (!work) return 1; if(_make_words(lengthlist,s->entries,work,quantvals,s,opb,maptype)) goto error_out; if (s->used_entries > INT_MAX/(s->dec_leafw+1)) goto error_out; if (s->dec_nodeb && s->used_entries * (s->dec_leafw+1) > INT_MAX/s->dec_nodeb) goto error_out; s->dec_table=_ogg_malloc((s->used_entries*(s->dec_leafw+1)-2)* s->dec_nodeb); if (!s->dec_table) goto error_out; if(s->dec_leafw==1){ switch(s->dec_nodeb){ case 1: for(i=0;i<s->used_entries*2-2;i++) ((unsigned char *)s->dec_table)[i]=(unsigned char) (((work[i] & 0x80000000UL) >> 24) | work[i]); break; case 2: for(i=0;i<s->used_entries*2-2;i++) ((ogg_uint16_t *)s->dec_table)[i]=(ogg_uint16_t) (((work[i] & 0x80000000UL) >> 16) | work[i]); break; } }else{ /* more complex; we have to do a two-pass repack that updates the node indexing. */ long top=s->used_entries*3-2; if(s->dec_nodeb==1){ unsigned char *out=(unsigned char *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i] & 0xff; out[top+3]=work[i+1] & 0xff; }else{ top-=3; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i+1] & 0xff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } }else{ ogg_uint16_t *out=(ogg_uint16_t *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i] & 0xffff; out[top+3]=work[i+1] & 0xffff; }else{ top-=3; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xffff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i+1] & 0xffff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } } } free(work); return 0; error_out: free(work); return 1; }
173,981
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void update_exception_bitmap(struct kvm_vcpu *vcpu) { u32 eb; eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | (1u << NM_VECTOR) | (1u << DB_VECTOR); if ((vcpu->guest_debug & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) eb |= 1u << BP_VECTOR; if (to_vmx(vcpu)->rmode.vm86_active) eb = ~0; if (enable_ept) eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */ if (vcpu->fpu_active) eb &= ~(1u << NM_VECTOR); /* When we are running a nested L2 guest and L1 specified for it a * certain exception bitmap, we must trap the same exceptions and pass * them to L1. When running L2, we will only handle the exceptions * specified above if L1 did not want them. */ if (is_guest_mode(vcpu)) eb |= get_vmcs12(vcpu)->exception_bitmap; vmcs_write32(EXCEPTION_BITMAP, eb); } Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399
static void update_exception_bitmap(struct kvm_vcpu *vcpu) { u32 eb; eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR); if ((vcpu->guest_debug & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) eb |= 1u << BP_VECTOR; if (to_vmx(vcpu)->rmode.vm86_active) eb = ~0; if (enable_ept) eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */ if (vcpu->fpu_active) eb &= ~(1u << NM_VECTOR); /* When we are running a nested L2 guest and L1 specified for it a * certain exception bitmap, we must trap the same exceptions and pass * them to L1. When running L2, we will only handle the exceptions * specified above if L1 did not want them. */ if (is_guest_mode(vcpu)) eb |= get_vmcs12(vcpu)->exception_bitmap; vmcs_write32(EXCEPTION_BITMAP, eb); }
166,600
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; size_t fname_len, localname_len = 0; php_stream *resource; zval zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } php_stream_to_zval(resource, &zresource); phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource); zval_ptr_dtor(&zresource); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; size_t fname_len, localname_len = 0; php_stream *resource; zval zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } php_stream_to_zval(resource, &zresource); phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource); zval_ptr_dtor(&zresource); }
165,070
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_one_file(Image *image) { if (!(image->opts & READ_FILE) || (image->opts & USE_STDIO)) { /* memory or stdio. */ FILE *f = fopen(image->file_name, "rb"); if (f != NULL) { if (image->opts & READ_FILE) image->input_file = f; else /* memory */ { if (fseek(f, 0, SEEK_END) == 0) { long int cb = ftell(f); if (cb > 0 && (unsigned long int)cb < (size_t)~(size_t)0) { png_bytep b = voidcast(png_bytep, malloc((size_t)cb)); if (b != NULL) { rewind(f); if (fread(b, (size_t)cb, 1, f) == 1) { fclose(f); image->input_memory_size = cb; image->input_memory = b; } else { free(b); return logclose(image, f, image->file_name, ": read failed: "); } } else return logclose(image, f, image->file_name, ": out of memory: "); } else if (cb == 0) return logclose(image, f, image->file_name, ": zero length: "); else return logclose(image, f, image->file_name, ": tell failed: "); } else return logclose(image, f, image->file_name, ": seek failed: "); } } else return logerror(image, image->file_name, ": open failed: ", strerror(errno)); } return read_file(image, FORMAT_NO_CHANGE, NULL); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
read_one_file(Image *image) { if (!(image->opts & READ_FILE) || (image->opts & USE_STDIO)) { /* memory or stdio. */ FILE *f = fopen(image->file_name, "rb"); if (f != NULL) { if (image->opts & READ_FILE) image->input_file = f; else /* memory */ { if (fseek(f, 0, SEEK_END) == 0) { long int cb = ftell(f); if (cb > 0) { #ifndef __COVERITY__ if ((unsigned long int)cb <= (size_t)~(size_t)0) #endif { png_bytep b = voidcast(png_bytep, malloc((size_t)cb)); if (b != NULL) { rewind(f); if (fread(b, (size_t)cb, 1, f) == 1) { fclose(f); image->input_memory_size = cb; image->input_memory = b; } else { free(b); return logclose(image, f, image->file_name, ": read failed: "); } } else return logclose(image, f, image->file_name, ": out of memory: "); } else return logclose(image, f, image->file_name, ": file too big for this architecture: "); /* cb is the length of the file as a (long) and * this is greater than the maximum amount of * memory that can be requested from malloc. */ } else if (cb == 0) return logclose(image, f, image->file_name, ": zero length: "); else return logclose(image, f, image->file_name, ": tell failed: "); } else return logclose(image, f, image->file_name, ": seek failed: "); } } else return logerror(image, image->file_name, ": open failed: ", strerror(errno)); } return read_file(image, FORMAT_NO_CHANGE, NULL); }
173,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RemoveInvalidFilesFromPersistentDirectory( const GDataCacheMetadataMap::ResourceIdToFilePathMap& persistent_file_map, const GDataCacheMetadataMap::ResourceIdToFilePathMap& outgoing_file_map, GDataCacheMetadataMap::CacheMap* cache_map) { for (GDataCacheMetadataMap::ResourceIdToFilePathMap::const_iterator iter = persistent_file_map.begin(); iter != persistent_file_map.end(); ++iter) { const std::string& resource_id = iter->first; const FilePath& file_path = iter->second; GDataCacheMetadataMap::CacheMap::iterator cache_map_iter = cache_map->find(resource_id); if (cache_map_iter != cache_map->end()) { const GDataCache::CacheEntry& cache_entry = cache_map_iter->second; if (cache_entry.IsDirty() && outgoing_file_map.count(resource_id) == 0) { LOG(WARNING) << "Removing dirty-but-not-committed file: " << file_path.value(); file_util::Delete(file_path, false); cache_map->erase(cache_map_iter); } if (!cache_entry.IsDirty() && !cache_entry.IsPinned()) { LOG(WARNING) << "Removing persistent-but-dangling file: " << file_path.value(); file_util::Delete(file_path, false); cache_map->erase(cache_map_iter); } } } } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void RemoveInvalidFilesFromPersistentDirectory(
170,867