instruction
stringclasses
1 value
input
stringlengths
56
241k
output
int64
0
1
__index_level_0__
int64
0
175k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content) { if (importLoader()) return; if (equalIgnoringCase(equiv, "content-security-policy")) contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta); else if (equalIgnoringCase(equiv, "content-security-policy-report-only")) contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta); else ASSERT_NOT_REACHED(); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 R=haraken@chromium.org Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254
0
127,537
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: struct r_bin_pe_addr_t *PE_(check_unknow) (struct PE_(r_bin_pe_obj_t) *bin) { struct r_bin_pe_addr_t *entry; if (!bin || !bin->b) { return 0LL; } ut8 *b = calloc (1, 512); if (!b) { return NULL; } entry = PE_ (r_bin_pe_get_entrypoint) (bin); if (r_buf_read_at (bin->b, entry->paddr, b, 512) < 1) { bprintf ("Warning: Cannot read entry at 0x%08"PFMT64x"\n", entry->paddr); free (entry); free (b); return NULL; } /* Decode the jmp instruction, this gets the address of the 'main' function for PE produced by a compiler whose name someone forgot to write down. */ if (b[367] == 0xe8) { const st32 jmp_dst = (st32) r_read_le32 (&b[368]); entry->paddr += 367 + 5 + jmp_dst; entry->vaddr += 367 + 5 + jmp_dst; free (b); return entry; } int i; for (i = 0; i < 512 - 16 ; i++) { if (!memcmp (b + i, "\xff\x15", 2)) { if (b[i+6] == 0x50) { if (b[i+7] == 0xe8) { const st32 call_dst = (st32) r_read_le32 (&b[i + 8]); entry->paddr = entry->vaddr - entry->paddr; entry->vaddr += (i + 7 + 5 + (long)call_dst); entry->paddr += entry->vaddr; free (b); return entry; } } } } free (entry); free (b); return NULL; } Commit Message: Fix crash in pe CWE ID: CWE-125
0
82,896
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static ssize_t ucma_set_option(struct ucma_file *file, const char __user *inbuf, int in_len, int out_len) { struct rdma_ucm_set_option cmd; struct ucma_context *ctx; void *optval; int ret; if (copy_from_user(&cmd, inbuf, sizeof(cmd))) return -EFAULT; if (unlikely(cmd.optlen > KMALLOC_MAX_SIZE)) return -EINVAL; ctx = ucma_get_ctx(file, cmd.id); if (IS_ERR(ctx)) return PTR_ERR(ctx); optval = memdup_user(u64_to_user_ptr(cmd.optval), cmd.optlen); if (IS_ERR(optval)) { ret = PTR_ERR(optval); goto out; } ret = ucma_set_option_level(ctx, cmd.level, cmd.optname, optval, cmd.optlen); kfree(optval); out: ucma_put_ctx(ctx); return ret; } Commit Message: infiniband: fix a possible use-after-free bug ucma_process_join() will free the new allocated "mc" struct, if there is any error after that, especially the copy_to_user(). But in parallel, ucma_leave_multicast() could find this "mc" through idr_find() before ucma_process_join() frees it, since it is already published. So "mc" could be used in ucma_leave_multicast() after it is been allocated and freed in ucma_process_join(), since we don't refcnt it. Fix this by separating "publish" from ID allocation, so that we can get an ID first and publish it later after copy_to_user(). Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support") Reported-by: Noam Rathaus <noamr@beyondsecurity.com> Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com> Signed-off-by: Jason Gunthorpe <jgg@mellanox.com> CWE ID: CWE-416
0
79,152
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebMediaPlayerMS::ExitPictureInPicture( blink::WebMediaPlayer::PipWindowClosedCallback callback) { delegate_->DidPictureInPictureModeEnd(delegate_id_, std::move(callback)); OnPictureInPictureModeEnded(); } 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 <hubbe@chromium.org> Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Reviewed-by: Raymond Toy <rtoy@chromium.org> Commit-Queue: Yutaka Hirano <yhirano@chromium.org> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
0
144,144
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: Dispatcher::Dispatcher(DispatcherDelegate* delegate) : delegate_(delegate), content_watcher_(new ContentWatcher()), source_map_(&ResourceBundle::GetSharedInstance()), v8_schema_registry_(new V8SchemaRegistry), user_script_set_manager_observer_(this), webrequest_used_(false) { const base::CommandLine& command_line = *(base::CommandLine::ForCurrentProcess()); set_idle_notifications_ = command_line.HasSwitch(switches::kExtensionProcess) || command_line.HasSwitch(::switches::kSingleProcess); if (set_idle_notifications_) { RenderThread::Get()->SetIdleNotificationDelayInMs( kInitialExtensionIdleHandlerDelayMs); } script_context_set_.reset(new ScriptContextSet(&active_extension_ids_)); user_script_set_manager_.reset(new UserScriptSetManager()); script_injection_manager_.reset( new ScriptInjectionManager(user_script_set_manager_.get())); user_script_set_manager_observer_.Add(user_script_set_manager_.get()); request_sender_.reset(new RequestSender(this)); PopulateSourceMap(); WakeEventPage::Get()->Init(RenderThread::Get()); RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension()); using RegisterFunction = void (*)(const WebString&); RegisterFunction register_functions[] = { WebSecurityPolicy::registerURLSchemeAsSecure, WebSecurityPolicy::registerURLSchemeAsCORSEnabled, WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy, WebSecurityPolicy::registerURLSchemeAsSupportingFetchAPI, WebSecurityPolicy::registerURLSchemeAsFirstPartyWhenTopLevel, }; WebString extension_scheme(base::ASCIIToUTF16(kExtensionScheme)); WebString extension_resource_scheme(base::ASCIIToUTF16( kExtensionResourceScheme)); for (RegisterFunction func : register_functions) { func(extension_scheme); func(extension_resource_scheme); } if (set_idle_notifications_) { forced_idle_timer_.reset(new base::RepeatingTimer); forced_idle_timer_->Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs), RenderThread::Get(), &RenderThread::IdleHandler); } for (const std::string& extension_id : active_extension_ids_) { const Extension* extension = RendererExtensionRegistry::Get()->GetByID(extension_id); CHECK(extension); InitOriginPermissions(extension); } EnableCustomElementWhiteList(); } 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
0
132,536
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline const unsigned char *PushDoublePixel(QuantumInfo *quantum_info, const unsigned char *magick_restrict pixels,double *pixel) { double *p; unsigned char quantum[8]; if (quantum_info->endian == LSBEndian) { quantum[0]=(*pixels++); quantum[1]=(*pixels++); quantum[2]=(*pixels++); quantum[3]=(*pixels++); quantum[4]=(*pixels++); quantum[5]=(*pixels++); quantum[6]=(*pixels++); quantum[7]=(*pixels++); p=(double *) quantum; *pixel=(*p); *pixel-=quantum_info->minimum; *pixel*=quantum_info->scale; return(pixels); } quantum[7]=(*pixels++); quantum[6]=(*pixels++); quantum[5]=(*pixels++); quantum[4]=(*pixels++); quantum[3]=(*pixels++); quantum[2]=(*pixels++); quantum[1]=(*pixels++); quantum[0]=(*pixels++); p=(double *) quantum; *pixel=(*p); *pixel-=quantum_info->minimum; *pixel*=quantum_info->scale; return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/129 CWE ID: CWE-284
0
71,883
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PassRefPtr<DocumentFragment> Range::cloneContents(ExceptionCode& ec) { if (!m_start.container()) { ec = INVALID_STATE_ERR; return 0; } return processContents(CLONE_CONTENTS, ec); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264
0
100,225
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: session_proctitle(Session *s) { if (s->pw == NULL) error("no user for session %d", s->self); else setproctitle("%s@%s", s->pw->pw_name, session_tty_list()); } Commit Message: CWE ID: CWE-264
0
14,421
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xsltFormatNumberFunction(xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr numberObj = NULL; xmlXPathObjectPtr formatObj = NULL; xmlXPathObjectPtr decimalObj = NULL; xsltStylesheetPtr sheet; xsltDecimalFormatPtr formatValues; xmlChar *result; xsltTransformContextPtr tctxt; tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) return; sheet = tctxt->style; if (sheet == NULL) return; formatValues = sheet->decimalFormat; switch (nargs) { case 3: CAST_TO_STRING; decimalObj = valuePop(ctxt); formatValues = xsltDecimalFormatGetByName(sheet, decimalObj->stringval); if (formatValues == NULL) { xsltTransformError(tctxt, NULL, NULL, "format-number() : undeclared decimal format '%s'\n", decimalObj->stringval); } /* Intentional fall-through */ case 2: CAST_TO_STRING; formatObj = valuePop(ctxt); CAST_TO_NUMBER; numberObj = valuePop(ctxt); break; default: XP_ERROR(XPATH_INVALID_ARITY); } if (formatValues != NULL) { if (xsltFormatNumberConversion(formatValues, formatObj->stringval, numberObj->floatval, &result) == XPATH_EXPRESSION_OK) { valuePush(ctxt, xmlXPathNewString(result)); xmlFree(result); } } xmlXPathFreeObject(numberObj); xmlXPathFreeObject(formatObj); xmlXPathFreeObject(decimalObj); } Commit Message: Fix harmless memory error in generate-id. BUG=140368 Review URL: https://chromiumcodereview.appspot.com/10823168 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@149998 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
106,468
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline void jmp_rel(struct x86_emulate_ctxt *ctxt, int rel) { register_address_increment(ctxt, &ctxt->_eip, rel); } Commit Message: KVM: x86: fix missing checks in syscall emulation On hosts without this patch, 32bit guests will crash (and 64bit guests may behave in a wrong way) for example by simply executing following nasm-demo-application: [bits 32] global _start SECTION .text _start: syscall (I tested it with winxp and linux - both always crashed) Disassembly of section .text: 00000000 <_start>: 0: 0f 05 syscall The reason seems a missing "invalid opcode"-trap (int6) for the syscall opcode "0f05", which is not available on Intel CPUs within non-longmodes, as also on some AMD CPUs within legacy-mode. (depending on CPU vendor, MSR_EFER and cpuid) Because previous mentioned OSs may not engage corresponding syscall target-registers (STAR, LSTAR, CSTAR), they remain NULL and (non trapping) syscalls are leading to multiple faults and finally crashs. Depending on the architecture (AMD or Intel) pretended by guests, various checks according to vendor's documentation are implemented to overcome the current issue and behave like the CPUs physical counterparts. [mtosatti: cleanup/beautify code] Signed-off-by: Stephan Baerwolf <stephan.baerwolf@tu-ilmenau.de> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID:
0
21,822
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: char *FLTGetBinaryComparisonSQLExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp) { const size_t bufferSize = 1024; char szBuffer[1024]; int bString=0; char szTmp[256]; char* pszEscapedStr = NULL; szBuffer[0] = '\0'; if (!psFilterNode || ! FLTIsBinaryComparisonFilterType(psFilterNode->pszValue)) return NULL; /* -------------------------------------------------------------------- */ /* check if the value is a numeric value or alphanumeric. If it */ /* is alphanumeric, add quotes around attribute and values. */ /* -------------------------------------------------------------------- */ bString = 0; if (psFilterNode->psRightNode->pszValue) { const char* pszOFGType; snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue); pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp); if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0) bString = 1; else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE) bString = 1; } /* specical case to be able to have empty strings in the expression. */ if (psFilterNode->psRightNode->pszValue == NULL) bString = 1; /*opening bracket*/ strlcat(szBuffer, " (", bufferSize); pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue); /* attribute */ /*case insensitive set ? */ if (bString && strcasecmp(psFilterNode->pszValue, "PropertyIsEqualTo") == 0 && psFilterNode->psRightNode->pOther && (*(int *)psFilterNode->psRightNode->pOther) == 1) { snprintf(szTmp, sizeof(szTmp), "lower(%s) ", pszEscapedStr); strlcat(szBuffer, szTmp, bufferSize); } else strlcat(szBuffer, pszEscapedStr, bufferSize); msFree(pszEscapedStr); pszEscapedStr = NULL; /* logical operator */ if (strcasecmp(psFilterNode->pszValue, "PropertyIsEqualTo") == 0) strlcat(szBuffer, "=", bufferSize); else if (strcasecmp(psFilterNode->pszValue, "PropertyIsNotEqualTo") == 0) strlcat(szBuffer, "<>", bufferSize); else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLessThan") == 0) strlcat(szBuffer, "<", bufferSize); else if (strcasecmp(psFilterNode->pszValue, "PropertyIsGreaterThan") == 0) strlcat(szBuffer, ">", bufferSize); else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLessThanOrEqualTo") == 0) strlcat(szBuffer, "<=", bufferSize); else if (strcasecmp(psFilterNode->pszValue, "PropertyIsGreaterThanOrEqualTo") == 0) strlcat(szBuffer, ">=", bufferSize); strlcat(szBuffer, " ", bufferSize); /* value */ if (bString && psFilterNode->psRightNode->pszValue && strcasecmp(psFilterNode->pszValue, "PropertyIsEqualTo") == 0 && psFilterNode->psRightNode->pOther && (*(int *)psFilterNode->psRightNode->pOther) == 1) { char* pszEscapedStr; pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue); snprintf(szTmp, sizeof(szTmp), "lower('%s') ", pszEscapedStr); msFree(pszEscapedStr); strlcat(szBuffer, szTmp, bufferSize); } else { if (bString) strlcat(szBuffer, "'", bufferSize); if (psFilterNode->psRightNode->pszValue) { if (bString) { char* pszEscapedStr; pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue); strlcat(szBuffer, pszEscapedStr, bufferSize); msFree(pszEscapedStr); pszEscapedStr=NULL; } else strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize); } if (bString) strlcat(szBuffer, "'", bufferSize); } /*closing bracket*/ strlcat(szBuffer, ") ", bufferSize); return msStrdup(szBuffer); } Commit Message: security fix (patch by EvenR) CWE ID: CWE-119
0
68,975
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: vrend_surface_reference(struct vrend_surface **ptr, struct vrend_surface *surf) { struct vrend_surface *old_surf = *ptr; if (pipe_reference(&(*ptr)->reference, &surf->reference)) vrend_destroy_surface(old_surf); *ptr = surf; } Commit Message: CWE ID: CWE-119
0
9,154
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: retrieve_url (struct url * orig_parsed, const char *origurl, char **file, char **newloc, const char *refurl, int *dt, bool recursive, struct iri *iri, bool register_status) { uerr_t result; char *url; bool location_changed; bool iri_fallbacked = 0; int dummy; char *mynewloc, *proxy; struct url *u = orig_parsed, *proxy_url; int up_error_code; /* url parse error code */ char *local_file = NULL; int redirection_count = 0; bool method_suspended = false; char *saved_body_data = NULL; char *saved_method = NULL; char *saved_body_file_name = NULL; /* If dt is NULL, use local storage. */ if (!dt) { dt = &dummy; dummy = 0; } url = xstrdup (origurl); if (newloc) *newloc = NULL; if (file) *file = NULL; if (!refurl) refurl = opt.referer; redirected: /* (also for IRI fallbacking) */ result = NOCONERROR; mynewloc = NULL; xfree(local_file); proxy_url = NULL; proxy = getproxy (u); if (proxy) { struct iri *pi = iri_new (); set_uri_encoding (pi, opt.locale, true); pi->utf8_encode = false; /* Parse the proxy URL. */ proxy_url = url_parse (proxy, &up_error_code, pi, true); if (!proxy_url) { char *error = url_error (proxy, up_error_code); logprintf (LOG_NOTQUIET, _("Error parsing proxy URL %s: %s.\n"), proxy, error); xfree (url); xfree (error); xfree (proxy); iri_free (pi); RESTORE_METHOD; result = PROXERR; goto bail; } if (proxy_url->scheme != SCHEME_HTTP && proxy_url->scheme != u->scheme) { logprintf (LOG_NOTQUIET, _("Error in proxy URL %s: Must be HTTP.\n"), proxy); url_free (proxy_url); xfree (url); xfree (proxy); iri_free (pi); RESTORE_METHOD; result = PROXERR; goto bail; } iri_free(pi); xfree (proxy); } if (u->scheme == SCHEME_HTTP #ifdef HAVE_SSL || u->scheme == SCHEME_HTTPS #endif || (proxy_url && proxy_url->scheme == SCHEME_HTTP)) { #ifdef HAVE_HSTS #ifdef TESTING /* we don't link against main.o when we're testing */ hsts_store_t hsts_store = NULL; #else extern hsts_store_t hsts_store; #endif if (opt.hsts && hsts_store) { if (hsts_match (hsts_store, u)) logprintf (LOG_VERBOSE, "URL transformed to HTTPS due to an HSTS policy\n"); } #endif result = http_loop (u, orig_parsed, &mynewloc, &local_file, refurl, dt, proxy_url, iri); } else if (u->scheme == SCHEME_FTP #ifdef HAVE_SSL || u->scheme == SCHEME_FTPS #endif ) { /* If this is a redirection, temporarily turn off opt.ftp_glob and opt.recursive, both being undesirable when following redirects. */ bool oldrec = recursive, glob = opt.ftp_glob; if (redirection_count) oldrec = glob = false; result = ftp_loop (u, &local_file, dt, proxy_url, recursive, glob); recursive = oldrec; /* There is a possibility of having HTTP being redirected to according to the suffix. The HTML suffixes are `.html', `.htm' and a few others, case-insensitive. */ if (redirection_count && local_file && (u->scheme == SCHEME_FTP #ifdef HAVE_SSL || u->scheme == SCHEME_FTPS #endif )) { if (has_html_suffix_p (local_file)) *dt |= TEXTHTML; } } if (proxy_url) { url_free (proxy_url); proxy_url = NULL; } location_changed = (result == NEWLOCATION || result == NEWLOCATION_KEEP_POST); if (location_changed) { char *construced_newloc; struct url *newloc_parsed; assert (mynewloc != NULL); xfree (local_file); /* The HTTP specs only allow absolute URLs to appear in redirects, but a ton of boneheaded webservers and CGIs out there break the rules and use relative URLs, and popular browsers are lenient about this, so wget should be too. */ construced_newloc = uri_merge (url, mynewloc); xfree (mynewloc); mynewloc = construced_newloc; #ifdef ENABLE_IRI /* Reset UTF-8 encoding state, set the URI encoding and reset the content encoding. */ iri->utf8_encode = opt.enable_iri; if (opt.encoding_remote) set_uri_encoding (iri, opt.encoding_remote, true); set_content_encoding (iri, NULL); xfree (iri->orig_url); #endif /* Now, see if this new location makes sense. */ newloc_parsed = url_parse (mynewloc, &up_error_code, iri, true); if (!newloc_parsed) { char *error = url_error (mynewloc, up_error_code); logprintf (LOG_NOTQUIET, "%s: %s.\n", escnonprint_uri (mynewloc), error); if (orig_parsed != u) { url_free (u); } xfree (url); xfree (mynewloc); xfree (error); RESTORE_METHOD; goto bail; } /* Now mynewloc will become newloc_parsed->url, because if the Location contained relative paths like .././something, we don't want that propagating as url. */ xfree (mynewloc); mynewloc = xstrdup (newloc_parsed->url); /* Check for max. number of redirections. */ if (++redirection_count > opt.max_redirect) { logprintf (LOG_NOTQUIET, _("%d redirections exceeded.\n"), opt.max_redirect); url_free (newloc_parsed); if (orig_parsed != u) { url_free (u); } xfree (url); xfree (mynewloc); RESTORE_METHOD; result = WRONGCODE; goto bail; } xfree (url); url = mynewloc; if (orig_parsed != u) { url_free (u); } u = newloc_parsed; /* If we're being redirected from POST, and we received a redirect code different than 307, we don't want to POST again. Many requests answer POST with a redirection to an index page; that redirection is clearly a GET. We "suspend" POST data for the duration of the redirections, and restore it when we're done. RFC2616 HTTP/1.1 introduces code 307 Temporary Redirect specifically to preserve the method of the request. */ if (result != NEWLOCATION_KEEP_POST && !method_suspended) SUSPEND_METHOD; goto redirected; } else { xfree(mynewloc); } /* Try to not encode in UTF-8 if fetching failed */ if (!(*dt & RETROKF) && iri->utf8_encode) { iri->utf8_encode = false; if (orig_parsed != u) { url_free (u); } u = url_parse (origurl, NULL, iri, true); if (u) { DEBUGP (("[IRI fallbacking to non-utf8 for %s\n", quote (url))); xfree (url); url = xstrdup (u->url); iri_fallbacked = 1; goto redirected; } else DEBUGP (("[Couldn't fallback to non-utf8 for %s\n", quote (url))); } if (local_file && u && (*dt & RETROKF || opt.content_on_error)) { register_download (u->url, local_file); if (!opt.spider && redirection_count && 0 != strcmp (origurl, u->url)) register_redirection (origurl, u->url); if (*dt & TEXTHTML) register_html (local_file); if (*dt & TEXTCSS) register_css (local_file); } if (file) *file = local_file ? local_file : NULL; else xfree (local_file); if (orig_parsed != u) { url_free (u); } if (redirection_count || iri_fallbacked) { if (newloc) *newloc = url; else xfree (url); } else { if (newloc) *newloc = NULL; xfree (url); } RESTORE_METHOD; bail: if (register_status) inform_exit_status (result); return result; } Commit Message: CWE ID: CWE-254
1
165,016
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Histogram::WriteHTMLGraph(std::string* output) const { output->append("<PRE>"); WriteAsciiImpl(true, "<br>", output); output->append("</PRE>"); } Commit Message: Convert DCHECKs to CHECKs for histogram types When a histogram is looked up by name, there is currently a DCHECK that verifies the type of the stored histogram matches the expected type. A mismatch represents a significant problem because the returned HistogramBase is cast to a Histogram in ValidateRangeChecksum, potentially causing a crash. This CL converts the DCHECK to a CHECK to prevent the possibility of type confusion in release builds. BUG=651443 R=isherman@chromium.org Review-Url: https://codereview.chromium.org/2381893003 Cr-Commit-Position: refs/heads/master@{#421929} CWE ID: CWE-476
0
140,080
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int hot_remove_disk(struct mddev *mddev, dev_t dev) { char b[BDEVNAME_SIZE]; struct md_rdev *rdev; rdev = find_rdev(mddev, dev); if (!rdev) return -ENXIO; if (mddev_is_clustered(mddev)) md_cluster_ops->metadata_update_start(mddev); clear_bit(Blocked, &rdev->flags); remove_and_add_spares(mddev, rdev); if (rdev->raid_disk >= 0) goto busy; if (mddev_is_clustered(mddev)) md_cluster_ops->remove_disk(mddev, rdev); md_kick_rdev_from_array(rdev); md_update_sb(mddev, 1); md_new_event(mddev); if (mddev_is_clustered(mddev)) md_cluster_ops->metadata_update_finish(mddev); return 0; busy: if (mddev_is_clustered(mddev)) md_cluster_ops->metadata_update_cancel(mddev); printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n", bdevname(rdev->bdev,b), mdname(mddev)); return -EBUSY; } Commit Message: md: use kzalloc() when bitmap is disabled In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a mdu_bitmap_file_t called "file". 5769 file = kmalloc(sizeof(*file), GFP_NOIO); 5770 if (!file) 5771 return -ENOMEM; This structure is copied to user space at the end of the function. 5786 if (err == 0 && 5787 copy_to_user(arg, file, sizeof(*file))) 5788 err = -EFAULT But if bitmap is disabled only the first byte of "file" is initialized with zero, so it's possible to read some bytes (up to 4095) of kernel space memory from user space. This is an information leak. 5775 /* bitmap disabled, zero the first byte and copy out */ 5776 if (!mddev->bitmap_info.file) 5777 file->pathname[0] = '\0'; Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr> Signed-off-by: NeilBrown <neilb@suse.com> CWE ID: CWE-200
0
42,397
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void LargeObjectPage::takeSnapshot( base::trace_event::MemoryAllocatorDump* pageDump, ThreadState::GCSnapshotInfo& info, HeapSnapshotInfo&) { size_t liveSize = 0; size_t deadSize = 0; size_t liveCount = 0; size_t deadCount = 0; HeapObjectHeader* header = heapObjectHeader(); size_t gcInfoIndex = header->gcInfoIndex(); size_t payloadSize = header->payloadSize(); if (header->isMarked()) { liveCount = 1; liveSize += payloadSize; info.liveCount[gcInfoIndex]++; info.liveSize[gcInfoIndex] += payloadSize; } else { deadCount = 1; deadSize += payloadSize; info.deadCount[gcInfoIndex]++; info.deadSize[gcInfoIndex] += payloadSize; } pageDump->AddScalar("live_count", "objects", liveCount); pageDump->AddScalar("dead_count", "objects", deadCount); pageDump->AddScalar("live_size", "bytes", liveSize); pageDump->AddScalar("dead_size", "bytes", deadSize); } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
0
147,595
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static bool ExecuteApplyParagraphStyle(LocalFrame& frame, EditorCommandSource source, InputEvent::InputType input_type, CSSPropertyID property_id, const String& property_value) { MutableStylePropertySet* style = MutableStylePropertySet::Create(kHTMLQuirksMode); style->SetProperty(property_id, property_value); switch (source) { case kCommandFromMenuOrKeyBinding: frame.GetEditor().ApplyParagraphStyleToSelection(style, input_type); return true; case kCommandFromDOM: frame.GetEditor().ApplyParagraphStyle(style, input_type); return true; } NOTREACHED(); return false; } Commit Message: Move Editor::Transpose() out of Editor class This patch moves |Editor::Transpose()| out of |Editor| class as preparation of expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor| class simpler for improving code health. Following patch will expand |Transpose()| into |ExecutTranspose()|. Bug: 672405 Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6 Reviewed-on: https://chromium-review.googlesource.com/583880 Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Cr-Commit-Position: refs/heads/master@{#489518} CWE ID:
0
128,498
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: CSSStyleSheet::InspectorMutationScope::InspectorMutationScope( CSSStyleSheet* sheet) : style_sheet_(sheet) { style_sheet_->EnableRuleAccessForInspector(); } Commit Message: Disallow access to opaque CSS responses. Bug: 848786 Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec Reviewed-on: https://chromium-review.googlesource.com/1088335 Reviewed-by: Kouhei Ueno <kouhei@chromium.org> Commit-Queue: Matt Falkenhagen <falken@chromium.org> Cr-Commit-Position: refs/heads/master@{#565537} CWE ID: CWE-200
0
153,941
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void UiSceneCreator::CreateAudioPermissionPrompt() { std::unique_ptr<UiElement> element; auto backplane = base::MakeUnique<InvisibleHitTarget>(); backplane->SetDrawPhase(kPhaseForeground); backplane->SetName(kAudioPermissionPromptBackplane); backplane->SetSize(kPromptBackplaneSize, kPromptBackplaneSize); backplane->SetTranslate(0.0, kContentVerticalOffset, -kOverlayPlaneDistance); EventHandlers event_handlers; event_handlers.button_up = base::Bind( [](UiBrowserInterface* browser, Model* m) { browser->OnExitVrPromptResult( ExitVrPromptChoice::CHOICE_NONE, GetReasonForPrompt(m->active_modal_prompt_type)); }, base::Unretained(browser_), base::Unretained(model_)); backplane->set_event_handlers(event_handlers); backplane->SetVisible(false); backplane->SetTransitionedProperties({OPACITY}); backplane->AddBinding(VR_BIND_FUNC( bool, Model, model_, active_modal_prompt_type == kModalPromptTypeExitVRForVoiceSearchRecordAudioOsPermission, UiElement, backplane.get(), SetVisible)); std::unique_ptr<Shadow> shadow = base::MakeUnique<Shadow>(); shadow->SetName(kAudioPermissionPromptShadow); shadow->SetDrawPhase(kPhaseForeground); std::unique_ptr<AudioPermissionPrompt> prompt = base::MakeUnique<AudioPermissionPrompt>( 1024, base::Bind( &UiBrowserInterface::OnExitVrPromptResult, base::Unretained(browser_), ExitVrPromptChoice::CHOICE_EXIT, UiUnsupportedMode::kVoiceSearchNeedsRecordAudioOsPermission), base::Bind( &UiBrowserInterface::OnExitVrPromptResult, base::Unretained(browser_), ExitVrPromptChoice::CHOICE_STAY, UiUnsupportedMode::kVoiceSearchNeedsRecordAudioOsPermission)); prompt->SetName(kAudioPermissionPrompt); prompt->SetDrawPhase(kPhaseForeground); prompt->SetSize(kAudioPermissionPromptWidth, kAudioPermissionPromptHeight); prompt->SetTranslate(0.0, 0.0f, kAudionPermisionPromptDepth); BindButtonColors(model_, prompt.get(), &ColorScheme::audio_permission_prompt_primary_button_colors, &AudioPermissionPrompt::SetPrimaryButtonColors); BindButtonColors( model_, prompt.get(), &ColorScheme::audio_permission_prompt_secondary_button_colors, &AudioPermissionPrompt::SetSecondaryButtonColors); BindColor(model_, prompt.get(), &ColorScheme::audio_permission_prompt_icon_foreground, &AudioPermissionPrompt::SetIconColor); BindColor(model_, prompt.get(), &ColorScheme::audio_permission_prompt_background, &TexturedElement::SetBackgroundColor); BindColor(model_, prompt.get(), &ColorScheme::element_foreground, &TexturedElement::SetForegroundColor); shadow->AddChild(std::move(prompt)); backplane->AddChild(std::move(shadow)); scene_->AddUiElement(k2dBrowsingRoot, std::move(backplane)); } Commit Message: Fix wrapping behavior of description text in omnibox suggestion This regression is introduced by https://chromium-review.googlesource.com/c/chromium/src/+/827033 The description text should not wrap. Bug: NONE Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;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 Change-Id: Iaac5e6176e1730853406602835d61fe1e80ec0d0 Reviewed-on: https://chromium-review.googlesource.com/839960 Reviewed-by: Christopher Grant <cjgrant@chromium.org> Commit-Queue: Biao She <bshe@chromium.org> Cr-Commit-Position: refs/heads/master@{#525806} CWE ID: CWE-200
0
155,503
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: sync_force_parallel_show(struct mddev *mddev, char *page) { return sprintf(page, "%d\n", mddev->parallel_resync); } Commit Message: md: use kzalloc() when bitmap is disabled In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a mdu_bitmap_file_t called "file". 5769 file = kmalloc(sizeof(*file), GFP_NOIO); 5770 if (!file) 5771 return -ENOMEM; This structure is copied to user space at the end of the function. 5786 if (err == 0 && 5787 copy_to_user(arg, file, sizeof(*file))) 5788 err = -EFAULT But if bitmap is disabled only the first byte of "file" is initialized with zero, so it's possible to read some bytes (up to 4095) of kernel space memory from user space. This is an information leak. 5775 /* bitmap disabled, zero the first byte and copy out */ 5776 if (!mddev->bitmap_info.file) 5777 file->pathname[0] = '\0'; Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr> Signed-off-by: NeilBrown <neilb@suse.com> CWE ID: CWE-200
0
42,561
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder) { #if LOG_REFCOUNTS printf("IPCThreadState::expungeHandle(%ld)\n", handle); #endif self()->mProcess->expungeHandle(handle, binder); } Commit Message: Fix issue #27252896: Security Vulnerability -- weak binder Sending transaction to freed BBinder through weak handle can cause use of a (mostly) freed object. We need to try to safely promote to a strong reference first. Change-Id: Ic9c6940fa824980472e94ed2dfeca52a6b0fd342 (cherry picked from commit c11146106f94e07016e8e26e4f8628f9a0c73199) CWE ID: CWE-264
0
161,140
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: _dbus_full_duplex_pipe (int *fd1, int *fd2, dbus_bool_t blocking, DBusError *error) { SOCKET temp, socket1 = -1, socket2 = -1; struct sockaddr_in saddr; int len; u_long arg; _dbus_win_startup_winsock (); temp = socket (AF_INET, SOCK_STREAM, 0); if (temp == INVALID_SOCKET) { DBUS_SOCKET_SET_ERRNO (); goto out0; } _DBUS_ZERO (saddr); saddr.sin_family = AF_INET; saddr.sin_port = 0; saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR) { DBUS_SOCKET_SET_ERRNO (); goto out0; } if (listen (temp, 1) == SOCKET_ERROR) { DBUS_SOCKET_SET_ERRNO (); goto out0; } len = sizeof (saddr); if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR) { DBUS_SOCKET_SET_ERRNO (); goto out0; } socket1 = socket (AF_INET, SOCK_STREAM, 0); if (socket1 == INVALID_SOCKET) { DBUS_SOCKET_SET_ERRNO (); goto out0; } if (connect (socket1, (struct sockaddr *)&saddr, len) == SOCKET_ERROR) { DBUS_SOCKET_SET_ERRNO (); goto out1; } socket2 = accept (temp, (struct sockaddr *) &saddr, &len); if (socket2 == INVALID_SOCKET) { DBUS_SOCKET_SET_ERRNO (); goto out1; } if (!blocking) { arg = 1; if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR) { DBUS_SOCKET_SET_ERRNO (); goto out2; } arg = 1; if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR) { DBUS_SOCKET_SET_ERRNO (); goto out2; } } *fd1 = socket1; *fd2 = socket2; _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n", *fd1, socket1, *fd2, socket2); closesocket (temp); return TRUE; out2: closesocket (socket2); out1: closesocket (socket1); out0: closesocket (temp); dbus_set_error (error, _dbus_error_from_errno (errno), "Could not setup socket pair: %s", _dbus_strerror_from_errno ()); return FALSE; } Commit Message: CWE ID: CWE-20
0
3,786
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_sock *sp = sctp_sk(sk); /* Applicable to UDP-style socket only */ if (sctp_style(sk, TCP)) return -EOPNOTSUPP; if (optlen != sizeof(int)) return -EINVAL; if (copy_from_user(&sp->autoclose, optval, optlen)) return -EFAULT; return 0; } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <linux@roeck-us.net> Acked-by: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
33,042
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static const char *parse_array(cJSON *item,const char *value,const char **ep) { cJSON *child; if (*value!='[') {*ep=value;return 0;} /* not an array! */ item->type=cJSON_Array; value=skip(value+1); if (*value==']') return value+1; /* empty array. */ item->child=child=cJSON_New_Item(); if (!item->child) return 0; /* memory fail */ value=skip(parse_value(child,skip(value),ep)); /* skip any spacing, get the value. */ if (!value) return 0; while (*value==',') { cJSON *new_item; if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_value(child,skip(value+1),ep)); if (!value) return 0; /* memory fail */ } if (*value==']') return value+1; /* end of array */ *ep=value;return 0; /* malformed. */ } Commit Message: fix buffer overflow (#30) CWE ID: CWE-125
0
93,731
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void btif_hl_proc_reg_request(UINT8 app_idx, UINT8 app_id, tBTA_HL_REG_PARAM *p_reg_param, tBTA_HL_CBACK *p_cback){ UNUSED(p_cback); BTIF_TRACE_DEBUG("%s app_idx=%d app_id=%d", __FUNCTION__, app_idx, app_id); if(reg_counter >1) { BTIF_TRACE_DEBUG("btif_hl_proc_reg_request: calling uPDATE"); BTA_HlUpdate(app_id, p_reg_param,TRUE, btif_hl_cback); } else BTA_HlRegister(app_id, p_reg_param, btif_hl_cback); } 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
0
158,737
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int em_movdqu(struct x86_emulate_ctxt *ctxt) { memcpy(&ctxt->dst.vec_val, &ctxt->src.vec_val, ctxt->op_bytes); return X86EMUL_CONTINUE; } Commit Message: KVM: x86: fix missing checks in syscall emulation On hosts without this patch, 32bit guests will crash (and 64bit guests may behave in a wrong way) for example by simply executing following nasm-demo-application: [bits 32] global _start SECTION .text _start: syscall (I tested it with winxp and linux - both always crashed) Disassembly of section .text: 00000000 <_start>: 0: 0f 05 syscall The reason seems a missing "invalid opcode"-trap (int6) for the syscall opcode "0f05", which is not available on Intel CPUs within non-longmodes, as also on some AMD CPUs within legacy-mode. (depending on CPU vendor, MSR_EFER and cpuid) Because previous mentioned OSs may not engage corresponding syscall target-registers (STAR, LSTAR, CSTAR), they remain NULL and (non trapping) syscalls are leading to multiple faults and finally crashs. Depending on the architecture (AMD or Intel) pretended by guests, various checks according to vendor's documentation are implemented to overcome the current issue and behave like the CPUs physical counterparts. [mtosatti: cleanup/beautify code] Signed-off-by: Stephan Baerwolf <stephan.baerwolf@tu-ilmenau.de> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID:
0
21,766
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static bool is_cc_error(PRInt32 err) { switch(err) { case SSL_ERROR_BAD_CERT_ALERT: case SSL_ERROR_EXPIRED_CERT_ALERT: case SSL_ERROR_REVOKED_CERT_ALERT: return true; default: return false; } } Commit Message: nss: refuse previously loaded certificate from file ... when we are not asked to use a certificate from file CWE ID: CWE-287
0
50,090
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void free_Style_className(void) { FREE(Style_className); } Commit Message: snapshot of project "lynx", label v2-8-9dev_15b CWE ID: CWE-416
0
59,024
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PHP_FUNCTION(xml_set_default_handler) { xml_parser *parser; zval *pind, **hdl; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rZ", &pind, &hdl) == FAILURE) { return; } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); xml_set_handler(&parser->defaultHandler, hdl); XML_SetDefaultHandler(parser->parser, _xml_defaultHandler); RETVAL_TRUE; } Commit Message: CWE ID: CWE-119
0
10,973
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: MATCHER(CompareMetricsIgnoringMillisecondsSinceFormParsed, "") { const auto& lhs = ::testing::get<0>(arg); const std::pair<const char*, int64_t>& rhs = ::testing::get<1>(arg); return lhs.first == base::HashMetricName(rhs.first) && (lhs.second == rhs.second || (lhs.second > 0 && rhs.first == UkmSuggestionFilledType::kMillisecondsSinceFormParsedName)); } 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 <rogerm@chromium.org> Commit-Queue: Sebastien Seguin-Gagnon <sebsg@chromium.org> Cr-Commit-Position: refs/heads/master@{#573315} CWE ID:
0
155,054
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int mem_cgroup_resize_limit(struct mem_cgroup *memcg, unsigned long long val) { int retry_count; u64 memswlimit, memlimit; int ret = 0; int children = mem_cgroup_count_children(memcg); u64 curusage, oldusage; int enlarge; /* * For keeping hierarchical_reclaim simple, how long we should retry * is depends on callers. We set our retry-count to be function * of # of children which we should visit in this loop. */ retry_count = MEM_CGROUP_RECLAIM_RETRIES * children; oldusage = res_counter_read_u64(&memcg->res, RES_USAGE); enlarge = 0; while (retry_count) { if (signal_pending(current)) { ret = -EINTR; break; } /* * Rather than hide all in some function, I do this in * open coded manner. You see what this really does. * We have to guarantee memcg->res.limit < memcg->memsw.limit. */ mutex_lock(&set_limit_mutex); memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT); if (memswlimit < val) { ret = -EINVAL; mutex_unlock(&set_limit_mutex); break; } memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT); if (memlimit < val) enlarge = 1; ret = res_counter_set_limit(&memcg->res, val); if (!ret) { if (memswlimit == val) memcg->memsw_is_minimum = true; else memcg->memsw_is_minimum = false; } mutex_unlock(&set_limit_mutex); if (!ret) break; mem_cgroup_reclaim(memcg, GFP_KERNEL, MEM_CGROUP_RECLAIM_SHRINK); curusage = res_counter_read_u64(&memcg->res, RES_USAGE); /* Usage is reduced ? */ if (curusage >= oldusage) retry_count--; else oldusage = curusage; } if (!ret && enlarge) memcg_oom_recover(memcg); return ret; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [akpm@linux-foundation.org: checkpatch fixes] Reported-by: Ulrich Obergfell <uobergfe@redhat.com> Signed-off-by: Andrea Arcangeli <aarcange@redhat.com> Acked-by: Johannes Weiner <hannes@cmpxchg.org> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Dave Jones <davej@redhat.com> Acked-by: Larry Woodman <lwoodman@redhat.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: Mark Salter <msalter@redhat.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-264
0
21,122
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct ctl_table *sd_alloc_ctl_entry(int n) { struct ctl_table *entry = kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL); return entry; } Commit Message: Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <efault@gmx.de> Reported-by: Bjoern B. Brandenburg <bbb.lst@gmail.com> Tested-by: Yong Zhang <yong.zhang0@gmail.com> Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: stable@kernel.org LKML-Reference: <1291802742.1417.9.camel@marge.simson.net> Signed-off-by: Ingo Molnar <mingo@elte.hu> CWE ID:
0
22,581
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ftrace_profile_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; /* big enough to hold a number */ int r; r = sprintf(buf, "%u\n", ftrace_profile_enabled); return simple_read_from_buffer(ubuf, cnt, ppos, buf, r); } Commit Message: tracing: Fix possible NULL pointer dereferences Currently set_ftrace_pid and set_graph_function files use seq_lseek for their fops. However seq_open() is called only for FMODE_READ in the fops->open() so that if an user tries to seek one of those file when she open it for writing, it sees NULL seq_file and then panic. It can be easily reproduced with following command: $ cd /sys/kernel/debug/tracing $ echo 1234 | sudo tee -a set_ftrace_pid In this example, GNU coreutils' tee opens the file with fopen(, "a") and then the fopen() internally calls lseek(). Link: http://lkml.kernel.org/r/1365663302-2170-1-git-send-email-namhyung@kernel.org Cc: Frederic Weisbecker <fweisbec@gmail.com> Cc: Ingo Molnar <mingo@kernel.org> Cc: Namhyung Kim <namhyung.kim@lge.com> Cc: stable@vger.kernel.org Signed-off-by: Namhyung Kim <namhyung@kernel.org> Signed-off-by: Steven Rostedt <rostedt@goodmis.org> CWE ID:
0
30,207
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: test_are_urls_equal(void) { unsigned i; static const struct { const char *url1; const char *url2; bool expected_result; } test_array[] = { { "http://www.adomain.com/apath/", "http://www.adomain.com/apath/", true }, { "http://www.adomain.com/apath/", "http://www.adomain.com/anotherpath/", false }, { "http://www.adomain.com/apath/", "http://www.anotherdomain.com/path/", false }, { "http://www.adomain.com/~path/", "http://www.adomain.com/%7epath/", true }, { "http://www.adomain.com/longer-path/", "http://www.adomain.com/path/", false }, { "http://www.adomain.com/path%2f", "http://www.adomain.com/path/", false }, }; for (i = 0; i < countof(test_array); ++i) { mu_assert ("test_are_urls_equal: wrong result", are_urls_equal (test_array[i].url1, test_array[i].url2) == test_array[i].expected_result); } return NULL; } Commit Message: CWE ID: CWE-93
0
8,702
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void n_tty_packet_mode_flush(struct tty_struct *tty) { unsigned long flags; if (tty->link->packet) { spin_lock_irqsave(&tty->ctrl_lock, flags); tty->ctrl_status |= TIOCPKT_FLUSHREAD; spin_unlock_irqrestore(&tty->ctrl_lock, flags); wake_up_interruptible(&tty->link->read_wait); } } Commit Message: n_tty: fix EXTPROC vs ICANON interaction with TIOCINQ (aka FIONREAD) We added support for EXTPROC back in 2010 in commit 26df6d13406d ("tty: Add EXTPROC support for LINEMODE") and the intent was to allow it to override some (all?) ICANON behavior. Quoting from that original commit message: There is a new bit in the termios local flag word, EXTPROC. When this bit is set, several aspects of the terminal driver are disabled. Input line editing, character echo, and mapping of signals are all disabled. This allows the telnetd to turn off these functions when in linemode, but still keep track of what state the user wants the terminal to be in. but the problem turns out that "several aspects of the terminal driver are disabled" is a bit ambiguous, and you can really confuse the n_tty layer by setting EXTPROC and then causing some of the ICANON invariants to no longer be maintained. This fixes at least one such case (TIOCINQ) becoming unhappy because of the confusion over whether ICANON really means ICANON when EXTPROC is set. This basically makes TIOCINQ match the case of read: if EXTPROC is set, we ignore ICANON. Also, make sure to reset the ICANON state ie EXTPROC changes, not just if ICANON changes. Fixes: 26df6d13406d ("tty: Add EXTPROC support for LINEMODE") Reported-by: Tetsuo Handa <penguin-kernel@i-love.sakura.ne.jp> Reported-by: syzkaller <syzkaller@googlegroups.com> Cc: Jiri Slaby <jslaby@suse.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-704
0
76,493
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: safeputs(netdissect_options *ndo, const u_char *s, const u_int maxlen) { u_int idx = 0; while (idx < maxlen && *s) { safeputchar(ndo, *s); idx++; s++; } } Commit Message: CVE-2017-13011/Properly check for buffer overflow in bittok2str_internal(). Also, make the buffer bigger. This fixes a buffer overflow discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-119
0
62,390
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int i2d_ECPrivateKey_fp(FILE *fp, EC_KEY *eckey) { return ASN1_i2d_fp_of(EC_KEY,i2d_ECPrivateKey,fp,eckey); } Commit Message: Fix various certificate fingerprint issues. By using non-DER or invalid encodings outside the signed portion of a certificate the fingerprint can be changed without breaking the signature. Although no details of the signed portion of the certificate can be changed this can cause problems with some applications: e.g. those using the certificate fingerprint for blacklists. 1. Reject signatures with non zero unused bits. If the BIT STRING containing the signature has non zero unused bits reject the signature. All current signature algorithms require zero unused bits. 2. Check certificate algorithm consistency. Check the AlgorithmIdentifier inside TBS matches the one in the certificate signature. NB: this will result in signature failure errors for some broken certificates. 3. Check DSA/ECDSA signatures use DER. Reencode DSA/ECDSA signatures and compare with the original received signature. Return an error if there is a mismatch. This will reject various cases including garbage after signature (thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS program for discovering this case) and use of BER or invalid ASN.1 INTEGERs (negative or with leading zeroes). CVE-2014-8275 Reviewed-by: Emilia Käsper <emilia@openssl.org> CWE ID: CWE-310
0
94,669
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: estack_underflow(i_ctx_t *i_ctx_p) { return gs_error_ExecStackUnderflow; } Commit Message: CWE ID: CWE-200
0
2,365
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PanoramiXRenderComposite(ClientPtr client) { PanoramiXRes *src, *msk, *dst; int result = Success, j; xRenderCompositeReq orig; REQUEST(xRenderCompositeReq); REQUEST_SIZE_MATCH(xRenderCompositeReq); VERIFY_XIN_PICTURE(src, stuff->src, client, DixReadAccess); VERIFY_XIN_ALPHA(msk, stuff->mask, client, DixReadAccess); VERIFY_XIN_PICTURE(dst, stuff->dst, client, DixWriteAccess); orig = *stuff; FOR_NSCREENS_FORWARD(j) { stuff->src = src->info[j].id; if (src->u.pict.root) { stuff->xSrc = orig.xSrc - screenInfo.screens[j]->x; stuff->ySrc = orig.ySrc - screenInfo.screens[j]->y; } stuff->dst = dst->info[j].id; if (dst->u.pict.root) { stuff->xDst = orig.xDst - screenInfo.screens[j]->x; stuff->yDst = orig.yDst - screenInfo.screens[j]->y; } if (msk) { stuff->mask = msk->info[j].id; if (msk->u.pict.root) { stuff->xMask = orig.xMask - screenInfo.screens[j]->x; stuff->yMask = orig.yMask - screenInfo.screens[j]->y; } } result = (*PanoramiXSaveRenderVector[X_RenderComposite]) (client); if (result != Success) break; } return result; } Commit Message: CWE ID: CWE-20
0
17,552
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ConfirmEmailDialogDelegate::OnAccepted() { base::ResetAndReturn(&callback_).Run( IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_OK_BUTTON); } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
0
112,588
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderFrameImpl::OnRedo() { frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement()); } Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame. BUG=369553 R=creis@chromium.org Review URL: https://codereview.chromium.org/263833020 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
110,187
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void HTMLMediaElement::SelectInitialTracksIfNecessary() { if (!MediaTracksEnabledInternally()) return; if (audioTracks().length() > 0 && !audioTracks().HasEnabledTrack()) audioTracks().AnonymousIndexedGetter(0)->setEnabled(true); if (videoTracks().length() > 0 && videoTracks().selectedIndex() == -1) videoTracks().AnonymousIndexedGetter(0)->setSelected(true); } Commit Message: defeat cors attacks on audio/video tags Neutralize error messages and fire no progress events until media metadata has been loaded for media loaded from cross-origin locations. Bug: 828265, 826187 Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6 Reviewed-on: https://chromium-review.googlesource.com/1015794 Reviewed-by: Mounir Lamouri <mlamouri@chromium.org> Reviewed-by: Dale Curtis <dalecurtis@chromium.org> Commit-Queue: Fredrik Hubinette <hubbe@chromium.org> Cr-Commit-Position: refs/heads/master@{#557312} CWE ID: CWE-200
0
154,147
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ACodec::LoadedState::LoadedState(ACodec *codec) : BaseState(codec) { } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 CWE ID: CWE-119
0
164,018
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: tt_cmap12_char_map_binary( TT_CMap cmap, FT_UInt32* pchar_code, FT_Bool next ) { FT_UInt gindex = 0; FT_Byte* p = cmap->data + 12; FT_UInt32 num_groups = TT_PEEK_ULONG( p ); FT_UInt32 char_code = *pchar_code; FT_UInt32 start, end, start_id; FT_UInt32 max, min, mid; if ( !num_groups ) return 0; /* make compiler happy */ mid = num_groups; end = 0xFFFFFFFFUL; if ( next ) char_code++; min = 0; max = num_groups; /* binary search */ while ( min < max ) { mid = ( min + max ) >> 1; p = cmap->data + 16 + 12 * mid; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); if ( char_code < start ) max = mid; else if ( char_code > end ) min = mid + 1; else { start_id = TT_PEEK_ULONG( p ); gindex = (FT_UInt)( start_id + char_code - start ); break; } } if ( next ) { TT_CMap12 cmap12 = (TT_CMap12)cmap; /* if `char_code' is not in any group, then `mid' is */ /* the group nearest to `char_code' */ /* */ if ( char_code > end ) { mid++; if ( mid == num_groups ) return 0; } cmap12->valid = 1; cmap12->cur_charcode = char_code; cmap12->cur_group = mid; if ( !gindex ) { tt_cmap12_next( cmap12 ); if ( cmap12->valid ) gindex = cmap12->cur_gindex; } else cmap12->cur_gindex = gindex; if ( gindex ) *pchar_code = cmap12->cur_charcode; } return gindex; } Commit Message: CWE ID: CWE-119
0
7,084
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void cachedAttribute2AttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); v8SetReturnValue(info, imp->cachedAttribute2().v8Value()); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
121,581
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int tg3_fiber_aneg_smachine(struct tg3 *tp, struct tg3_fiber_aneginfo *ap) { u16 flowctrl; unsigned long delta; u32 rx_cfg_reg; int ret; if (ap->state == ANEG_STATE_UNKNOWN) { ap->rxconfig = 0; ap->link_time = 0; ap->cur_time = 0; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->idle_match = 0; ap->ack_match = 0; } ap->cur_time++; if (tr32(MAC_STATUS) & MAC_STATUS_RCVD_CFG) { rx_cfg_reg = tr32(MAC_RX_AUTO_NEG); if (rx_cfg_reg != ap->ability_match_cfg) { ap->ability_match_cfg = rx_cfg_reg; ap->ability_match = 0; ap->ability_match_count = 0; } else { if (++ap->ability_match_count > 1) { ap->ability_match = 1; ap->ability_match_cfg = rx_cfg_reg; } } if (rx_cfg_reg & ANEG_CFG_ACK) ap->ack_match = 1; else ap->ack_match = 0; ap->idle_match = 0; } else { ap->idle_match = 1; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->ack_match = 0; rx_cfg_reg = 0; } ap->rxconfig = rx_cfg_reg; ret = ANEG_OK; switch (ap->state) { case ANEG_STATE_UNKNOWN: if (ap->flags & (MR_AN_ENABLE | MR_RESTART_AN)) ap->state = ANEG_STATE_AN_ENABLE; /* fallthru */ case ANEG_STATE_AN_ENABLE: ap->flags &= ~(MR_AN_COMPLETE | MR_PAGE_RX); if (ap->flags & MR_AN_ENABLE) { ap->link_time = 0; ap->cur_time = 0; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->idle_match = 0; ap->ack_match = 0; ap->state = ANEG_STATE_RESTART_INIT; } else { ap->state = ANEG_STATE_DISABLE_LINK_OK; } break; case ANEG_STATE_RESTART_INIT: ap->link_time = ap->cur_time; ap->flags &= ~(MR_NP_LOADED); ap->txconfig = 0; tw32(MAC_TX_AUTO_NEG, 0); tp->mac_mode |= MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ret = ANEG_TIMER_ENAB; ap->state = ANEG_STATE_RESTART; /* fallthru */ case ANEG_STATE_RESTART: delta = ap->cur_time - ap->link_time; if (delta > ANEG_STATE_SETTLE_TIME) ap->state = ANEG_STATE_ABILITY_DETECT_INIT; else ret = ANEG_TIMER_ENAB; break; case ANEG_STATE_DISABLE_LINK_OK: ret = ANEG_DONE; break; case ANEG_STATE_ABILITY_DETECT_INIT: ap->flags &= ~(MR_TOGGLE_TX); ap->txconfig = ANEG_CFG_FD; flowctrl = tg3_advert_flowctrl_1000X(tp->link_config.flowctrl); if (flowctrl & ADVERTISE_1000XPAUSE) ap->txconfig |= ANEG_CFG_PS1; if (flowctrl & ADVERTISE_1000XPSE_ASYM) ap->txconfig |= ANEG_CFG_PS2; tw32(MAC_TX_AUTO_NEG, ap->txconfig); tp->mac_mode |= MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = ANEG_STATE_ABILITY_DETECT; break; case ANEG_STATE_ABILITY_DETECT: if (ap->ability_match != 0 && ap->rxconfig != 0) ap->state = ANEG_STATE_ACK_DETECT_INIT; break; case ANEG_STATE_ACK_DETECT_INIT: ap->txconfig |= ANEG_CFG_ACK; tw32(MAC_TX_AUTO_NEG, ap->txconfig); tp->mac_mode |= MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = ANEG_STATE_ACK_DETECT; /* fallthru */ case ANEG_STATE_ACK_DETECT: if (ap->ack_match != 0) { if ((ap->rxconfig & ~ANEG_CFG_ACK) == (ap->ability_match_cfg & ~ANEG_CFG_ACK)) { ap->state = ANEG_STATE_COMPLETE_ACK_INIT; } else { ap->state = ANEG_STATE_AN_ENABLE; } } else if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = ANEG_STATE_AN_ENABLE; } break; case ANEG_STATE_COMPLETE_ACK_INIT: if (ap->rxconfig & ANEG_CFG_INVAL) { ret = ANEG_FAILED; break; } ap->flags &= ~(MR_LP_ADV_FULL_DUPLEX | MR_LP_ADV_HALF_DUPLEX | MR_LP_ADV_SYM_PAUSE | MR_LP_ADV_ASYM_PAUSE | MR_LP_ADV_REMOTE_FAULT1 | MR_LP_ADV_REMOTE_FAULT2 | MR_LP_ADV_NEXT_PAGE | MR_TOGGLE_RX | MR_NP_RX); if (ap->rxconfig & ANEG_CFG_FD) ap->flags |= MR_LP_ADV_FULL_DUPLEX; if (ap->rxconfig & ANEG_CFG_HD) ap->flags |= MR_LP_ADV_HALF_DUPLEX; if (ap->rxconfig & ANEG_CFG_PS1) ap->flags |= MR_LP_ADV_SYM_PAUSE; if (ap->rxconfig & ANEG_CFG_PS2) ap->flags |= MR_LP_ADV_ASYM_PAUSE; if (ap->rxconfig & ANEG_CFG_RF1) ap->flags |= MR_LP_ADV_REMOTE_FAULT1; if (ap->rxconfig & ANEG_CFG_RF2) ap->flags |= MR_LP_ADV_REMOTE_FAULT2; if (ap->rxconfig & ANEG_CFG_NP) ap->flags |= MR_LP_ADV_NEXT_PAGE; ap->link_time = ap->cur_time; ap->flags ^= (MR_TOGGLE_TX); if (ap->rxconfig & 0x0008) ap->flags |= MR_TOGGLE_RX; if (ap->rxconfig & ANEG_CFG_NP) ap->flags |= MR_NP_RX; ap->flags |= MR_PAGE_RX; ap->state = ANEG_STATE_COMPLETE_ACK; ret = ANEG_TIMER_ENAB; break; case ANEG_STATE_COMPLETE_ACK: if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = ANEG_STATE_AN_ENABLE; break; } delta = ap->cur_time - ap->link_time; if (delta > ANEG_STATE_SETTLE_TIME) { if (!(ap->flags & (MR_LP_ADV_NEXT_PAGE))) { ap->state = ANEG_STATE_IDLE_DETECT_INIT; } else { if ((ap->txconfig & ANEG_CFG_NP) == 0 && !(ap->flags & MR_NP_RX)) { ap->state = ANEG_STATE_IDLE_DETECT_INIT; } else { ret = ANEG_FAILED; } } } break; case ANEG_STATE_IDLE_DETECT_INIT: ap->link_time = ap->cur_time; tp->mac_mode &= ~MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = ANEG_STATE_IDLE_DETECT; ret = ANEG_TIMER_ENAB; break; case ANEG_STATE_IDLE_DETECT: if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = ANEG_STATE_AN_ENABLE; break; } delta = ap->cur_time - ap->link_time; if (delta > ANEG_STATE_SETTLE_TIME) { /* XXX another gem from the Broadcom driver :( */ ap->state = ANEG_STATE_LINK_OK; } break; case ANEG_STATE_LINK_OK: ap->flags |= (MR_AN_COMPLETE | MR_LINK_OK); ret = ANEG_DONE; break; case ANEG_STATE_NEXT_PAGE_WAIT_INIT: /* ??? unimplemented */ break; case ANEG_STATE_NEXT_PAGE_WAIT: /* ??? unimplemented */ break; default: ret = ANEG_FAILED; break; } return ret; } Commit Message: tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <keescook@chromium.org> Reported-by: Oded Horovitz <oded@privatecore.com> Reported-by: Brad Spengler <spender@grsecurity.net> Cc: stable@vger.kernel.org Cc: Matt Carlson <mcarlson@broadcom.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
0
32,531
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderFrameHostImpl::OnFocusedNodeChanged( bool is_editable_element, const gfx::Rect& bounds_in_frame_widget) { if (!GetView()) return; has_focused_editable_element_ = is_editable_element; delegate_->OnFocusedElementChangedInFrame( this, gfx::Rect(GetView()->TransformPointToRootCoordSpace( bounds_in_frame_widget.origin()), bounds_in_frame_widget.size())); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <iclelland@chromium.org> Reviewed-by: Charles Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
0
127,854
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
0
78,226
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst) { xmlParserCtxtPtr ctxt; xmlDocPtr newDoc; xmlNodePtr newRoot; xmlSAXHandlerPtr oldsax = NULL; int ret = 0; xmlChar start[4]; xmlCharEncoding enc; if (ctx == NULL) return(-1); if (((ctx->depth > 40) && ((ctx->options & XML_PARSE_HUGE) == 0)) || (ctx->depth > 1024)) { return(XML_ERR_ENTITY_LOOP); } if (lst != NULL) *lst = NULL; if ((URL == NULL) && (ID == NULL)) return(-1); if (ctx->myDoc == NULL) /* @@ relax but check for dereferences */ return(-1); ctxt = xmlCreateEntityParserCtxtInternal(URL, ID, NULL, ctx); if (ctxt == NULL) { return(-1); } oldsax = ctxt->sax; ctxt->sax = ctx->sax; xmlDetectSAX2(ctxt); newDoc = xmlNewDoc(BAD_CAST "1.0"); if (newDoc == NULL) { xmlFreeParserCtxt(ctxt); return(-1); } newDoc->properties = XML_DOC_INTERNAL; if (ctx->myDoc->dict) { newDoc->dict = ctx->myDoc->dict; xmlDictReference(newDoc->dict); } if (ctx->myDoc != NULL) { newDoc->intSubset = ctx->myDoc->intSubset; newDoc->extSubset = ctx->myDoc->extSubset; } if (ctx->myDoc->URL != NULL) { newDoc->URL = xmlStrdup(ctx->myDoc->URL); } newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST "pseudoroot", NULL); if (newRoot == NULL) { ctxt->sax = oldsax; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(-1); } xmlAddChild((xmlNodePtr) newDoc, newRoot); nodePush(ctxt, newDoc->children); if (ctx->myDoc == NULL) { ctxt->myDoc = newDoc; } else { ctxt->myDoc = ctx->myDoc; newDoc->children->doc = ctx->myDoc; } /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ GROW if ((ctxt->input->end - ctxt->input->cur) >= 4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } /* * Parse a possible text declaration first */ if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); /* * An XML-1.0 document can't reference an entity not XML-1.0 */ if ((xmlStrEqual(ctx->version, BAD_CAST "1.0")) && (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) { xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH, "Version mismatch between document and entity\n"); } } /* * If the user provided its own SAX callbacks then reuse the * useData callback field, otherwise the expected setup in a * DOM builder is to have userData == ctxt */ if (ctx->userData == ctx) ctxt->userData = ctxt; else ctxt->userData = ctx->userData; /* * Doing validity checking on chunk doesn't make sense */ ctxt->instate = XML_PARSER_CONTENT; ctxt->validate = ctx->validate; ctxt->valid = ctx->valid; ctxt->loadsubset = ctx->loadsubset; ctxt->depth = ctx->depth + 1; ctxt->replaceEntities = ctx->replaceEntities; if (ctxt->validate) { ctxt->vctxt.error = ctx->vctxt.error; ctxt->vctxt.warning = ctx->vctxt.warning; } else { ctxt->vctxt.error = NULL; ctxt->vctxt.warning = NULL; } ctxt->vctxt.nodeTab = NULL; ctxt->vctxt.nodeNr = 0; ctxt->vctxt.nodeMax = 0; ctxt->vctxt.node = NULL; if (ctxt->dict != NULL) xmlDictFree(ctxt->dict); ctxt->dict = ctx->dict; ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3); ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5); ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36); ctxt->dictNames = ctx->dictNames; ctxt->attsDefault = ctx->attsDefault; ctxt->attsSpecial = ctx->attsSpecial; ctxt->linenumbers = ctx->linenumbers; xmlParseContent(ctxt); ctx->validate = ctxt->validate; ctx->valid = ctxt->valid; if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } if (ctxt->node != newDoc->children) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } if (!ctxt->wellFormed) { if (ctxt->errNo == 0) ret = 1; else ret = ctxt->errNo; } else { if (lst != NULL) { xmlNodePtr cur; /* * Return the newly created nodeset after unlinking it from * they pseudo parent. */ cur = newDoc->children->children; *lst = cur; while (cur != NULL) { cur->parent = NULL; cur = cur->next; } newDoc->children->children = NULL; } ret = 0; } ctxt->sax = oldsax; ctxt->dict = NULL; ctxt->attsDefault = NULL; ctxt->attsSpecial = NULL; xmlFreeParserCtxt(ctxt); newDoc->intSubset = NULL; newDoc->extSubset = NULL; xmlFreeDoc(newDoc); return(ret); } Commit Message: DO NOT MERGE: Add validation for eternal enities https://bugzilla.gnome.org/show_bug.cgi?id=780691 Bug: 36556310 Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648 (cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049) CWE ID: CWE-611
0
163,449
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif )) return ((tmsize_t)(-1)); assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[tile])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at row %lu, col %lu, tile %lu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned __int64) cc, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long long) cc, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[tile]; mb=ma+size; if ((td->td_stripoffset[tile] > (uint64)TIFF_TMSIZE_T_MAX)||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned __int64) n, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned long long) n, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } Commit Message: * libtiff/tif_read.c, libtiff/tiffiop.h: fix uint32 overflow in TIFFReadEncodedStrip() that caused an integer division by zero. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2596 CWE ID: CWE-369
0
70,339
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int prepare_reply(struct genl_info *info, u8 cmd, struct sk_buff **skbp, size_t size) { struct sk_buff *skb; void *reply; /* * If new attributes are added, please revisit this allocation */ skb = genlmsg_new(size, GFP_KERNEL); if (!skb) return -ENOMEM; if (!info) { int seq = this_cpu_inc_return(taskstats_seqnum) - 1; reply = genlmsg_put(skb, 0, seq, &family, 0, cmd); } else reply = genlmsg_put_reply(skb, info, &family, 0, cmd); if (reply == NULL) { nlmsg_free(skb); return -EINVAL; } *skbp = skb; return 0; } Commit Message: Make TASKSTATS require root access Ok, this isn't optimal, since it means that 'iotop' needs admin capabilities, and we may have to work on this some more. But at the same time it is very much not acceptable to let anybody just read anybody elses IO statistics quite at this level. Use of the GENL_ADMIN_PERM suggested by Johannes Berg as an alternative to checking the capabilities by hand. Reported-by: Vasiliy Kulikov <segoon@openwall.com> Cc: Johannes Berg <johannes.berg@intel.com> Acked-by: Balbir Singh <bsingharora@gmail.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-200
0
26,924
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void check_clr_rcv_irq(struct smi_info *smi_info) { u8 enables = 0; int rv; rv = get_global_enables(smi_info, &enables); if (!rv) { if ((enables & IPMI_BMC_RCV_MSG_INTR) == 0) /* Already clear, should work ok. */ return; enables &= ~IPMI_BMC_RCV_MSG_INTR; rv = set_global_enables(smi_info, enables); } if (rv < 0) { dev_err(smi_info->io.dev, "Cannot check clearing the rcv irq: %d\n", rv); return; } if (rv) { /* * An error when setting the event buffer bit means * clearing the bit is not supported. */ dev_warn(smi_info->io.dev, "The BMC does not support clearing the recv irq bit, compensating, but the BMC needs to be fixed.\n"); smi_info->cannot_disable_irq = true; } } Commit Message: ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: stable@vger.kernel.org Reported-by: NuoHan Qiao <qiaonuohan@huawei.com> Suggested-by: Corey Minyard <cminyard@mvista.com> Signed-off-by: Yang Yingliang <yangyingliang@huawei.com> Signed-off-by: Corey Minyard <cminyard@mvista.com> CWE ID: CWE-416
0
90,206
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh, struct nfsd4_open *open) { struct iattr iattr = { .ia_valid = ATTR_SIZE, .ia_size = 0, }; if (!open->op_truncate) return 0; if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE)) return nfserr_inval; return nfsd_setattr(rqstp, fh, &iattr, 0, (time_t)0); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
0
65,643
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static VOID SetAllVlanFilters(PARANDIS_ADAPTER *pContext, BOOLEAN bOn) { ULONG i; for (i = 0; i <= MAX_VLAN_ID; ++i) SetSingleVlanFilter(pContext, i, bOn, 7); } Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <yhindin@rehat.com> CWE ID: CWE-20
0
74,403
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) { pp::MouseInputEvent normalized_event = NormalizeMouseEvent(client_->GetPluginInstance(), event); if (normalized_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_LEFT) return OnLeftMouseDown(normalized_event); if (normalized_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) return OnMiddleMouseDown(normalized_event); if (normalized_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT) return OnRightMouseDown(normalized_event); return false; } Commit Message: [pdf] Use a temporary list when unloading pages When traversing the |deferred_page_unloads_| list and handling the unloads it's possible for new pages to get added to the list which will invalidate the iterator. This CL swaps the list with an empty list and does the iteration on the list copy. New items that are unloaded while handling the defers will be unloaded at a later point. Bug: 780450 Change-Id: Ic7ced1c82227109784fb536ce19a4dd51b9119ac Reviewed-on: https://chromium-review.googlesource.com/758916 Commit-Queue: dsinclair <dsinclair@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Cr-Commit-Position: refs/heads/master@{#515056} CWE ID: CWE-416
0
146,177
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void CrosMock::SetPowerLibraryExpectations() { EXPECT_CALL(*mock_power_library_, EnableScreenLock(_)) .Times(AnyNumber()); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
99,633
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-vsoxm] [-d DIR]/[-D] [FILE]\n" "\n" "Extract Xorg crash from FILE (or standard input)" ); /* Keep OPT_z enums and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL( 's', NULL, NULL, _("Log to syslog")), OPT_BOOL( 'o', NULL, NULL, _("Print found crash data on standard output")), OPT_STRING('d', NULL, &debug_dumps_dir, "DIR", _("Create problem directory in DIR for every crash found")), OPT_BOOL( 'D', NULL, NULL, _("Same as -d DumpLocation, DumpLocation is specified in abrt.conf")), OPT_BOOL( 'x', NULL, NULL, _("Make the problem directory world readable")), OPT_BOOL( 'm', NULL, NULL, _("Print search string(s) to stdout and exit")), OPT_END() }; unsigned opts = g_opts = parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(0); msg_prefix = g_progname; if ((opts & OPT_s) || getenv("ABRT_SYSLOG")) { logmode = LOGMODE_JOURNAL; } if (opts & OPT_m) { puts("Backtrace"); return 0; } if (opts & OPT_D) { if (opts & OPT_d) show_usage_and_die(program_usage_string, program_options); load_abrt_conf(); debug_dumps_dir = g_settings_dump_location; g_settings_dump_location = NULL; free_abrt_conf_data(); } argv += optind; if (argv[0]) xmove_fd(xopen(argv[0], O_RDONLY), STDIN_FILENO); char *line; while ((line = xmalloc_fgetline(stdin)) != NULL) { char *p = skip_pfx(line); if (strcmp(p, "Backtrace:") == 0) { free(line); g_bt_count++; process_xorg_bt(); continue; } free(line); } /* If we are run by a log watcher, this delays log rescan * (because log watcher waits to us to terminate) * and possibly prevents dreaded "abrt storm". */ if (opts & (OPT_d|OPT_D)) { if (g_bt_count > MAX_DUMPED_DD_COUNT) sleep(g_bt_count - MAX_DUMPED_DD_COUNT); } return 0; } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <jfilak@redhat.com> CWE ID: CWE-200
0
96,411
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool cli_check_msdfs_proxy(TALLOC_CTX *ctx, struct cli_state *cli, const char *sharename, char **pp_newserver, char **pp_newshare, bool force_encrypt, const char *username, const char *password, const char *domain) { struct client_dfs_referral *refs = NULL; size_t num_refs = 0; size_t consumed = 0; char *fullpath = NULL; bool res; uint16_t cnum; char *newextrapath = NULL; NTSTATUS status; const char *remote_name; if (!cli || !sharename) { return false; } remote_name = smbXcli_conn_remote_name(cli->conn); cnum = cli_state_get_tid(cli); /* special case. never check for a referral on the IPC$ share */ if (strequal(sharename, "IPC$")) { return false; } /* send a trans2_query_path_info to check for a referral */ fullpath = talloc_asprintf(ctx, "\\%s\\%s", remote_name, sharename); if (!fullpath) { return false; } /* check for the referral */ if (!NT_STATUS_IS_OK(cli_tree_connect(cli, "IPC$", "IPC", NULL, 0))) { return false; } if (force_encrypt) { status = cli_cm_force_encryption(cli, username, password, domain, "IPC$"); if (!NT_STATUS_IS_OK(status)) { return false; } } status = cli_dfs_get_referral(ctx, cli, fullpath, &refs, &num_refs, &consumed); res = NT_STATUS_IS_OK(status); status = cli_tdis(cli); if (!NT_STATUS_IS_OK(status)) { return false; } cli_state_set_tid(cli, cnum); if (!res || !num_refs) { return false; } if (!refs[0].dfspath) { return false; } if (!split_dfs_path(ctx, refs[0].dfspath, pp_newserver, pp_newshare, &newextrapath)) { return false; } /* check that this is not a self-referral */ if (strequal(remote_name, *pp_newserver) && strequal(sharename, *pp_newshare)) { return false; } return true; } Commit Message: CWE ID: CWE-20
0
2,497
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: testThread(void) { fprintf(stderr, "Specific platform thread support not detected\n"); return (-1); } Commit Message: Fix handling of parameter-entity references There were two bugs where parameter-entity references could lead to an unexpected change of the input buffer in xmlParseNameComplex and xmlDictLookup being called with an invalid pointer. Percent sign in DTD Names ========================= The NEXTL macro used to call xmlParserHandlePEReference. When parsing "complex" names inside the DTD, this could result in entity expansion which created a new input buffer. The fix is to simply remove the call to xmlParserHandlePEReference from the NEXTL macro. This is safe because no users of the macro require expansion of parameter entities. - xmlParseNameComplex - xmlParseNCNameComplex - xmlParseNmtoken The percent sign is not allowed in names, which are grammatical tokens. - xmlParseEntityValue Parameter-entity references in entity values are expanded but this happens in a separate step in this function. - xmlParseSystemLiteral Parameter-entity references are ignored in the system literal. - xmlParseAttValueComplex - xmlParseCharDataComplex - xmlParseCommentComplex - xmlParsePI - xmlParseCDSect Parameter-entity references are ignored outside the DTD. - xmlLoadEntityContent This function is only called from xmlStringLenDecodeEntities and entities are replaced in a separate step immediately after the function call. This bug could also be triggered with an internal subset and double entity expansion. This fixes bug 766956 initially reported by Wei Lei and independently by Chromium's ClusterFuzz, Hanno Böck, and Marco Grassi. Thanks to everyone involved. xmlParseNameComplex with XML_PARSE_OLD10 ======================================== When parsing Names inside an expanded parameter entity with the XML_PARSE_OLD10 option, xmlParseNameComplex would call xmlGROW via the GROW macro if the input buffer was exhausted. At the end of the parameter entity's replacement text, this function would then call xmlPopInput which invalidated the input buffer. There should be no need to invoke GROW in this situation because the buffer is grown periodically every XML_PARSER_CHUNK_SIZE characters and, at least for UTF-8, in xmlCurrentChar. This also matches the code path executed when XML_PARSE_OLD10 is not set. This fixes bugs 781205 (CVE-2017-9049) and 781361 (CVE-2017-9050). Thanks to Marcel Böhme and Thuan Pham for the report. Additional hardening ==================== A separate check was added in xmlParseNameComplex to validate the buffer size. CWE ID: CWE-119
0
59,634
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: virtual void SetUp() { m_webViewImpl = toWebViewImpl(WebView::create(0)); WebSettings* settings = m_webViewImpl->settings(); settings->setImagesEnabled(true); settings->setLoadsImagesAutomatically(true); settings->setJavaScriptEnabled(true); m_mainFrame = WebFrame::create(&m_webFrameClient); m_webViewImpl->setMainFrame(m_mainFrame); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > R=abarth@chromium.org > > Review URL: https://codereview.chromium.org/68613003 TBR=tiger@opera.com Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
0
118,881
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; int buffer_size = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; int nbchars = 0; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } Commit Message: Add a check to prevent len from going negative in xmlParseAttValueComplex. BUG=158249 Review URL: https://chromiumcodereview.appspot.com/11343029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@164867 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
102,543
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc) { int i, l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; /* stack of filled segments */ struct seg *stack; struct seg *sp; char **pts; if (!im->tile) { return; } wx2=im->sx;wy2=im->sy; nc = gdImageTileGet(im,x,y); pts = (char **) ecalloc(im->sy + 1, sizeof(char *)); for (i = 0; i < im->sy + 1; i++) { pts[i] = (char *) ecalloc(im->sx + 1, sizeof(char)); } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; oc = gdImageGetPixel(im, x, y); /* 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 && (!pts[y][x] && gdImageGetPixel(im,x,y)==oc); x--) { nc = gdImageTileGet(im,x,y); pts[y][x] = 1; 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 && (!pts[y][x] && gdImageGetPixel(im,x, y)==oc); x++) { nc = gdImageTileGet(im,x,y); pts[y][x] = 1; 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 && (pts[y][x] || gdImageGetPixel(im,x, y)!=oc); x++); l = x; } while (x<=x2); } for(i = 0; i < im->sy + 1; i++) { efree(pts[i]); } efree(pts); efree(stack); } Commit Message: Fix #72696: imagefilltoborder stackoverflow on truecolor images We must not allow negative color values be passed to gdImageFillToBorder(), because that can lead to infinite recursion since the recursion termination condition will not necessarily be met. CWE ID: CWE-119
0
72,459
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void add_metadata(RCore *r, RBinReloc *reloc, ut64 addr, int mode) { RBinFile * binfile = r->bin->cur; RBinObject *binobj = binfile ? binfile->o: NULL; RBinInfo *info = binobj ? binobj->info: NULL; RIOSection *section; int cdsz; cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0; if (cdsz == 0) { return; } section = r_io_section_vget (r->io, addr); if (!section || section->flags & R_IO_EXEC) { return; } if (IS_MODE_SET(mode)) { r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr + cdsz, NULL); } else if (IS_MODE_RAD (mode)) { r_cons_printf ("f Cd %d @ 0x%08" PFMT64x "\n", cdsz, addr); } } Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923) CWE ID: CWE-125
0
82,949
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: get_first_ssl_listener_index(const struct mg_context *ctx) { unsigned int i; int idx = -1; if (ctx) { for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) { idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1; } } return idx; } Commit Message: Check length of memcmp CWE ID: CWE-125
0
81,670
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GF_Err mvhd_Read(GF_Box *s, GF_BitStream *bs) { GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s; if (ptr == NULL) return GF_BAD_PARAM; if (ptr->version == 1) { ptr->creationTime = gf_bs_read_u64(bs); ptr->modificationTime = gf_bs_read_u64(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u64(bs); } else { ptr->creationTime = gf_bs_read_u32(bs); ptr->modificationTime = gf_bs_read_u32(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u32(bs); } if (!ptr->timeScale) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Movie header timescale is invalid (0) - defaulting to 600\n" )); ptr->timeScale = 600; } ptr->preferredRate = gf_bs_read_u32(bs); ptr->preferredVolume = gf_bs_read_u16(bs); gf_bs_read_data(bs, ptr->reserved, 10); ptr->matrixA = gf_bs_read_u32(bs); ptr->matrixB = gf_bs_read_u32(bs); ptr->matrixU = gf_bs_read_u32(bs); ptr->matrixC = gf_bs_read_u32(bs); ptr->matrixD = gf_bs_read_u32(bs); ptr->matrixV = gf_bs_read_u32(bs); ptr->matrixX = gf_bs_read_u32(bs); ptr->matrixY = gf_bs_read_u32(bs); ptr->matrixW = gf_bs_read_u32(bs); ptr->previewTime = gf_bs_read_u32(bs); ptr->previewDuration = gf_bs_read_u32(bs); ptr->posterTime = gf_bs_read_u32(bs); ptr->selectionTime = gf_bs_read_u32(bs); ptr->selectionDuration = gf_bs_read_u32(bs); ptr->currentTime = gf_bs_read_u32(bs); ptr->nextTrackID = gf_bs_read_u32(bs); ptr->original_duration = ptr->duration; return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
0
80,278
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Browser::DidEndColorChooser() { color_chooser_.reset(); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
117,764
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: gfx::Rect Label::GetTextBounds() const { gfx::Rect available_rect(GetAvailableRect()); gfx::Size text_size(GetTextSize()); text_size.set_width(std::min(available_rect.width(), text_size.width())); gfx::Insets insets = GetInsets(); gfx::Point text_origin(insets.left(), insets.top()); switch (horiz_alignment_) { case ALIGN_LEFT: break; case ALIGN_CENTER: text_origin.Offset((available_rect.width() + 1 - text_size.width()) / 2, 0); break; case ALIGN_RIGHT: text_origin.set_x(available_rect.right() - text_size.width()); break; default: NOTREACHED(); break; } text_origin.Offset(0, std::max(0, (available_rect.height() - text_size.height())) / 2); return gfx::Rect(text_origin, text_size); } Commit Message: wstring: remove wstring version of SplitString Retry of r84336. BUG=23581 Review URL: http://codereview.chromium.org/6930047 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@84355 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
100,909
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int sysMapFile(const char* fn, MemMapping* pMap) { memset(pMap, 0, sizeof(*pMap)); if (fn && fn[0] == '@') { FILE* mapf = fopen(fn+1, "r"); if (mapf == NULL) { LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno)); return -1; } if (sysMapBlockFile(mapf, pMap) != 0) { LOGW("Map of '%s' failed\n", fn); return -1; } fclose(mapf); } else { int fd = open(fn, O_RDONLY, 0); if (fd < 0) { LOGE("Unable to open '%s': %s\n", fn, strerror(errno)); return -1; } if (sysMapFD(fd, pMap) != 0) { LOGE("Map of '%s' failed\n", fn); close(fd); return -1; } close(fd); } return 0; } Commit Message: Fix integer overflows in recovery procedure. Bug: 26960931 Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf (cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b) CWE ID: CWE-189
1
173,905
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: std::string GetProduct() { return version_info::GetProductNameAndVersionForUserAgent(); } 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 <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
0
142,667
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: ofputil_encode_role_reply(const struct ofp_header *request, const struct ofputil_role_request *rr) { struct ofpbuf *buf; enum ofpraw raw; raw = ofpraw_decode_assert(request); if (raw == OFPRAW_OFPT12_ROLE_REQUEST) { struct ofp12_role_request *orr; buf = ofpraw_alloc_reply(OFPRAW_OFPT12_ROLE_REPLY, request, 0); orr = ofpbuf_put_zeros(buf, sizeof *orr); orr->role = htonl(rr->role); orr->generation_id = htonll(rr->have_generation_id ? rr->generation_id : UINT64_MAX); } else if (raw == OFPRAW_NXT_ROLE_REQUEST) { struct nx_role_request *nrr; BUILD_ASSERT(NX_ROLE_OTHER == OFPCR12_ROLE_EQUAL - 1); BUILD_ASSERT(NX_ROLE_MASTER == OFPCR12_ROLE_MASTER - 1); BUILD_ASSERT(NX_ROLE_SLAVE == OFPCR12_ROLE_SLAVE - 1); buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, request, 0); nrr = ofpbuf_put_zeros(buf, sizeof *nrr); nrr->role = htonl(rr->role - 1); } else { OVS_NOT_REACHED(); } return buf; } Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command. When decoding a group mod, the current code validates the group type and command after the whole group mod has been decoded. The OF1.5 decoder, however, tries to use the type and command earlier, when it might still be invalid. This caused an assertion failure (via OVS_NOT_REACHED). This commit fixes the problem. ovs-vswitchd does not enable support for OpenFlow 1.5 by default. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249 Signed-off-by: Ben Pfaff <blp@ovn.org> Reviewed-by: Yifeng Sun <pkusunyifeng@gmail.com> CWE ID: CWE-617
0
77,594
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void config__cleanup_plugins(struct mosquitto__config *config) { int i, j; struct mosquitto__auth_plugin_config *plug; if(config->security_options.auth_plugin_configs){ for(i=0; i<config->security_options.auth_plugin_config_count; i++){ plug = &config->security_options.auth_plugin_configs[i]; mosquitto__free(plug->path); plug->path = NULL; if(plug->options){ for(j=0; j<plug->option_count; j++){ mosquitto__free(plug->options[j].key); mosquitto__free(plug->options[j].value); } mosquitto__free(plug->options); plug->options = NULL; plug->option_count = 0; } } mosquitto__free(config->security_options.auth_plugin_configs); config->security_options.auth_plugin_configs = NULL; } } Commit Message: Fix acl_file being ignore for default listener if with per_listener_settings Close #1073. Thanks to Jef Driesen. Bug: https://github.com/eclipse/mosquitto/issues/1073 CWE ID:
0
75,602
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static BOOLEAN btif_hl_proc_dch_open_cfm(tBTA_HL *p_data) { btif_hl_mdl_cb_t *p_dcb; btif_hl_pending_chan_cb_t *p_pcb; UINT8 app_idx, mcl_idx, mdl_idx, mdep_cfg_idx; BOOLEAN status = FALSE; BOOLEAN close_dch = FALSE; BTIF_TRACE_DEBUG("%s", __FUNCTION__); btif_hl_find_app_idx_using_mdepId(p_data->dch_open_cfm.local_mdep_id,&app_idx); if (btif_hl_find_mcl_idx_using_app_idx(p_data->dch_open_cfm.mcl_handle, app_idx, &mcl_idx )) { BTIF_HL_GET_APP_CB_PTR(app_idx); BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx); p_pcb = BTIF_HL_GET_PCB_PTR(app_idx, mcl_idx); if (btif_hl_find_avail_mdl_idx(app_idx, mcl_idx, &mdl_idx)) { p_dcb = BTIF_HL_GET_MDL_CB_PTR(app_idx, mcl_idx, mdl_idx); if (btif_hl_find_mdep_cfg_idx(app_idx, p_data->dch_open_cfm.local_mdep_id, &mdep_cfg_idx)) { p_dcb->in_use = TRUE; p_dcb->mdl_handle = p_data->dch_open_cfm.mdl_handle; p_dcb->local_mdep_cfg_idx = mdep_cfg_idx; p_dcb->local_mdep_id = p_data->dch_open_cfm.local_mdep_id; p_dcb->mdl_id = p_data->dch_open_cfm.mdl_id; p_dcb->dch_mode = p_data->dch_open_cfm.dch_mode; p_dcb->is_the_first_reliable= p_data->dch_open_cfm.first_reliable; p_dcb->mtu = p_data->dch_open_cfm.mtu; p_dcb->channel_id = p_pcb->channel_id; BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=%d mdl_idx=%d", app_idx, mcl_idx, mdl_idx ); btif_hl_send_setup_connecting_cb(app_idx, mcl_idx); if (btif_hl_create_socket(app_idx, mcl_idx, mdl_idx)) { status = TRUE; BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=%d mdl_idx=%d p_dcb->channel_id=0x%08x", app_idx, mcl_idx, mdl_idx, p_dcb->channel_id); btif_hl_clean_pcb(p_pcb); } else { BTIF_TRACE_ERROR("Unable to create socket"); close_dch = TRUE; } } else { BTIF_TRACE_ERROR("INVALID_LOCAL_MDEP_ID mdep_id=%d",p_data->dch_open_cfm.local_mdep_id); close_dch = TRUE; } if (close_dch) { btif_hl_clean_mdl_cb(p_dcb); BTA_HlDchClose(p_data->dch_open_cfm.mdl_handle); } } } return status; } 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
0
158,730
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: SPICE_GNUC_VISIBLE int spice_server_set_agent_copypaste(SpiceServer *s, int enable) { spice_assert(reds == s); agent_copypaste = enable; reds->agent_state.write_filter.copy_paste_enabled = agent_copypaste; reds->agent_state.read_filter.copy_paste_enabled = agent_copypaste; return 0; } Commit Message: CWE ID: CWE-119
0
1,973
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int wc_ecc_get_curve_size_from_name(const char* curveName) { int curve_idx; if (curveName == NULL) return BAD_FUNC_ARG; curve_idx = wc_ecc_get_curve_idx_from_name(curveName); if (curve_idx < 0) return curve_idx; return ecc_sets[curve_idx].size; } Commit Message: Change ECDSA signing to use blinding. CWE ID: CWE-200
0
81,891
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s) { tor_assert(lst); tor_assert(s); tor_assert(s->directory); smartlist_add(lst, rend_service_path(s, private_key_fname)); smartlist_add(lst, rend_service_path(s, hostname_fname)); smartlist_add(lst, rend_service_path(s, client_keys_fname)); smartlist_add(lst, rend_service_sos_poison_path(s)); } Commit Message: Fix log-uninitialized-stack bug in rend_service_intro_established. Fixes bug 23490; bugfix on 0.2.7.2-alpha. TROVE-2017-008 CVE-2017-0380 CWE ID: CWE-532
0
69,602
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void PasswordAutofillManager::RegisterDeletionCallback( base::OnceClosure deletion_callback) { deletion_callback_ = std::move(deletion_callback); } Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature. Fixing names of password_manager kEnableManualFallbacksFilling feature as per the naming convention. Bug: 785953 Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03 Reviewed-on: https://chromium-review.googlesource.com/900566 Reviewed-by: Vaclav Brozek <vabr@chromium.org> Commit-Queue: NIKHIL SAHNI <nikhil.sahni@samsung.com> Cr-Commit-Position: refs/heads/master@{#534923} CWE ID: CWE-264
0
124,612
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access) { gpa_t t_gpa; struct x86_exception exception; BUG_ON(!mmu_is_nested(vcpu)); /* NPT walks are always user-walks */ access |= PFERR_USER_MASK; t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception); return t_gpa; } Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings (cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e) If some vcpus are created before KVM_CREATE_IRQCHIP, then irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading to potential NULL pointer dereferences. Fix by: - ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called - ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP This is somewhat long winded because vcpu->arch.apic is created without kvm->lock held. Based on earlier patch by Michael Ellerman. Signed-off-by: Michael Ellerman <michael@ellerman.id.au> Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-399
0
20,884
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void UserCloudPolicyManagerChromeOS::EnableWildcardLoginCheck( const std::string& username) { DCHECK(access_token_.empty()); wildcard_username_ = username; } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
0
110,385
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: nfs3svc_decode_sattrargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_sattrargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = decode_sattr3(p, &args->attrs); if ((args->check_guard = ntohl(*p++)) != 0) { struct timespec time; p = decode_time3(p, &time); args->guardtime = time.tv_sec; } return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
0
65,275
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void skcipher_pull_sgl(struct sock *sk, int used) { struct alg_sock *ask = alg_sk(sk); struct skcipher_ctx *ctx = ask->private; struct skcipher_sg_list *sgl; struct scatterlist *sg; int i; while (!list_empty(&ctx->tsgl)) { sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list, list); sg = sgl->sg; for (i = 0; i < sgl->cur; i++) { int plen = min_t(int, used, sg[i].length); if (!sg_page(sg + i)) continue; sg[i].length -= plen; sg[i].offset += plen; used -= plen; ctx->used -= plen; if (sg[i].length) return; put_page(sg_page(sg + i)); sg_assign_page(sg + i, NULL); } list_del(&sgl->list); sock_kfree_s(sk, sgl, sizeof(*sgl) + sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1)); } if (!ctx->used) ctx->merge = 0; } Commit Message: crypto: algif - suppress sending source address information in recvmsg The current code does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that. Cc: <stable@vger.kernel.org> # 2.6.38 Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-200
0
30,851
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static json_t *json_object_deep_copy(const json_t *object) { json_t *result; void *iter; result = json_object(); if(!result) return NULL; /* Cannot use json_object_foreach because object has to be cast non-const */ iter = json_object_iter((json_t *)object); while(iter) { const char *key; const json_t *value; key = json_object_iter_key(iter); value = json_object_iter_value(iter); json_object_set_new_nocheck(result, key, json_deep_copy(value)); iter = json_object_iter_next((json_t *)object, iter); } return result; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
0
40,911
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void kvm_set_page_dirty(struct page *page) { kvm_set_pfn_dirty(page_to_pfn(page)); } Commit Message: KVM: unmap pages from the iommu when slots are removed commit 32f6daad4651a748a58a3ab6da0611862175722f upstream. We've been adding new mappings, but not destroying old mappings. This can lead to a page leak as pages are pinned using get_user_pages, but only unpinned with put_page if they still exist in the memslots list on vm shutdown. A memslot that is destroyed while an iommu domain is enabled for the guest will therefore result in an elevated page reference count that is never cleared. Additionally, without this fix, the iommu is only programmed with the first translation for a gpa. This can result in peer-to-peer errors if a mapping is destroyed and replaced by a new mapping at the same gpa as the iommu will still be pointing to the original, pinned memory address. Signed-off-by: Alex Williamson <alex.williamson@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-264
0
20,390
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) { return ProfileIOData::IsHandledURL(url); } Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances. BUG=174943 TEST=Can't post message to CWS. See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12301013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
115,767
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool ChromeContentBrowserClient::AllowWorkerIndexedDB( const GURL& url, const string16& name, content::ResourceContext* context, const std::vector<std::pair<int, int> >& render_views) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); ProfileIOData* io_data = ProfileIOData::FromResourceContext(context); CookieSettings* cookie_settings = io_data->GetCookieSettings(); bool allow = cookie_settings->IsSettingCookieAllowed(url, url); std::vector<std::pair<int, int> >::const_iterator i; for (i = render_views.begin(); i != render_views.end(); ++i) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&TabSpecificContentSettings::IndexedDBAccessed, i->first, i->second, url, name, !allow)); } return allow; } Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances. BUG=174943 TEST=Can't post message to CWS. See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12301013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
115,725
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebSocketJob::OnClose(SocketStream* socket) { state_ = CLOSED; WebSocketThrottle::GetInstance()->RemoveFromQueue(this); WebSocketThrottle::GetInstance()->WakeupSocketIfNecessary(); scoped_refptr<WebSocketJob> protect(this); SocketStream::Delegate* delegate = delegate_; delegate_ = NULL; socket_ = NULL; if (callback_) { waiting_ = false; callback_ = NULL; Release(); // Balanced with OnStartOpenConnection(). } if (delegate) delegate->OnClose(socket); } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
0
98,375
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: OMX_ERRORTYPE omx_video::use_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes, OMX_IN OMX_U8* buffer) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter unsigned char *buf_addr = NULL; #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("Inside use_output_buffer()"); if (bytes != m_sOutPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: use_output_buffer: Size Mismatch!! " "bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sOutPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_out_mem_ptr) { output_use_buffer = true; int nBufHdrSize = 0; DEBUG_PRINT_LOW("Allocating First Output Buffer(%u)",(unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); if (m_out_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_out_mem_ptr"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif if (m_out_mem_ptr) { bufHdr = m_out_mem_ptr; DEBUG_PRINT_LOW("Memory Allocation Succeeded for OUT port%p",m_out_mem_ptr); for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: Output buf mem alloc failed[0x%p]",m_out_mem_ptr); eRet = OMX_ErrorInsufficientResources; } } for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (!m_use_output_pmem) { #ifdef USE_ION #ifdef _MSM8974_ align_size = (m_sOutPortDef.nBufferSize + (SZ_4K - 1)) & ~(SZ_4K - 1); m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,0); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory( m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap() Failed"); close(m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } } else { OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO*>((*bufferHdr)->pAppPrivate); DEBUG_PRINT_LOW("Inside qcom_ext pParam: %p", pParam); if (pParam) { DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (int)pParam->offset); m_pOutput_pmem[i].fd = pParam->pmem_fd; m_pOutput_pmem[i].offset = pParam->offset; m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].buffer = (unsigned char *)buffer; } else { DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM o/p UseBuffer case"); return OMX_ErrorBadParameter; } buf_addr = (unsigned char *)buffer; } DEBUG_PRINT_LOW("use_out:: bufhdr = %p, pBuffer = %p, m_pOutput_pmem[i].buffer = %p", (*bufferHdr), (*bufferHdr)->pBuffer, m_pOutput_pmem[i].buffer); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf Failed for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p Buffers have been Used, invalid use_buf call for " "index = %u", i); eRet = OMX_ErrorInsufficientResources; } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
0
160,663
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: _dbus_header_cache_invalidate_all (DBusHeader *header) { int i; i = 0; while (i <= DBUS_HEADER_FIELD_LAST) { header->fields[i].value_pos = _DBUS_HEADER_FIELD_VALUE_UNKNOWN; ++i; } } Commit Message: CWE ID: CWE-20
0
2,738
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: TabContents* PrintPreviewHandler::preview_tab_contents() const { return TabContents::FromWebContents(preview_web_contents()); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
0
105,835
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SyncBackendHost::Core::RouteJsMessageReplyOnFrontendLoop( const std::string& name, const JsArgList& args, const JsEventHandler* target) { if (!host_ || !parent_router_) return; DCHECK_EQ(MessageLoop::current(), host_->frontend_loop_); parent_router_->RouteJsMessageReply(name, args, target); } Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed. BUG=69561 TEST=Run sync manually and run integration tests, sync should not crash. Review URL: http://codereview.chromium.org/7016007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
101,478
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: rpc_default_callback(struct rpc_task *task, void *data) { } Commit Message: NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin <vvs@sw.ru> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> Cc: stable@kernel.org CWE ID: CWE-399
0
34,900
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool PageLayoutIsEqual(const PrintMsg_PrintPages_Params& oldParams, const PrintMsg_PrintPages_Params& newParams) { return oldParams.params.content_size == newParams.params.content_size && oldParams.params.printable_area == newParams.params.printable_area && oldParams.params.page_size == newParams.params.page_size && oldParams.params.margin_top == newParams.params.margin_top && oldParams.params.margin_left == newParams.params.margin_left && oldParams.params.desired_dpi == newParams.params.desired_dpi && oldParams.params.dpi == newParams.params.dpi; } Commit Message: Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
0
102,581
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x + right.x; destination->y = left.y + right.y; destination->z = left.z + right.z; destination->w = left.w + right.w; } Commit Message: Added check to prevent image being 0x0 (reported in #489). CWE ID: CWE-20
0
65,113
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: AtomicString Document::contentType() const { if (!m_mimeType.isEmpty()) return m_mimeType; if (DocumentLoader* documentLoader = loader()) return documentLoader->mimeType(); String mimeType = suggestedMIMEType(); if (!mimeType.isEmpty()) return AtomicString(mimeType); return AtomicString("application/xml"); } Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone. BUG=556724,577105 Review URL: https://codereview.chromium.org/1667573002 Cr-Commit-Position: refs/heads/master@{#373642} CWE ID: CWE-264
0
124,305
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, one, offset, pixel_info_length; ssize_t count, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 64) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows*MagickMax(number_planes,4); pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Fixed check for the number of pixels that will be allocated. CWE ID: CWE-125
1
168,808
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool CanonicalizePort(const char* spec, const Component& port, int default_port_for_scheme, CanonOutput* output, Component* out_port) { return DoPort<char, unsigned char>(spec, port, default_port_for_scheme, output, out_port); } Commit Message: Percent-encode UTF8 characters in URL fragment identifiers. This brings us into line with Firefox, Safari, and the spec. Bug: 758523 Change-Id: I7e354ab441222d9fd08e45f0e70f91ad4e35fafe Reviewed-on: https://chromium-review.googlesource.com/668363 Commit-Queue: Mike West <mkwst@chromium.org> Reviewed-by: Jochen Eisinger <jochen@chromium.org> Reviewed-by: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#507481} CWE ID: CWE-79
0
149,849
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static enum test_return test_binary_incr_impl(const char* key, uint8_t cmd) { union { protocol_binary_request_no_extras request; protocol_binary_response_no_extras response_header; protocol_binary_response_incr response; char bytes[1024]; } send, receive; size_t len = arithmetic_command(send.bytes, sizeof(send.bytes), cmd, key, strlen(key), 1, 0, 0); int ii; for (ii = 0; ii < 10; ++ii) { safe_send(send.bytes, len, false); if (cmd == PROTOCOL_BINARY_CMD_INCREMENT) { safe_recv_packet(receive.bytes, sizeof(receive.bytes)); validate_response_header(&receive.response_header, cmd, PROTOCOL_BINARY_RESPONSE_SUCCESS); assert(ntohll(receive.response.message.body.value) == ii); } } if (cmd == PROTOCOL_BINARY_CMD_INCREMENTQ) { test_binary_noop(); } return TEST_PASS; } Commit Message: Issue 102: Piping null to the server will crash it CWE ID: CWE-20
0
94,264
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static inline void unmap_mapping_range_tree(struct rb_root *root, struct zap_details *details) { struct vm_area_struct *vma; pgoff_t vba, vea, zba, zea; vma_interval_tree_foreach(vma, root, details->first_index, details->last_index) { vba = vma->vm_pgoff; vea = vba + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) - 1; /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */ zba = details->first_index; if (zba < vba) zba = vba; zea = details->last_index; if (zea > vea) zea = vea; unmap_mapping_range_vma(vma, ((zba - vba) << PAGE_SHIFT) + vma->vm_start, ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start, details); } } Commit Message: vm: add vm_iomap_memory() helper function Various drivers end up replicating the code to mmap() their memory buffers into user space, and our core memory remapping function may be very flexible but it is unnecessarily complicated for the common cases to use. Our internal VM uses pfn's ("page frame numbers") which simplifies things for the VM, and allows us to pass physical addresses around in a denser and more efficient format than passing a "phys_addr_t" around, and having to shift it up and down by the page size. But it just means that drivers end up doing that shifting instead at the interface level. It also means that drivers end up mucking around with internal VM things like the vma details (vm_pgoff, vm_start/end) way more than they really need to. So this just exports a function to map a certain physical memory range into user space (using a phys_addr_t based interface that is much more natural for a driver) and hides all the complexity from the driver. Some drivers will still end up tweaking the vm_page_prot details for things like prefetching or cacheability etc, but that's actually relevant to the driver, rather than caring about what the page offset of the mapping is into the particular IO memory region. Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-189
0
94,461
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ewk_frame_load_firstlayout_finished(Evas_Object* ewkFrame) { evas_object_smart_callback_call(ewkFrame, "load,firstlayout,finished", 0); } Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing https://bugs.webkit.org/show_bug.cgi?id=85879 Patch by Mikhail Pozdnyakov <mikhail.pozdnyakov@intel.com> on 2012-05-17 Reviewed by Noam Rosenthal. Source/WebKit/efl: _ewk_frame_smart_del() is considering now that the frame can be present in cache. loader()->detachFromParent() is only applied for the main frame. loader()->cancelAndClear() is not used anymore. * ewk/ewk_frame.cpp: (_ewk_frame_smart_del): LayoutTests: * platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html. git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
107,668
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { register const xmlChar *cmp = other; register const xmlChar *in; const xmlChar *ret; GROW; in = ctxt->input->cur; while (*in != 0 && *in == *cmp) { ++in; ++cmp; ctxt->input->col++; } if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) { /* success */ ctxt->input->cur = in; return (const xmlChar*) 1; } /* failure (or end of input buffer), check with full function */ ret = xmlParseName (ctxt); /* strings coming from the dictionnary direct compare possible */ if (ret == other) { return (const xmlChar*) 1; } return ret; } 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
1
171,296
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int sg_proc_seq_show_version(struct seq_file *s, void *v) { seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR, sg_version_date); return 0; } Commit Message: sg_start_req(): make sure that there's not too many elements in iovec unfortunately, allowing an arbitrary 16bit value means a possibility of overflow in the calculation of total number of pages in bio_map_user_iov() - we rely on there being no more than PAGE_SIZE members of sum in the first loop there. If that sum wraps around, we end up allocating too small array of pointers to pages and it's easy to overflow it in the second loop. X-Coverup: TINC (and there's no lumber cartel either) Cc: stable@vger.kernel.org # way, way back Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-189
0
42,290