prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RemoteFrame::Navigate(const FrameLoadRequest& passed_request) { FrameLoadRequest frame_request(passed_request); FrameLoader::SetReferrerForFrameRequest(frame_request); FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(), frame_request.OriginDocument()); frame_request.GetResourceRequest().SetHasUserGesture( Frame::HasTransientUserActivation(this)); Client()->Navigate(frame_request.GetResourceRequest(), frame_request.ReplacesCurrentItem()); } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190 Target: 1 Example 2: Code: ZEND_API zval* ZEND_FASTCALL zend_hash_str_add_empty_element(HashTable *ht, const char *str, size_t len) { zval dummy; ZVAL_NULL(&dummy); return zend_hash_str_add(ht, str, len, &dummy); } Commit Message: Fix #73832 - leave the table in a safe state if the size is too big. CWE ID: CWE-190 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,Image* image, const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/148 CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ip6_print(netdissect_options *ndo, const u_char *bp, u_int length) { register const struct ip6_hdr *ip6; register int advance; u_int len; const u_char *ipend; register const u_char *cp; register u_int payload_len; int nh; int fragmented = 0; u_int flow; ip6 = (const struct ip6_hdr *)bp; ND_TCHECK(*ip6); if (length < sizeof (struct ip6_hdr)) { ND_PRINT((ndo, "truncated-ip6 %u", length)); return; } if (!ndo->ndo_eflag) ND_PRINT((ndo, "IP6 ")); if (IP6_VERSION(ip6) != 6) { ND_PRINT((ndo,"version error: %u != 6", IP6_VERSION(ip6))); return; } payload_len = EXTRACT_16BITS(&ip6->ip6_plen); len = payload_len + sizeof(struct ip6_hdr); if (length < len) ND_PRINT((ndo, "truncated-ip6 - %u bytes missing!", len - length)); if (ndo->ndo_vflag) { flow = EXTRACT_32BITS(&ip6->ip6_flow); ND_PRINT((ndo, "(")); #if 0 /* rfc1883 */ if (flow & 0x0f000000) ND_PRINT((ndo, "pri 0x%02x, ", (flow & 0x0f000000) >> 24)); if (flow & 0x00ffffff) ND_PRINT((ndo, "flowlabel 0x%06x, ", flow & 0x00ffffff)); #else /* RFC 2460 */ if (flow & 0x0ff00000) ND_PRINT((ndo, "class 0x%02x, ", (flow & 0x0ff00000) >> 20)); if (flow & 0x000fffff) ND_PRINT((ndo, "flowlabel 0x%05x, ", flow & 0x000fffff)); #endif ND_PRINT((ndo, "hlim %u, next-header %s (%u) payload length: %u) ", ip6->ip6_hlim, tok2str(ipproto_values,"unknown",ip6->ip6_nxt), ip6->ip6_nxt, payload_len)); } /* * Cut off the snapshot length to the end of the IP payload. */ ipend = bp + len; if (ipend < ndo->ndo_snapend) ndo->ndo_snapend = ipend; cp = (const u_char *)ip6; advance = sizeof(struct ip6_hdr); nh = ip6->ip6_nxt; while (cp < ndo->ndo_snapend && advance > 0) { cp += advance; len -= advance; if (cp == (const u_char *)(ip6 + 1) && nh != IPPROTO_TCP && nh != IPPROTO_UDP && nh != IPPROTO_DCCP && nh != IPPROTO_SCTP) { ND_PRINT((ndo, "%s > %s: ", ip6addr_string(ndo, &ip6->ip6_src), ip6addr_string(ndo, &ip6->ip6_dst))); } switch (nh) { case IPPROTO_HOPOPTS: advance = hbhopt_print(ndo, cp); if (advance < 0) return; nh = *cp; break; case IPPROTO_DSTOPTS: advance = dstopt_print(ndo, cp); if (advance < 0) return; nh = *cp; break; case IPPROTO_FRAGMENT: advance = frag6_print(ndo, cp, (const u_char *)ip6); if (advance < 0 || ndo->ndo_snapend <= cp + advance) return; nh = *cp; fragmented = 1; break; case IPPROTO_MOBILITY_OLD: case IPPROTO_MOBILITY: /* * XXX - we don't use "advance"; RFC 3775 says that * the next header field in a mobility header * should be IPPROTO_NONE, but speaks of * the possiblity of a future extension in * which payload can be piggybacked atop a * mobility header. */ advance = mobility_print(ndo, cp, (const u_char *)ip6); nh = *cp; return; case IPPROTO_ROUTING: advance = rt6_print(ndo, cp, (const u_char *)ip6); nh = *cp; break; case IPPROTO_SCTP: sctp_print(ndo, cp, (const u_char *)ip6, len); return; case IPPROTO_DCCP: dccp_print(ndo, cp, (const u_char *)ip6, len); return; case IPPROTO_TCP: tcp_print(ndo, cp, len, (const u_char *)ip6, fragmented); return; case IPPROTO_UDP: udp_print(ndo, cp, len, (const u_char *)ip6, fragmented); return; case IPPROTO_ICMPV6: icmp6_print(ndo, cp, len, (const u_char *)ip6, fragmented); return; case IPPROTO_AH: advance = ah_print(ndo, cp); nh = *cp; break; case IPPROTO_ESP: { int enh, padlen; advance = esp_print(ndo, cp, len, (const u_char *)ip6, &enh, &padlen); nh = enh & 0xff; len -= padlen; break; } case IPPROTO_IPCOMP: { ipcomp_print(ndo, cp); /* * Either this has decompressed the payload and * printed it, in which case there's nothing more * to do, or it hasn't, in which case there's * nothing more to do. */ advance = -1; break; } case IPPROTO_PIM: pim_print(ndo, cp, len, (const u_char *)ip6); return; case IPPROTO_OSPF: ospf6_print(ndo, cp, len); return; case IPPROTO_IPV6: ip6_print(ndo, cp, len); return; case IPPROTO_IPV4: ip_print(ndo, cp, len); return; case IPPROTO_PGM: pgm_print(ndo, cp, len, (const u_char *)ip6); return; case IPPROTO_GRE: gre_print(ndo, cp, len); return; case IPPROTO_RSVP: rsvp_print(ndo, cp, len); return; case IPPROTO_NONE: ND_PRINT((ndo, "no next header")); return; default: ND_PRINT((ndo, "ip-proto-%d %d", nh, len)); return; } } return; trunc: ND_PRINT((ndo, "[|ip6]")); } Commit Message: CVE-2017-12985/IPv6: Check for print routines returning -1 when running past the end. rt6_print(), ah_print(), and esp_print() return -1 if they run up against the end of the packet while dissecting; if that happens, stop dissecting, don't try to fetch the next header value, because 1) *it* might be past the end of the packet and 2) we won't be using it in any case, as we'll be exiting the loop. Also, change mobility_print() to return -1 if it runs up against the end of the packet, and stop dissecting if it does so. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: bool HTMLCanvasElement::IsOpaque() const { return context_ && !context_->CreationAttributes().alpha; } Commit Message: Clean up CanvasResourceDispatcher on finalizer We may have pending mojo messages after GC, so we want to drop the dispatcher as soon as possible. Bug: 929757,913964 Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0 Reviewed-on: https://chromium-review.googlesource.com/c/1489175 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Auto-Submit: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#635833} CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int is_idle_stream_id(h2o_http2_conn_t *conn, uint32_t stream_id) { return (h2o_http2_stream_is_push(stream_id) ? conn->push_stream_ids.max_open : conn->pull_stream_ids.max_open) < stream_id; } Commit Message: h2: use after free on premature connection close #920 lib/http2/connection.c:on_read() calls parse_input(), which might free `conn`. It does so in particular if the connection preface isn't the expected one in expect_preface(). `conn` is then used after the free in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`. We fix this by adding a return value to close_connection that returns a negative value if `conn` has been free'd and can't be used anymore. Credits for finding the bug to Tim Newsham. CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DestroySkImageOnOriginalThread( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper, std::unique_ptr<gpu::SyncToken> sync_token) { if (context_provider_wrapper && image->isValid( context_provider_wrapper->ContextProvider()->GetGrContext())) { if (sync_token->HasData()) { context_provider_wrapper->ContextProvider() ->ContextGL() ->WaitSyncTokenCHROMIUM(sync_token->GetData()); } image->getTexture()->textureParamsModified(); } } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119 Target: 1 Example 2: Code: static int csnmp_config_add_host_priv_protocol(host_definition_t *hd, oconfig_item_t *ci) { char buffer[4]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (strcasecmp("AES", buffer) == 0) { hd->priv_protocol = usmAESPrivProtocol; hd->priv_protocol_len = sizeof(usmAESPrivProtocol) / sizeof(oid); } else if (strcasecmp("DES", buffer) == 0) { hd->priv_protocol = usmDESPrivProtocol; hd->priv_protocol_len = sizeof(usmDESPrivProtocol) / sizeof(oid); } else { WARNING("snmp plugin: The `PrivProtocol' config option must be `AES' or " "`DES'."); return (-1); } DEBUG("snmp plugin: host = %s; host->priv_protocol = %s;", hd->name, hd->priv_protocol == usmAESPrivProtocol ? "AES" : "DES"); return (0); } /* int csnmp_config_add_host_priv_protocol */ Commit Message: snmp plugin: Fix double free of request PDU snmp_sess_synch_response() always frees request PDU, in both case of request error and success. If error condition occurs inside of `while (status == 0)` loop, double free of `req` happens. Issue: #2291 Signed-off-by: Florian Forster <[email protected]> CWE ID: CWE-415 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: blink::mojom::FileChooserPtr RenderFrameHostImpl::BindFileChooserForTesting() { blink::mojom::FileChooserPtr chooser; FileChooserImpl::Create(this, mojo::MakeRequest(&chooser)); return chooser; } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter, param_type* r) { const char *data; int data_size = 0; bool result = m->ReadData(iter, &data, &data_size); if (result && data_size == sizeof(LOGFONT)) { memcpy(r, data, sizeof(LOGFONT)); } else { result = false; NOTREACHED(); } return result; } Commit Message: Verify lfFaceName is NUL terminated in IPC deserializer. BUG=162066 Review URL: https://chromiumcodereview.appspot.com/11416115 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168937 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: XSSAuditor::XSSAuditor() : is_enabled_(false), xss_protection_(kFilterReflectedXSS), did_send_valid_xss_protection_header_(false), state_(kUninitialized), script_tag_found_in_request_(false), script_tag_nesting_level_(0), encoding_(UTF8Encoding()) { } Commit Message: Restrict the xss audit report URL to same origin BUG=441275 [email protected],[email protected] Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d Reviewed-on: https://chromium-review.googlesource.com/768367 Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#516666} CWE ID: CWE-79 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool IDNToUnicodeOneComponent(const base::char16* comp, size_t comp_len, bool is_tld_ascii, bool enable_spoof_checks, base::string16* out, bool* has_idn_component) { DCHECK(out); DCHECK(has_idn_component); *has_idn_component = false; if (comp_len == 0) return false; static const base::char16 kIdnPrefix[] = {'x', 'n', '-', '-'}; if (comp_len <= base::size(kIdnPrefix) || memcmp(comp, kIdnPrefix, sizeof(kIdnPrefix)) != 0) { out->append(comp, comp_len); return false; } UIDNA* uidna = g_uidna.Get().value; DCHECK(uidna != nullptr); size_t original_length = out->length(); int32_t output_length = 64; UIDNAInfo info = UIDNA_INFO_INITIALIZER; UErrorCode status; do { out->resize(original_length + output_length); status = U_ZERO_ERROR; output_length = uidna_labelToUnicode( uidna, comp, static_cast<int32_t>(comp_len), &(*out)[original_length], output_length, &info, &status); } while ((status == U_BUFFER_OVERFLOW_ERROR && info.errors == 0)); if (U_SUCCESS(status) && info.errors == 0) { *has_idn_component = true; out->resize(original_length + output_length); if (!enable_spoof_checks) { return true; } if (IsIDNComponentSafe( base::StringPiece16(out->data() + original_length, base::checked_cast<size_t>(output_length)), is_tld_ascii)) { return true; } } out->resize(original_length); out->append(comp, comp_len); return false; } Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains This character (þ) can be confused with both b and p when used in a domain name. IDN spoof checker doesn't have a good way of flagging a character as confusable with multiple characters, so it can't catch spoofs containing this character. As a practical fix, this CL restricts this character to domains under Iceland's ccTLD (.is). With this change, a domain name containing "þ" with a non-.is TLD will be displayed in punycode in the UI. This change affects less than 10 real world domains with limited popularity. Bug: 798892, 843352, 904327, 1017707 Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992 Commit-Queue: Mustafa Emre Acer <[email protected]> Reviewed-by: Christopher Thompson <[email protected]> Cr-Commit-Position: refs/heads/master@{#709309} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xsltApplyTemplates(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemApplyTemplatesPtr comp = (xsltStyleItemApplyTemplatesPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif int i; xmlNodePtr cur, delNode = NULL, oldContextNode; xmlNodeSetPtr list = NULL, oldList; xsltStackElemPtr withParams = NULL; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; const xmlChar *oldMode, *oldModeURI; xmlDocPtr oldXPDoc; xsltDocumentPtr oldDocInfo; xmlXPathContextPtr xpctxt; xmlNsPtr *oldXPNamespaces; if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:apply-templates : compilation failed\n"); return; } if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; #ifdef WITH_XSLT_DEBUG_PROCESS if ((node != NULL) && (node->name != NULL)) XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext, "xsltApplyTemplates: node: '%s'\n", node->name)); #endif xpctxt = ctxt->xpathCtxt; /* * Save context states. */ oldContextNode = ctxt->node; oldMode = ctxt->mode; oldModeURI = ctxt->modeURI; oldDocInfo = ctxt->document; oldList = ctxt->nodeList; /* * The xpath context size and proximity position, as * well as the xpath and context documents, may be changed * so we save their initial state and will restore on exit */ oldXPContextSize = xpctxt->contextSize; oldXPProximityPosition = xpctxt->proximityPosition; oldXPDoc = xpctxt->doc; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; /* * Set up contexts. */ ctxt->mode = comp->mode; ctxt->modeURI = comp->modeURI; if (comp->select != NULL) { xmlXPathObjectPtr res = NULL; if (comp->comp == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:apply-templates : compilation failed\n"); goto error; } #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext, "xsltApplyTemplates: select %s\n", comp->select)); #endif /* * Set up XPath. */ xpctxt->node = node; /* Set the "context node" */ #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif res = xmlXPathCompiledEval(comp->comp, xpctxt); xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; if (res != NULL) { if (res->type == XPATH_NODESET) { list = res->nodesetval; /* consume the node set */ res->nodesetval = NULL; } else { xsltTransformError(ctxt, NULL, inst, "The 'select' expression did not evaluate to a " "node set.\n"); ctxt->state = XSLT_STATE_STOPPED; xmlXPathFreeObject(res); goto error; } xmlXPathFreeObject(res); /* * Note: An xsl:apply-templates with a 'select' attribute, * can change the current source doc. */ } else { xsltTransformError(ctxt, NULL, inst, "Failed to evaluate the 'select' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } if (list == NULL) { #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext, "xsltApplyTemplates: select didn't evaluate to a node list\n")); #endif goto exit; } /* * * NOTE: Previously a document info (xsltDocument) was * created and attached to the Result Tree Fragment. * But such a document info is created on demand in * xsltKeyFunction() (functions.c), so we need to create * it here beforehand. * In order to take care of potential keys we need to * do some extra work for the case when a Result Tree Fragment * is converted into a nodeset (e.g. exslt:node-set()) : * We attach a "pseudo-doc" (xsltDocument) to _private. * This xsltDocument, together with the keyset, will be freed * when the Result Tree Fragment is freed. * */ #if 0 if ((ctxt->nbKeys > 0) && (list->nodeNr != 0) && (list->nodeTab[0]->doc != NULL) && XSLT_IS_RES_TREE_FRAG(list->nodeTab[0]->doc)) { /* * NOTE that it's also OK if @effectiveDocInfo will be * set to NULL. */ isRTF = 1; effectiveDocInfo = list->nodeTab[0]->doc->_private; } #endif } else { /* * Build an XPath node set with the children */ list = xmlXPathNodeSetCreate(NULL); if (list == NULL) goto error; if (node->type != XML_NAMESPACE_DECL) cur = node->children; else cur = NULL; while (cur != NULL) { switch (cur->type) { case XML_TEXT_NODE: if ((IS_BLANK_NODE(cur)) && (cur->parent != NULL) && (cur->parent->type == XML_ELEMENT_NODE) && (ctxt->style->stripSpaces != NULL)) { const xmlChar *val; if (cur->parent->ns != NULL) { val = (const xmlChar *) xmlHashLookup2(ctxt->style->stripSpaces, cur->parent->name, cur->parent->ns->href); if (val == NULL) { val = (const xmlChar *) xmlHashLookup2(ctxt->style->stripSpaces, BAD_CAST "*", cur->parent->ns->href); } } else { val = (const xmlChar *) xmlHashLookup2(ctxt->style->stripSpaces, cur->parent->name, NULL); } if ((val != NULL) && (xmlStrEqual(val, (xmlChar *) "strip"))) { delNode = cur; break; } } /* no break on purpose */ case XML_ELEMENT_NODE: case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: case XML_CDATA_SECTION_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: xmlXPathNodeSetAddUnique(list, cur); break; case XML_DTD_NODE: /* Unlink the DTD, it's still reachable * using doc->intSubset */ if (cur->next != NULL) cur->next->prev = cur->prev; if (cur->prev != NULL) cur->prev->next = cur->next; break; case XML_NAMESPACE_DECL: break; default: #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext, "xsltApplyTemplates: skipping cur type %d\n", cur->type)); #endif delNode = cur; } cur = cur->next; if (delNode != NULL) { #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext, "xsltApplyTemplates: removing ignorable blank cur\n")); #endif xmlUnlinkNode(delNode); xmlFreeNode(delNode); delNode = NULL; } } } #ifdef WITH_XSLT_DEBUG_PROCESS if (list != NULL) XSLT_TRACE(ctxt,XSLT_TRACE_APPLY_TEMPLATES,xsltGenericDebug(xsltGenericDebugContext, "xsltApplyTemplates: list of %d nodes\n", list->nodeNr)); #endif if ((list == NULL) || (list->nodeNr == 0)) goto exit; /* * Set the context's node set and size; this is also needed for * for xsltDoSortFunction(). */ ctxt->nodeList = list; /* * Process xsl:with-param and xsl:sort instructions. * (The code became so verbose just to avoid the * xmlNodePtr sorts[XSLT_MAX_SORT] if there's no xsl:sort) * BUG TODO: We are not using namespaced potentially defined on the * xsl:sort or xsl:with-param elements; XPath expression might fail. */ if (inst->children) { xsltStackElemPtr param; cur = inst->children; while (cur) { #ifdef WITH_DEBUGGER if (ctxt->debugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(cur, node, NULL, ctxt); #endif if (ctxt->state == XSLT_STATE_STOPPED) break; if (cur->type == XML_TEXT_NODE) { cur = cur->next; continue; } if (! IS_XSLT_ELEM(cur)) break; if (IS_XSLT_NAME(cur, "with-param")) { param = xsltParseStylesheetCallerParam(ctxt, cur); if (param != NULL) { param->next = withParams; withParams = param; } } if (IS_XSLT_NAME(cur, "sort")) { xsltTemplatePtr oldCurTempRule = ctxt->currentTemplateRule; int nbsorts = 0; xmlNodePtr sorts[XSLT_MAX_SORT]; sorts[nbsorts++] = cur; while (cur) { #ifdef WITH_DEBUGGER if (ctxt->debugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(cur, node, NULL, ctxt); #endif if (ctxt->state == XSLT_STATE_STOPPED) break; if (cur->type == XML_TEXT_NODE) { cur = cur->next; continue; } if (! IS_XSLT_ELEM(cur)) break; if (IS_XSLT_NAME(cur, "with-param")) { param = xsltParseStylesheetCallerParam(ctxt, cur); if (param != NULL) { param->next = withParams; withParams = param; } } if (IS_XSLT_NAME(cur, "sort")) { if (nbsorts >= XSLT_MAX_SORT) { xsltTransformError(ctxt, NULL, cur, "The number (%d) of xsl:sort instructions exceeds the " "maximum allowed by this processor's settings.\n", nbsorts); ctxt->state = XSLT_STATE_STOPPED; break; } else { sorts[nbsorts++] = cur; } } cur = cur->next; } /* * The "current template rule" is cleared for xsl:sort. */ ctxt->currentTemplateRule = NULL; /* * Sort. */ xsltDoSortFunction(ctxt, sorts, nbsorts); ctxt->currentTemplateRule = oldCurTempRule; break; } cur = cur->next; } } xpctxt->contextSize = list->nodeNr; /* * Apply templates for all selected source nodes. */ for (i = 0; i < list->nodeNr; i++) { cur = list->nodeTab[i]; /* * The node becomes the "current node". */ ctxt->node = cur; /* * An xsl:apply-templates can change the current context doc. * OPTIMIZE TODO: Get rid of the need to set the context doc. */ if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL)) xpctxt->doc = cur->doc; xpctxt->proximityPosition = i + 1; /* * Find and apply a template for this node. */ xsltProcessOneNode(ctxt, cur, withParams); } exit: error: /* * Free the parameter list. */ if (withParams != NULL) xsltFreeStackElemList(withParams); if (list != NULL) xmlXPathFreeNodeSet(list); /* * Restore context states. */ xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; xpctxt->doc = oldXPDoc; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; ctxt->document = oldDocInfo; ctxt->nodeList = oldList; ctxt->node = oldContextNode; ctxt->mode = oldMode; ctxt->modeURI = oldModeURI; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 1 Example 2: Code: static ssize_t new_offset_store(struct md_rdev *rdev, const char *buf, size_t len) { unsigned long long new_offset; struct mddev *mddev = rdev->mddev; if (kstrtoull(buf, 10, &new_offset) < 0) return -EINVAL; if (mddev->sync_thread || test_bit(MD_RECOVERY_RUNNING,&mddev->recovery)) return -EBUSY; if (new_offset == rdev->data_offset) /* reset is always permitted */ ; else if (new_offset > rdev->data_offset) { /* must not push array size beyond rdev_sectors */ if (new_offset - rdev->data_offset + mddev->dev_sectors > rdev->sectors) return -E2BIG; } /* Metadata worries about other space details. */ /* decreasing the offset is inconsistent with a backwards * reshape. */ if (new_offset < rdev->data_offset && mddev->reshape_backwards) return -EINVAL; /* Increasing offset is inconsistent with forwards * reshape. reshape_direction should be set to * 'backwards' first. */ if (new_offset > rdev->data_offset && !mddev->reshape_backwards) return -EINVAL; if (mddev->pers && mddev->persistent && !super_types[mddev->major_version] .allow_new_offset(rdev, new_offset)) return -E2BIG; rdev->new_data_offset = new_offset; if (new_offset > rdev->data_offset) mddev->reshape_backwards = 1; else if (new_offset < rdev->data_offset) mddev->reshape_backwards = 0; return len; } 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 <[email protected]> Signed-off-by: NeilBrown <[email protected]> CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: tt_cmap10_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_ULong length, count; if ( table + 20 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); p = table + 16; count = TT_NEXT_ULONG( p ); if ( table + length > valid->limit || length < 20 + count * 2 ) FT_INVALID_TOO_SHORT; /* check glyph indices */ { FT_UInt gindex; for ( ; count > 0; count-- ) { gindex = TT_NEXT_USHORT( p ); if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; } } return SFNT_Err_Ok; } Commit Message: CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void TearDown() { delete[] src_; delete[] ref_; libvpx_test::ClearSystemState(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static int cdrom_ioctl_changer_nslots(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROM_CHANGER_NSLOTS\n"); return cdi->capacity; } Commit Message: cdrom: fix improper type cast, which can leat to information leak. There is another cast from unsigned long to int which causes a bounds check to fail with specially crafted input. The value is then used as an index in the slot array in cdrom_slot_status(). This issue is similar to CVE-2018-16658 and CVE-2018-10940. Signed-off-by: Young_X <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool BrowserView::IsAlwaysOnTop() const { return false; } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead"); snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <[email protected]> Cc: Steffen Klassert <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: ImportSingleTIFF ( const TIFF_Manager::TagInfo & tagInfo, const bool nativeEndian, SXMPMeta * xmp, const char * xmpNS, const char * xmpProp ) { switch ( tagInfo.type ) { case kTIFF_ShortType : ImportSingleTIFF_Short ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; case kTIFF_LongType : ImportSingleTIFF_Long ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; case kTIFF_RationalType : ImportSingleTIFF_Rational ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; case kTIFF_SRationalType : ImportSingleTIFF_SRational ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; case kTIFF_ASCIIType : ImportSingleTIFF_ASCII ( tagInfo, xmp, xmpNS, xmpProp ); break; case kTIFF_ByteType : ImportSingleTIFF_Byte ( tagInfo, xmp, xmpNS, xmpProp ); break; case kTIFF_SByteType : ImportSingleTIFF_SByte ( tagInfo, xmp, xmpNS, xmpProp ); break; case kTIFF_SShortType : ImportSingleTIFF_SShort ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; case kTIFF_SLongType : ImportSingleTIFF_SLong ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; case kTIFF_FloatType : ImportSingleTIFF_Float ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; case kTIFF_DoubleType : ImportSingleTIFF_Double ( tagInfo, nativeEndian, xmp, xmpNS, xmpProp ); break; } } // ImportSingleTIFF Commit Message: CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void LauncherView::CalculateIdealBounds(IdealBounds* bounds) { int available_size = primary_axis_coordinate(width(), height()); if (!available_size) return; int x = primary_axis_coordinate(kLeadingInset, 0); int y = primary_axis_coordinate(0, kLeadingInset); for (int i = 0; i < view_model_->view_size(); ++i) { view_model_->set_ideal_bounds(i, gfx::Rect( x, y, kLauncherPreferredSize, kLauncherPreferredSize)); x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0); y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing); } if (view_model_->view_size() > 0) { view_model_->set_ideal_bounds(0, gfx::Rect(gfx::Size( primary_axis_coordinate(kLeadingInset + kLauncherPreferredSize, kLauncherPreferredSize), primary_axis_coordinate(kLauncherPreferredSize, kLeadingInset + kLauncherPreferredSize)))); } bounds->overflow_bounds.set_size( gfx::Size(kLauncherPreferredSize, kLauncherPreferredSize)); last_visible_index_ = DetermineLastVisibleIndex( available_size - kLeadingInset - kLauncherPreferredSize - kButtonSpacing - kLauncherPreferredSize); int app_list_index = view_model_->view_size() - 1; bool show_overflow = (last_visible_index_ + 1 < app_list_index); for (int i = 0; i < view_model_->view_size(); ++i) { view_model_->view_at(i)->SetVisible( i == app_list_index || i <= last_visible_index_); } overflow_button_->SetVisible(show_overflow); if (show_overflow) { DCHECK_NE(0, view_model_->view_size()); if (last_visible_index_ == -1) { x = primary_axis_coordinate(kLeadingInset, 0); y = primary_axis_coordinate(0, kLeadingInset); } else { x = primary_axis_coordinate( view_model_->ideal_bounds(last_visible_index_).right(), 0); y = primary_axis_coordinate(0, view_model_->ideal_bounds(last_visible_index_).bottom()); } gfx::Rect app_list_bounds = view_model_->ideal_bounds(app_list_index); app_list_bounds.set_x(x); app_list_bounds.set_y(y); view_model_->set_ideal_bounds(app_list_index, app_list_bounds); x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0); y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing); bounds->overflow_bounds.set_x(x); bounds->overflow_bounds.set_y(y); } } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ext4_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { handle_t *handle = ext4_journal_current_handle(); struct inode *inode = mapping->host; loff_t old_size = inode->i_size; int ret = 0, ret2; int i_size_changed = 0; trace_ext4_write_end(inode, pos, len, copied); if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) { ret = ext4_jbd2_file_inode(handle, inode); if (ret) { unlock_page(page); put_page(page); goto errout; } } if (ext4_has_inline_data(inode)) { ret = ext4_write_inline_data_end(inode, pos, len, copied, page); if (ret < 0) goto errout; copied = ret; } else copied = block_write_end(file, mapping, pos, len, copied, page, fsdata); /* * it's important to update i_size while still holding page lock: * page writeout could otherwise come in and zero beyond i_size. */ i_size_changed = ext4_update_inode_size(inode, pos + copied); unlock_page(page); put_page(page); if (old_size < pos) pagecache_isize_extended(inode, old_size, pos); /* * Don't mark the inode dirty under page lock. First, it unnecessarily * makes the holding time of page lock longer. Second, it forces lock * ordering of page lock and transaction start for journaling * filesystems. */ if (i_size_changed) ext4_mark_inode_dirty(handle, inode); if (pos + len > inode->i_size && ext4_can_truncate(inode)) /* if we have allocated more blocks and copied * less. We will have blocks allocated outside * inode->i_size. So truncate them */ ext4_orphan_add(handle, inode); errout: ret2 = ext4_journal_stop(handle); if (!ret) ret = ret2; if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be * on the orphan list; we need to make sure the inode * is removed from the orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } return ret ? ret : copied; } Commit Message: ext4: fix data exposure after a crash Huang has reported that in his powerfail testing he is seeing stale block contents in some of recently allocated blocks although he mounts ext4 in data=ordered mode. After some investigation I have found out that indeed when delayed allocation is used, we don't add inode to transaction's list of inodes needing flushing before commit. Originally we were doing that but commit f3b59291a69d removed the logic with a flawed argument that it is not needed. The problem is that although for delayed allocated blocks we write their contents immediately after allocating them, there is no guarantee that the IO scheduler or device doesn't reorder things and thus transaction allocating blocks and attaching them to inode can reach stable storage before actual block contents. Actually whenever we attach freshly allocated blocks to inode using a written extent, we should add inode to transaction's ordered inode list to make sure we properly wait for block contents to be written before committing the transaction. So that is what we do in this patch. This also handles other cases where stale data exposure was possible - like filling hole via mmap in data=ordered,nodelalloc mode. The only exception to the above rule are extending direct IO writes where blkdev_direct_IO() waits for IO to complete before increasing i_size and thus stale data exposure is not possible. For now we don't complicate the code with optimizing this special case since the overhead is pretty low. In case this is observed to be a performance problem we can always handle it using a special flag to ext4_map_blocks(). CC: [email protected] Fixes: f3b59291a69d0b734be1fc8be489fef2dd846d3d Reported-by: "HUANG Weller (CM/ESW12-CN)" <[email protected]> Tested-by: "HUANG Weller (CM/ESW12-CN)" <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static int mp_break_ctl(struct tty_struct *tty, int break_state) { struct sb_uart_state *state = tty->driver_data; struct sb_uart_port *port = state->port; MP_STATE_LOCK(state); if (port->type != PORT_UNKNOWN) port->ops->break_ctl(port, break_state); MP_STATE_UNLOCK(state); return 0; } Commit Message: Staging: sb105x: info leak in mp_get_count() The icount.reserved[] array isn't initialized so it leaks stack information to userspace. Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AuthenticatorBlePinEntrySheetModel::IsAcceptButtonEnabled() const { return true; } Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break. As requested by UX in [1], allow long host names to split a title into two lines. This allows us to show more of the name before eliding, although sufficiently long names will still trigger elision. Screenshot at https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r. [1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12 Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34 Bug: 870892 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812 Auto-Submit: Adam Langley <[email protected]> Commit-Queue: Nina Satragno <[email protected]> Reviewed-by: Nina Satragno <[email protected]> Cr-Commit-Position: refs/heads/master@{#658114} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: const char *cJSON_GetErrorPtr( void ) { return ep; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: int inet_csk_listen_start(struct sock *sk, const int nr_table_entries) { struct inet_sock *inet = inet_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int rc = reqsk_queue_alloc(&icsk->icsk_accept_queue, nr_table_entries); if (rc != 0) return rc; sk->sk_max_ack_backlog = 0; sk->sk_ack_backlog = 0; inet_csk_delack_init(sk); /* There is race window here: we announce ourselves listening, * but this transition is still not validated by get_port(). * It is OK, because this socket enters to hash table only * after validation is complete. */ sk->sk_state = TCP_LISTEN; if (!sk->sk_prot->get_port(sk, inet->inet_num)) { inet->inet_sport = htons(inet->inet_num); sk_dst_reset(sk); sk->sk_prot->hash(sk); return 0; } sk->sk_state = TCP_CLOSE; __reqsk_queue_destroy(&icsk->icsk_accept_queue); return -EADDRINUSE; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static long vbg_misc_device_ioctl(struct file *filp, unsigned int req, unsigned long arg) { struct vbg_session *session = filp->private_data; size_t returned_size, size; struct vbg_ioctl_hdr hdr; bool is_vmmdev_req; int ret = 0; void *buf; if (copy_from_user(&hdr, (void *)arg, sizeof(hdr))) return -EFAULT; if (hdr.version != VBG_IOCTL_HDR_VERSION) return -EINVAL; if (hdr.size_in < sizeof(hdr) || (hdr.size_out && hdr.size_out < sizeof(hdr))) return -EINVAL; size = max(hdr.size_in, hdr.size_out); if (_IOC_SIZE(req) && _IOC_SIZE(req) != size) return -EINVAL; if (size > SZ_16M) return -E2BIG; /* * IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid * the need for a bounce-buffer and another copy later on. */ is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) || req == VBG_IOCTL_VMMDEV_REQUEST_BIG; if (is_vmmdev_req) buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT); else buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; if (copy_from_user(buf, (void *)arg, hdr.size_in)) { ret = -EFAULT; goto out; } if (hdr.size_in < size) memset(buf + hdr.size_in, 0, size - hdr.size_in); ret = vbg_core_ioctl(session, req, buf); if (ret) goto out; returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out; if (returned_size > size) { vbg_debug("%s: too much output data %zu > %zu\n", __func__, returned_size, size); returned_size = size; } if (copy_to_user((void *)arg, buf, returned_size) != 0) ret = -EFAULT; out: if (is_vmmdev_req) vbg_req_free(buf, size); else kfree(buf); return ret; } Commit Message: virt: vbox: Only copy_from_user the request-header once In vbg_misc_device_ioctl(), the header of the ioctl argument is copied from the userspace pointer 'arg' and saved to the kernel object 'hdr'. Then the 'version', 'size_in', and 'size_out' fields of 'hdr' are verified. Before this commit, after the checks a buffer for the entire request would be allocated and then all data including the verified header would be copied from the userspace 'arg' pointer again. Given that the 'arg' pointer resides in userspace, a malicious userspace process can race to change the data pointed to by 'arg' between the two copies. By doing so, the user can bypass the verifications on the ioctl argument. This commit fixes this by using the already checked copy of the header to fill the header part of the allocated buffer and only copying the remainder of the data from userspace. Signed-off-by: Wenwen Wang <[email protected]> Reviewed-by: Hans de Goede <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE SoftAMR::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (mMode == MODE_NARROW) { if (strncmp((const char *)roleParams->cRole, "audio_decoder.amrnb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } else { if (strncmp((const char *)roleParams->cRole, "audio_decoder.amrwb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { const OMX_AUDIO_PARAM_AMRTYPE *aacParams = (const OMX_AUDIO_PARAM_AMRTYPE *)params; if (aacParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Target: 1 Example 2: Code: bool IsElementEditable(const WebInputElement& element) { return element.IsEnabled() && !element.IsReadOnly(); } Commit Message: [Android][TouchToFill] Use FindPasswordInfoForElement for triggering Use for TouchToFill the same triggering logic that is used for regular suggestions. Bug: 1010233 Change-Id: I111d4eac4ce94dd94b86097b6b6c98e08875e11a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1834230 Commit-Queue: Boris Sazonov <[email protected]> Reviewed-by: Vadym Doroshenko <[email protected]> Cr-Commit-Position: refs/heads/master@{#702058} CWE ID: CWE-125 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap) { RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context); ScriptPromise promise = resolver->promise(); resolver->resolve(imageBitmap); return promise; } Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas BUG=354356 Review URL: https://codereview.chromium.org/211313003 git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b) { return (b[0]<<8) | b[1]; } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682 Target: 1 Example 2: Code: RenderViewImpl* RenderViewImpl::Create( gfx::NativeViewId parent_hwnd, int32 opener_id, const content::RendererPreferences& renderer_prefs, const WebPreferences& webkit_prefs, SharedRenderViewCounter* counter, int32 routing_id, int32 surface_id, int64 session_storage_namespace_id, const string16& frame_name, int32 next_page_id, const WebKit::WebScreenInfo& screen_info) { DCHECK(routing_id != MSG_ROUTING_NONE); return new RenderViewImpl( parent_hwnd, opener_id, renderer_prefs, webkit_prefs, counter, routing_id, surface_id, session_storage_namespace_id, frame_name, next_page_id, screen_info); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void nfs4_delegreturn_done(struct rpc_task *task, void *calldata) { struct nfs4_delegreturndata *data = calldata; if (!nfs4_sequence_done(task, &data->res.seq_res)) return; trace_nfs4_delegreturn_exit(&data->args, &data->res, task->tk_status); switch (task->tk_status) { case 0: renew_lease(data->res.server, data->timestamp); case -NFS4ERR_ADMIN_REVOKED: case -NFS4ERR_DELEG_REVOKED: case -NFS4ERR_BAD_STATEID: case -NFS4ERR_OLD_STATEID: case -NFS4ERR_STALE_STATEID: case -NFS4ERR_EXPIRED: task->tk_status = 0; if (data->roc) pnfs_roc_set_barrier(data->inode, data->roc_barrier); break; default: if (nfs4_async_handle_error(task, data->res.server, NULL, NULL) == -EAGAIN) { rpc_restart_call_prepare(task); return; } } data->rpc_status = task->tk_status; } Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client ---Steps to Reproduce-- <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) <nfs-client> # mount -t nfs nfs-server:/nfs/ /mnt/ # ll /mnt/*/ <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) # service nfs restart <nfs-client> # ll /mnt/*/ --->>>>> oops here [ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null) [ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0 [ 5123.104131] Oops: 0000 [#1] [ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd] [ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214 [ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014 [ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000 [ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246 [ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240 [ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908 [ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000 [ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800 [ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240 [ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000 [ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0 [ 5123.112888] Stack: [ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000 [ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6 [ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800 [ 5123.115264] Call Trace: [ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4] [ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4] [ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4] [ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0 [ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70 [ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33 [ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.122308] RSP <ffff88005877fdb8> [ 5123.122942] CR2: 0000000000000000 Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops") Cc: [email protected] # v3.13+ Signed-off-by: Kinglong Mee <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE SoftVorbis::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioVorbis: { OMX_AUDIO_PARAM_VORBISTYPE *vorbisParams = (OMX_AUDIO_PARAM_VORBISTYPE *)params; if (vorbisParams->nPortIndex != 0) { return OMX_ErrorUndefined; } vorbisParams->nBitRate = 0; vorbisParams->nMinBitRate = 0; vorbisParams->nMaxBitRate = 0; vorbisParams->nAudioBandWidth = 0; vorbisParams->nQuality = 3; vorbisParams->bManaged = OMX_FALSE; vorbisParams->bDownmix = OMX_FALSE; if (!isConfigured()) { vorbisParams->nChannels = 1; vorbisParams->nSampleRate = 44100; } else { vorbisParams->nChannels = mVi->channels; vorbisParams->nSampleRate = mVi->rate; vorbisParams->nBitRate = mVi->bitrate_nominal; vorbisParams->nMinBitRate = mVi->bitrate_lower; vorbisParams->nMaxBitRate = mVi->bitrate_upper; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; if (!isConfigured()) { pcmParams->nChannels = 1; pcmParams->nSamplingRate = 44100; } else { pcmParams->nChannels = mVi->channels; pcmParams->nSamplingRate = mVi->rate; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Target: 1 Example 2: Code: fbFetchPixel_a1b5g5r5 (const FbBits *bits, int offset, miIndexedPtr indexed) { CARD32 pixel = READ((CARD16 *) bits + offset); CARD32 a,r,g,b; a = (CARD32) ((CARD8) (0 - ((pixel & 0x8000) >> 15))) << 24; b = ((pixel & 0x7c00) | ((pixel & 0x7000) >> 5)) >> 7; g = ((pixel & 0x03e0) | ((pixel & 0x0380) >> 5)) << 6; r = ((pixel & 0x001c) | ((pixel & 0x001f) << 5)) << 14; return (a | r | g | b); } Commit Message: CWE ID: CWE-189 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { return generic_fh_to_parent(sb, fid, fh_len, fh_type, ext4_nfs_get_inode); } Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info() Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by zero when trying to mount a corrupted file system") fixes CVE-2009-4307 by performing a sanity check on s_log_groups_per_flex, since it can be set to a bogus value by an attacker. sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { ... } This patch fixes two potential issues in the previous commit. 1) The sanity check might only work on architectures like PowerPC. On x86, 5 bits are used for the shifting amount. That means, given a large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36 is essentially 1 << 4 = 16, rather than 0. This will bypass the check, leaving s_log_groups_per_flex and groups_per_flex inconsistent. 2) The sanity check relies on undefined behavior, i.e., oversized shift. A standard-confirming C compiler could rewrite the check in unexpected ways. Consider the following equivalent form, assuming groups_per_flex is unsigned for simplicity. groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex == 0 || groups_per_flex == 1) { We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will completely optimize away the check groups_per_flex == 0, leaving the patched code as vulnerable as the original. GCC keeps the check, but there is no guarantee that future versions will do the same. Signed-off-by: Xi Wang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [email protected] CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowDCMException(exception,message) \ { \ if (info.scale != (Quantum *) NULL) \ info.scale=(Quantum *) RelinquishMagickMemory(info.scale); \ if (data != (unsigned char *) NULL) \ data=(unsigned char *) RelinquishMagickMemory(data); \ if (graymap != (int *) NULL) \ graymap=(int *) RelinquishMagickMemory(graymap); \ if (bluemap != (int *) NULL) \ bluemap=(int *) RelinquishMagickMemory(bluemap); \ if (greenmap != (int *) NULL) \ greenmap=(int *) RelinquishMagickMemory(greenmap); \ if (redmap != (int *) NULL) \ redmap=(int *) RelinquishMagickMemory(redmap); \ if (stream_info->offsets != (ssize_t *) NULL) \ stream_info->offsets=(ssize_t *) RelinquishMagickMemory( \ stream_info->offsets); \ if (stream_info != (DCMStreamInfo *) NULL) \ stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \ ThrowReaderException((exception),(message)); \ } char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMInfo info; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, *redmap; MagickBooleanType explicit_file, explicit_retry, use_explicit; MagickOffsetType offset; register unsigned char *p; register ssize_t i; size_t colors, height, length, number_scenes, quantum, status, width; ssize_t count, scene; unsigned char *data; unsigned short group, element; /* 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) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ (void) memset(&info,0,sizeof(info)); data=(unsigned char *) NULL; graymap=(int *) NULL; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent); info.bits_allocated=8; info.bytes_per_pixel=1; info.depth=8; info.mask=0xffff; info.max_value=255UL; info.samples_per_pixel=1; info.signed_data=(~0UL); info.rescale_slope=1.0; data=(unsigned char *) NULL; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; number_scenes=1; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; while (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { for (group=0; (group != 0x7FE0) || (element != 0x0010) ; ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group == 0xfffc) && (element == 0xfffc)) break; if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); /* Check for "explicitness", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,"OB",2) == 0) || (strncmp(explicit_vr,"UN",2) == 0) || (strncmp(explicit_vr,"OW",2) == 0) || (strncmp(explicit_vr,"SQ",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,"OW",2) == 0) || (strncmp(implicit_vr,"SS",2) == 0) || (strncmp(implicit_vr,"US",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,"FL",2) == 0) || (strncmp(implicit_vr,"OF",2) == 0) || (strncmp(implicit_vr,"SL",2) == 0) || (strncmp(implicit_vr,"UL",2) == 0)) quantum=4; else if (strncmp(implicit_vr,"FD",2) == 0) quantum=8; else quantum=1; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout," %s",dicom_info[i].description); (void) FormatLocaleFile(stdout,": "); } if ((group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"\n"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowDCMException(ResourceLimitError, "MemoryAllocationFailed"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"count=%d quantum=%d " "length=%d group=%d\n",(int) count,(int) quantum,(int) length,(int) group); ThrowDCMException(CorruptImageError, "InsufficientImageDataInFile"); } data[length*quantum]='\0'; } if ((((unsigned int) group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, "Corrupted image - trying explicit format\n"); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n", (const char *) transfer_syntax); if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0) { int subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=(ssize_t) sscanf(transfer_syntax+17,".%d.%d",&type, &subtype); if (count < 1) ThrowDCMException(CorruptImageError, "ImproperImageHeader"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ info.samples_per_pixel=(size_t) datum; if ((info.samples_per_pixel == 0) || (info.samples_per_pixel > 4)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ info.bits_allocated=(size_t) datum; info.bytes_per_pixel=1; if (datum > 8) info.bytes_per_pixel=2; info.depth=info.bits_allocated; if ((info.depth == 0) || (info.depth > 32)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.bits_allocated)-1; image->depth=info.depth; break; } case 0x0101: { /* Bits stored. */ info.significant_bits=(size_t) datum; info.bytes_per_pixel=1; if (info.significant_bits > 8) info.bytes_per_pixel=2; info.depth=info.significant_bits; if ((info.depth == 0) || (info.depth > 16)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); info.max_value=(1UL << info.significant_bits)-1; info.mask=(size_t) GetQuantumRange(info.significant_bits); image->depth=info.depth; break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ info.signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) info.window_center=StringToDouble((char *) data,(char **) NULL); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) info.window_width=StringToDouble((char *) data,(char **) NULL); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) info.rescale_intercept=StringToDouble((char *) data, (char **) NULL); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) info.rescale_slope=StringToDouble((char *) data,(char **) NULL); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/info.bytes_per_pixel); datum=(int) colors; if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); graymap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*graymap)); if (graymap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(graymap,0,MagickMax(colors,65536)* sizeof(*graymap)); for (i=0; i < (ssize_t) colors; i++) if (info.bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); redmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*redmap)); if (redmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(redmap,0,MagickMax(colors,65536)* sizeof(*redmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); greenmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(greenmap,0,MagickMax(colors,65536)* sizeof(*greenmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); bluemap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(bluemap,0,MagickMax(colors,65536)* sizeof(*bluemap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,"INVERSE",7) == 0)) info.polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString("dcm:"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute," ",""); (void) SetImageProperty(image,attribute,(char *) data, exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,"%d\n",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,"%d",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,"%c",data[i]); else (void) FormatLocaleFile(stdout,"%c",'.'); (void) FormatLocaleFile(stdout,"\n"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } if ((group == 0xfffc) && (element == 0xfffc)) { Image *last; last=RemoveLastImageFromList(&image); if (last != (Image *) NULL) last=DestroyImage(last); break; } if ((width == 0) || (height == 0)) ThrowDCMException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) width; image->rows=(size_t) height; if (info.signed_data == 0xffff) info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) if (ReadBlobByte(image) == EOF) break; (void) (((ssize_t) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image)); length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory( stream_info->offsets); stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) { read_info=DestroyImageInfo(read_info); ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, "UnableToCreateTemporaryFile",filename); break; } for (c=EOF; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } if (fputc(c,file) != c) break; } (void) fclose(file); if (c == EOF) break; (void) FormatLocaleString(read_info->filename,MagickPathExtent, "jpeg:%s",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, "j2k:%s",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); image=DestroyImageList(image); return(GetFirstImageInList(images)); } if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(info.depth)+1); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile"); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); info.scale=(Quantum *) AcquireQuantumMemory(MagickMax(length,256), sizeof(*info.scale)); if (info.scale == (Quantum *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(info.scale,0,MagickMax(length,256)* sizeof(*info.scale)); range=GetQuantumRange(info.depth); for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++) info.scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) { stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); if (EOFBlob(image) != MagickFalse) break; } offset=TellBlob(image)+8; for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { image->columns=(size_t) width; image->rows=(size_t) height; image->depth=info.depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; (void) SetImageBackgroundColor(image,exception); if ((image->colormap == (PixelInfo *) NULL) && (info.samples_per_pixel == 1)) { int index; size_t one; one=1; if (colors == 0) colors=one << info.depth; if (AcquireImageColormap(image,colors,exception) == MagickFalse) ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); ThrowDCMException(CorruptImageError,"ImproperImageHeader"); } stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; if (stream_info->segment_count > 1) { info.bytes_per_pixel=1; info.depth=8; if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[0],SEEK_SET); } } if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { register ssize_t x; register Quantum *q; ssize_t y; /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) info.samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } 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 { const char *option; /* Convert DCM Medical image to pixel packets. */ option=GetImageOption(image_info,"dcm:display-range"); if (option != (const char *) NULL) { if (LocaleCompare(option,"reset") == 0) info.window_width=0; } option=GetImageOption(image_info,"dcm:window"); if (option != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(option,&geometry_info); if (flags & RhoValue) info.window_center=geometry_info.rho; if (flags & SigmaValue) info.window_width=geometry_info.sigma; info.rescale=MagickTrue; } option=GetImageOption(image_info,"dcm:rescale"); if (option != (char *) NULL) info.rescale=IsStringTrue(option); if ((info.window_center != 0) && (info.window_width == 0)) info.window_width=info.window_center; status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception); if ((status != MagickFalse) && (stream_info->segment_count > 1)) { if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[1],SEEK_SET); (void) ReadDCMPixels(image,&info,stream_info,MagickFalse, exception); } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); 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; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } if (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); if (image == (Image *) NULL) return(image); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1269 CWE ID: CWE-20 Target: 1 Example 2: Code: static int ecp_double_add_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, mbedtls_ecp_point *S, const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q, const mbedtls_mpi *d ) { int ret; mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB; #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) if ( mbedtls_internal_ecp_grp_capable( grp ) ) { return mbedtls_internal_ecp_double_add_mxz( grp, R, S, P, Q, d ); } #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */ mbedtls_mpi_init( &A ); mbedtls_mpi_init( &AA ); mbedtls_mpi_init( &B ); mbedtls_mpi_init( &BB ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &C ); mbedtls_mpi_init( &D ); mbedtls_mpi_init( &DA ); mbedtls_mpi_init( &CB ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &A, &P->X, &P->Z ) ); MOD_ADD( A ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &AA, &A, &A ) ); MOD_MUL( AA ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &B, &P->X, &P->Z ) ); MOD_SUB( B ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &BB, &B, &B ) ); MOD_MUL( BB ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &E, &AA, &BB ) ); MOD_SUB( E ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &C, &Q->X, &Q->Z ) ); MOD_ADD( C ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &D, &Q->X, &Q->Z ) ); MOD_SUB( D ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DA, &D, &A ) ); MOD_MUL( DA ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &CB, &C, &B ) ); MOD_MUL( CB ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &S->X, &DA, &CB ) ); MOD_MUL( S->X ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->X, &S->X, &S->X ) ); MOD_MUL( S->X ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &S->Z, &DA, &CB ) ); MOD_SUB( S->Z ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->Z, &S->Z, &S->Z ) ); MOD_MUL( S->Z ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->Z, d, &S->Z ) ); MOD_MUL( S->Z ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->X, &AA, &BB ) ); MOD_MUL( R->X ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->Z, &grp->A, &E ) ); MOD_MUL( R->Z ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &R->Z, &BB, &R->Z ) ); MOD_ADD( R->Z ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->Z, &E, &R->Z ) ); MOD_MUL( R->Z ); cleanup: mbedtls_mpi_free( &A ); mbedtls_mpi_free( &AA ); mbedtls_mpi_free( &B ); mbedtls_mpi_free( &BB ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &C ); mbedtls_mpi_free( &D ); mbedtls_mpi_free( &DA ); mbedtls_mpi_free( &CB ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool blk_mq_has_free_tags(struct blk_mq_tags *tags) { if (!tags) return true; return bt_has_free_tags(&tags->bitmap_tags); } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(argc, argv) int argc; char *argv[]; { krb5_data pname_data, tkt_data; int sock = 0; socklen_t l; int retval; struct sockaddr_in l_inaddr, f_inaddr; /* local, foreign address */ krb5_creds creds, *new_creds; krb5_ccache cc; krb5_data msgtext, msg; krb5_context context; krb5_auth_context auth_context = NULL; #ifndef DEBUG freopen("/tmp/uu-server.log", "w", stderr); #endif retval = krb5_init_context(&context); if (retval) { com_err(argv[0], retval, "while initializing krb5"); exit(1); } #ifdef DEBUG { int one = 1; int acc; struct servent *sp; socklen_t namelen = sizeof(f_inaddr); if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { com_err("uu-server", errno, "creating socket"); exit(3); } l_inaddr.sin_family = AF_INET; l_inaddr.sin_addr.s_addr = 0; if (argc == 2) { l_inaddr.sin_port = htons(atoi(argv[1])); } else { if (!(sp = getservbyname("uu-sample", "tcp"))) { com_err("uu-server", 0, "can't find uu-sample/tcp service"); exit(3); } l_inaddr.sin_port = sp->s_port; } (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof (one)); if (bind(sock, (struct sockaddr *)&l_inaddr, sizeof(l_inaddr))) { com_err("uu-server", errno, "binding socket"); exit(3); } if (listen(sock, 1) == -1) { com_err("uu-server", errno, "listening"); exit(3); } printf("Server started\n"); fflush(stdout); if ((acc = accept(sock, (struct sockaddr *)&f_inaddr, &namelen)) == -1) { com_err("uu-server", errno, "accepting"); exit(3); } dup2(acc, 0); close(sock); sock = 0; } #endif retval = krb5_read_message(context, (krb5_pointer) &sock, &pname_data); if (retval) { com_err ("uu-server", retval, "reading pname"); return 2; } retval = krb5_read_message(context, (krb5_pointer) &sock, &tkt_data); if (retval) { com_err ("uu-server", retval, "reading ticket data"); return 2; } retval = krb5_cc_default(context, &cc); if (retval) { com_err("uu-server", retval, "getting credentials cache"); return 4; } memset (&creds, 0, sizeof(creds)); retval = krb5_cc_get_principal(context, cc, &creds.client); if (retval) { com_err("uu-client", retval, "getting principal name"); return 6; } /* client sends it already null-terminated. */ printf ("uu-server: client principal is \"%s\".\n", pname_data.data); retval = krb5_parse_name(context, pname_data.data, &creds.server); if (retval) { com_err("uu-server", retval, "parsing client name"); return 3; } creds.second_ticket = tkt_data; printf ("uu-server: client ticket is %d bytes.\n", creds.second_ticket.length); retval = krb5_get_credentials(context, KRB5_GC_USER_USER, cc, &creds, &new_creds); if (retval) { com_err("uu-server", retval, "getting user-user ticket"); return 5; } #ifndef DEBUG l = sizeof(f_inaddr); if (getpeername(0, (struct sockaddr *)&f_inaddr, &l) == -1) { com_err("uu-server", errno, "getting client address"); return 6; } #endif l = sizeof(l_inaddr); if (getsockname(0, (struct sockaddr *)&l_inaddr, &l) == -1) { com_err("uu-server", errno, "getting local address"); return 6; } /* send a ticket/authenticator to the other side, so it can get the key we're using for the krb_safe below. */ retval = krb5_auth_con_init(context, &auth_context); if (retval) { com_err("uu-server", retval, "making auth_context"); return 8; } retval = krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE); if (retval) { com_err("uu-server", retval, "initializing the auth_context flags"); return 8; } retval = krb5_auth_con_genaddrs(context, auth_context, sock, KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR | KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR); if (retval) { com_err("uu-server", retval, "generating addrs for auth_context"); return 9; } #if 1 retval = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SESSION_KEY, NULL, new_creds, &msg); if (retval) { com_err("uu-server", retval, "making AP_REQ"); return 8; } retval = krb5_write_message(context, (krb5_pointer) &sock, &msg); #else retval = krb5_sendauth(context, &auth_context, (krb5_pointer)&sock, "???", 0, 0, AP_OPTS_MUTUAL_REQUIRED | AP_OPTS_USE_SESSION_KEY, NULL, &creds, cc, NULL, NULL, NULL); #endif if (retval) goto cl_short_wrt; free(msg.data); msgtext.length = 32; msgtext.data = "Hello, other end of connection."; retval = krb5_mk_safe(context, auth_context, &msgtext, &msg, NULL); if (retval) { com_err("uu-server", retval, "encoding message to client"); return 6; } retval = krb5_write_message(context, (krb5_pointer) &sock, &msg); if (retval) { cl_short_wrt: com_err("uu-server", retval, "writing message to client"); return 7; } krb5_free_data_contents(context, &msg); krb5_free_data_contents(context, &pname_data); /* tkt_data freed with creds */ krb5_free_cred_contents(context, &creds); krb5_free_creds(context, new_creds); krb5_cc_close(context, cc); krb5_auth_con_free(context, auth_context); krb5_free_context(context); return 0; } Commit Message: Fix krb5_read_message handling [CVE-2014-5355] In recvauth_common, do not use strcmp against the data fields of krb5_data objects populated by krb5_read_message(), as there is no guarantee that they are C strings. Instead, create an expected krb5_data value and use data_eq(). In the sample user-to-user server application, check that the received client principal name is null-terminated before using it with printf and krb5_parse_name. CVE-2014-5355: In MIT krb5, when a server process uses the krb5_recvauth function, an unauthenticated remote attacker can cause a NULL dereference by sending a zero-byte version string, or a read beyond the end of allocated storage by sending a non-null-terminated version string. The example user-to-user server application (uuserver) is similarly vulnerable to a zero-length or non-null-terminated principal name string. The krb5_recvauth function reads two version strings from the client using krb5_read_message(), which produces a krb5_data structure containing a length and a pointer to an octet sequence. krb5_recvauth assumes that the data pointer is a valid C string and passes it to strcmp() to verify the versions. If the client sends an empty octet sequence, the data pointer will be NULL and strcmp() will dereference a NULL pointer, causing the process to crash. If the client sends a non-null-terminated octet sequence, strcmp() will read beyond the end of the allocated storage, possibly causing the process to crash. uuserver similarly uses krb5_read_message() to read a client principal name, and then passes it to printf() and krb5_parse_name() without verifying that it is a valid C string. The krb5_recvauth function is used by kpropd and the Kerberized versions of the BSD rlogin and rsh daemons. These daemons are usually run out of inetd or in a mode which forks before processing incoming connections, so a process crash will generally not result in a complete denial of service. Thanks to Tim Uglow for discovering this issue. CVSSv2: AV:N/AC:L/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C [[email protected]: CVSS score] ticket: 8050 (new) target_version: 1.13.1 tags: pullup CWE ID: Target: 1 Example 2: Code: static void floatMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValue(info, imp->floatMethod()); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vga_draw_graphic(VGACommonState *s, int full_update) { DisplaySurface *surface = qemu_console_surface(s->con); int y1, y, update, linesize, y_start, double_scan, mask, depth; int width, height, shift_control, line_offset, bwidth, bits; ram_addr_t page0, page1; DirtyBitmapSnapshot *snap = NULL; int disp_width, multi_scan, multi_run; uint8_t *d; uint32_t v, addr1, addr; vga_draw_line_func *vga_draw_line = NULL; bool share_surface; pixman_format_code_t format; #ifdef HOST_WORDS_BIGENDIAN bool byteswap = !s->big_endian_fb; #else bool byteswap = s->big_endian_fb; #endif full_update |= update_basic_params(s); s->get_resolution(s, &width, &height); disp_width = width; shift_control = (s->gr[VGA_GFX_MODE] >> 5) & 3; double_scan = (s->cr[VGA_CRTC_MAX_SCAN] >> 7); if (shift_control != 1) { multi_scan = (((s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1) << double_scan) - 1; } else { /* in CGA modes, multi_scan is ignored */ /* XXX: is it correct ? */ multi_scan = double_scan; } multi_run = multi_scan; if (shift_control != s->shift_control || double_scan != s->double_scan) { full_update = 1; s->shift_control = shift_control; s->double_scan = double_scan; } if (shift_control == 0) { if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { disp_width <<= 1; } } else if (shift_control == 1) { if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { disp_width <<= 1; } } depth = s->get_bpp(s); /* * Check whether we can share the surface with the backend * or whether we need a shadow surface. We share native * endian surfaces for 15bpp and above and byteswapped * surfaces for 24bpp and above. */ format = qemu_default_pixman_format(depth, !byteswap); if (format) { share_surface = dpy_gfx_check_format(s->con, format) && !s->force_shadow; } else { share_surface = false; } if (s->line_offset != s->last_line_offset || disp_width != s->last_width || height != s->last_height || s->last_depth != depth || s->last_byteswap != byteswap || share_surface != is_buffer_shared(surface)) { if (share_surface) { surface = qemu_create_displaysurface_from(disp_width, height, format, s->line_offset, s->vram_ptr + (s->start_addr * 4)); dpy_gfx_replace_surface(s->con, surface); } else { qemu_console_resize(s->con, disp_width, height); surface = qemu_console_surface(s->con); } s->last_scr_width = disp_width; s->last_scr_height = height; s->last_width = disp_width; s->last_height = height; s->last_line_offset = s->line_offset; s->last_depth = depth; s->last_byteswap = byteswap; full_update = 1; } else if (is_buffer_shared(surface) && (full_update || surface_data(surface) != s->vram_ptr + (s->start_addr * 4))) { pixman_format_code_t format = qemu_default_pixman_format(depth, !byteswap); surface = qemu_create_displaysurface_from(disp_width, height, format, s->line_offset, s->vram_ptr + (s->start_addr * 4)); dpy_gfx_replace_surface(s->con, surface); } if (shift_control == 0) { full_update |= update_palette16(s); if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { v = VGA_DRAW_LINE4D2; } else { v = VGA_DRAW_LINE4; } bits = 4; } else if (shift_control == 1) { full_update |= update_palette16(s); if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) { v = VGA_DRAW_LINE2D2; } else { v = VGA_DRAW_LINE2; } bits = 4; } else { switch(s->get_bpp(s)) { default: case 0: full_update |= update_palette256(s); v = VGA_DRAW_LINE8D2; bits = 4; break; case 8: full_update |= update_palette256(s); v = VGA_DRAW_LINE8; bits = 8; break; case 15: v = s->big_endian_fb ? VGA_DRAW_LINE15_BE : VGA_DRAW_LINE15_LE; bits = 16; break; case 16: v = s->big_endian_fb ? VGA_DRAW_LINE16_BE : VGA_DRAW_LINE16_LE; bits = 16; break; case 24: v = s->big_endian_fb ? VGA_DRAW_LINE24_BE : VGA_DRAW_LINE24_LE; bits = 24; break; case 32: v = s->big_endian_fb ? VGA_DRAW_LINE32_BE : VGA_DRAW_LINE32_LE; bits = 32; break; } } vga_draw_line = vga_draw_line_table[v]; if (!is_buffer_shared(surface) && s->cursor_invalidate) { s->cursor_invalidate(s); } line_offset = s->line_offset; #if 0 printf("w=%d h=%d v=%d line_offset=%d cr[0x09]=0x%02x cr[0x17]=0x%02x linecmp=%d sr[0x01]=0x%02x\n", width, height, v, line_offset, s->cr[9], s->cr[VGA_CRTC_MODE], s->line_compare, sr(s, VGA_SEQ_CLOCK_MODE)); #endif addr1 = (s->start_addr * 4); bwidth = (width * bits + 7) / 8; y_start = -1; d = surface_data(surface); linesize = surface_stride(surface); y1 = 0; if (!full_update) { vga_sync_dirty_bitmap(s); snap = memory_region_snapshot_and_clear_dirty(&s->vram, addr1, bwidth * height, DIRTY_MEMORY_VGA); } for(y = 0; y < height; y++) { addr = addr1; if (!(s->cr[VGA_CRTC_MODE] & 1)) { int shift; /* CGA compatibility handling */ shift = 14 + ((s->cr[VGA_CRTC_MODE] >> 6) & 1); addr = (addr & ~(1 << shift)) | ((y1 & 1) << shift); } if (!(s->cr[VGA_CRTC_MODE] & 2)) { addr = (addr & ~0x8000) | ((y1 & 2) << 14); } update = full_update; page0 = addr; page1 = addr + bwidth - 1; if (full_update) { update = 1; } else { update = memory_region_snapshot_get_dirty(&s->vram, snap, page0, page1 - page0); } /* explicit invalidation for the hardware cursor (cirrus only) */ update |= vga_scanline_invalidated(s, y); if (update) { if (y_start < 0) y_start = y; if (!(is_buffer_shared(surface))) { vga_draw_line(s, d, s->vram_ptr + addr, width); if (s->cursor_draw_line) s->cursor_draw_line(s, d, y); } } else { if (y_start >= 0) { /* flush to display */ dpy_gfx_update(s->con, 0, y_start, disp_width, y - y_start); y_start = -1; } } if (!multi_run) { mask = (s->cr[VGA_CRTC_MODE] & 3) ^ 3; if ((y1 & mask) == mask) addr1 += line_offset; y1++; multi_run = multi_scan; } else { multi_run--; } /* line compare acts on the displayed lines */ if (y == s->line_compare) addr1 = 0; d += linesize; } if (y_start >= 0) { /* flush to display */ dpy_gfx_update(s->con, 0, y_start, disp_width, y - y_start); } g_free(snap); memset(s->invalidated_y_table, 0, sizeof(s->invalidated_y_table)); } Commit Message: CWE ID: CWE-617 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || data_size < 8) { return ERROR_MALFORMED; } mSyncSampleOffset = data_offset; uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mNumSyncSamples = U32_AT(&header[4]); if (mNumSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } mSyncSamples = new uint32_t[mNumSyncSamples]; size_t size = mNumSyncSamples * sizeof(uint32_t); if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size) != (ssize_t)size) { return ERROR_IO; } for (size_t i = 0; i < mNumSyncSamples; ++i) { mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } return OK; } Commit Message: SampleTable: check integer overflow during table alloc Bug: 15328708 Bug: 15342615 Bug: 15342751 Change-Id: I6bb110a1eba46506799c73be8ff9a4f71c7e7053 CWE ID: CWE-189 Target: 1 Example 2: Code: static HeapVector<Member<Resource>> CachedResourcesForFrame(LocalFrame* frame, bool skip_xhrs) { HeapVector<Member<Resource>> result; Document* root_document = frame->GetDocument(); HeapVector<Member<Document>> loaders = InspectorPageAgent::ImportsForFrame(frame); CachedResourcesForDocument(root_document, result, skip_xhrs); for (size_t i = 0; i < loaders.size(); ++i) CachedResourcesForDocument(loaders[i], result, skip_xhrs); return result; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ssize_t read_and_process_frames(struct audio_stream_in *stream, void* buffer, ssize_t frames_num) { struct stream_in *in = (struct stream_in *)stream; ssize_t frames_wr = 0; /* Number of frames actually read */ size_t bytes_per_sample = audio_bytes_per_sample(stream->common.get_format(&stream->common)); void *proc_buf_out = buffer; #ifdef PREPROCESSING_ENABLED audio_buffer_t in_buf; audio_buffer_t out_buf; int i; bool has_processing = in->num_preprocessors != 0; #endif /* Additional channels might be added on top of main_channels: * - aux_channels (by processing effects) * - extra channels due to HW limitations * In case of additional channels, we cannot work inplace */ size_t src_channels = in->config.channels; size_t dst_channels = audio_channel_count_from_in_mask(in->main_channels); bool channel_remapping_needed = (dst_channels != src_channels); size_t src_buffer_size = frames_num * src_channels * bytes_per_sample; #ifdef PREPROCESSING_ENABLED if (has_processing) { /* since all the processing below is done in frames and using the config.channels * as the number of channels, no changes is required in case aux_channels are present */ while (frames_wr < frames_num) { /* first reload enough frames at the end of process input buffer */ if (in->proc_buf_frames < (size_t)frames_num) { ssize_t frames_rd; if (in->proc_buf_size < (size_t)frames_num) { in->proc_buf_size = (size_t)frames_num; in->proc_buf_in = realloc(in->proc_buf_in, src_buffer_size); ALOG_ASSERT((in->proc_buf_in != NULL), "process_frames() failed to reallocate proc_buf_in"); if (channel_remapping_needed) { in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size); ALOG_ASSERT((in->proc_buf_out != NULL), "process_frames() failed to reallocate proc_buf_out"); proc_buf_out = in->proc_buf_out; } } frames_rd = read_frames(in, in->proc_buf_in + in->proc_buf_frames * src_channels * bytes_per_sample, frames_num - in->proc_buf_frames); if (frames_rd < 0) { /* Return error code */ frames_wr = frames_rd; break; } in->proc_buf_frames += frames_rd; } /* in_buf.frameCount and out_buf.frameCount indicate respectively * the maximum number of frames to be consumed and produced by process() */ in_buf.frameCount = in->proc_buf_frames; in_buf.s16 = in->proc_buf_in; out_buf.frameCount = frames_num - frames_wr; out_buf.s16 = (int16_t *)proc_buf_out + frames_wr * in->config.channels; /* FIXME: this works because of current pre processing library implementation that * does the actual process only when the last enabled effect process is called. * The generic solution is to have an output buffer for each effect and pass it as * input to the next. */ for (i = 0; i < in->num_preprocessors; i++) { (*in->preprocessors[i].effect_itfe)->process(in->preprocessors[i].effect_itfe, &in_buf, &out_buf); } /* process() has updated the number of frames consumed and produced in * in_buf.frameCount and out_buf.frameCount respectively * move remaining frames to the beginning of in->proc_buf_in */ in->proc_buf_frames -= in_buf.frameCount; if (in->proc_buf_frames) { memcpy(in->proc_buf_in, in->proc_buf_in + in_buf.frameCount * src_channels * bytes_per_sample, in->proc_buf_frames * in->config.channels * audio_bytes_per_sample(in_get_format(in))); } /* if not enough frames were passed to process(), read more and retry. */ if (out_buf.frameCount == 0) { ALOGW("No frames produced by preproc"); continue; } if ((frames_wr + (ssize_t)out_buf.frameCount) <= frames_num) { frames_wr += out_buf.frameCount; } else { /* The effect does not comply to the API. In theory, we should never end up here! */ ALOGE("preprocessing produced too many frames: %d + %zd > %d !", (unsigned int)frames_wr, out_buf.frameCount, (unsigned int)frames_num); frames_wr = frames_num; } } } else #endif //PREPROCESSING_ENABLED { /* No processing effects attached */ if (channel_remapping_needed) { /* With additional channels, we cannot use original buffer */ if (in->proc_buf_size < src_buffer_size) { in->proc_buf_size = src_buffer_size; in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size); ALOG_ASSERT((in->proc_buf_out != NULL), "process_frames() failed to reallocate proc_buf_out"); } proc_buf_out = in->proc_buf_out; } frames_wr = read_frames(in, proc_buf_out, frames_num); ALOG_ASSERT(frames_wr <= frames_num, "read more frames than requested"); } if (channel_remapping_needed) { size_t ret = adjust_channels(proc_buf_out, src_channels, buffer, dst_channels, bytes_per_sample, frames_wr * src_channels * bytes_per_sample); ALOG_ASSERT(ret == (frames_wr * dst_channels * bytes_per_sample)); } return frames_wr; } Commit Message: Fix audio record pre-processing proc_buf_out consistently initialized. intermediate scratch buffers consistently initialized. prevent read failure from overwriting memory. Test: POC, CTS, camera record Bug: 62873231 Change-Id: Ie26e12a419a5819c1c5c3a0bcf1876d6d7aca686 (cherry picked from commit 6d7b330c27efba944817e647955da48e54fd74eb) CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadHALDImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; size_t cube_size, level; ssize_t y; /* Create HALD color lookup table image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); level=0; if (*image_info->filename != '\0') level=StringToUnsignedLong(image_info->filename); if (level < 2) level=8; status=MagickTrue; cube_size=level*level; image->columns=(size_t) (level*cube_size); image->rows=(size_t) (level*cube_size); for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) level) { ssize_t blue, green, red; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=QueueAuthenticPixels(image,0,y,image->columns,(size_t) level, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } blue=y/(ssize_t) level; for (green=0; green < (ssize_t) cube_size; green++) { for (red=0; red < (ssize_t) cube_size; red++) { SetPixelRed(q,ClampToQuantum((MagickRealType) (QuantumRange*red/(cube_size-1.0)))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (QuantumRange*green/(cube_size-1.0)))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (QuantumRange*blue/(cube_size-1.0)))); SetPixelOpacity(q,OpaqueOpacity); q++; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static noinline int balance_level(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, int level) { struct extent_buffer *right = NULL; struct extent_buffer *mid; struct extent_buffer *left = NULL; struct extent_buffer *parent = NULL; int ret = 0; int wret; int pslot; int orig_slot = path->slots[level]; u64 orig_ptr; if (level == 0) return 0; mid = path->nodes[level]; WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK && path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING); WARN_ON(btrfs_header_generation(mid) != trans->transid); orig_ptr = btrfs_node_blockptr(mid, orig_slot); if (level < BTRFS_MAX_LEVEL - 1) { parent = path->nodes[level + 1]; pslot = path->slots[level + 1]; } /* * deal with the case where there is only one pointer in the root * by promoting the node below to a root */ if (!parent) { struct extent_buffer *child; if (btrfs_header_nritems(mid) != 1) return 0; /* promote the child to a root */ child = read_node_slot(root, mid, 0); if (!child) { ret = -EROFS; btrfs_std_error(root->fs_info, ret); goto enospc; } btrfs_tree_lock(child); btrfs_set_lock_blocking(child); ret = btrfs_cow_block(trans, root, child, mid, 0, &child); if (ret) { btrfs_tree_unlock(child); free_extent_buffer(child); goto enospc; } tree_mod_log_set_root_pointer(root, child, 1); rcu_assign_pointer(root->node, child); add_root_to_dirty_list(root); btrfs_tree_unlock(child); path->locks[level] = 0; path->nodes[level] = NULL; clean_tree_block(trans, root, mid); btrfs_tree_unlock(mid); /* once for the path */ free_extent_buffer(mid); root_sub_used(root, mid->len); btrfs_free_tree_block(trans, root, mid, 0, 1); /* once for the root ptr */ free_extent_buffer_stale(mid); return 0; } if (btrfs_header_nritems(mid) > BTRFS_NODEPTRS_PER_BLOCK(root) / 4) return 0; left = read_node_slot(root, parent, pslot - 1); if (left) { btrfs_tree_lock(left); btrfs_set_lock_blocking(left); wret = btrfs_cow_block(trans, root, left, parent, pslot - 1, &left); if (wret) { ret = wret; goto enospc; } } right = read_node_slot(root, parent, pslot + 1); if (right) { btrfs_tree_lock(right); btrfs_set_lock_blocking(right); wret = btrfs_cow_block(trans, root, right, parent, pslot + 1, &right); if (wret) { ret = wret; goto enospc; } } /* first, try to make some room in the middle buffer */ if (left) { orig_slot += btrfs_header_nritems(left); wret = push_node_left(trans, root, left, mid, 1); if (wret < 0) ret = wret; } /* * then try to empty the right most buffer into the middle */ if (right) { wret = push_node_left(trans, root, mid, right, 1); if (wret < 0 && wret != -ENOSPC) ret = wret; if (btrfs_header_nritems(right) == 0) { clean_tree_block(trans, root, right); btrfs_tree_unlock(right); del_ptr(root, path, level + 1, pslot + 1); root_sub_used(root, right->len); btrfs_free_tree_block(trans, root, right, 0, 1); free_extent_buffer_stale(right); right = NULL; } else { struct btrfs_disk_key right_key; btrfs_node_key(right, &right_key, 0); tree_mod_log_set_node_key(root->fs_info, parent, pslot + 1, 0); btrfs_set_node_key(parent, &right_key, pslot + 1); btrfs_mark_buffer_dirty(parent); } } if (btrfs_header_nritems(mid) == 1) { /* * we're not allowed to leave a node with one item in the * tree during a delete. A deletion from lower in the tree * could try to delete the only pointer in this node. * So, pull some keys from the left. * There has to be a left pointer at this point because * otherwise we would have pulled some pointers from the * right */ if (!left) { ret = -EROFS; btrfs_std_error(root->fs_info, ret); goto enospc; } wret = balance_node_right(trans, root, mid, left); if (wret < 0) { ret = wret; goto enospc; } if (wret == 1) { wret = push_node_left(trans, root, left, mid, 1); if (wret < 0) ret = wret; } BUG_ON(wret == 1); } if (btrfs_header_nritems(mid) == 0) { clean_tree_block(trans, root, mid); btrfs_tree_unlock(mid); del_ptr(root, path, level + 1, pslot); root_sub_used(root, mid->len); btrfs_free_tree_block(trans, root, mid, 0, 1); free_extent_buffer_stale(mid); mid = NULL; } else { /* update the parent key to reflect our changes */ struct btrfs_disk_key mid_key; btrfs_node_key(mid, &mid_key, 0); tree_mod_log_set_node_key(root->fs_info, parent, pslot, 0); btrfs_set_node_key(parent, &mid_key, pslot); btrfs_mark_buffer_dirty(parent); } /* update the path */ if (left) { if (btrfs_header_nritems(left) > orig_slot) { extent_buffer_get(left); /* left was locked after cow */ path->nodes[level] = left; path->slots[level + 1] -= 1; path->slots[level] = orig_slot; if (mid) { btrfs_tree_unlock(mid); free_extent_buffer(mid); } } else { orig_slot -= btrfs_header_nritems(left); path->slots[level] = orig_slot; } } /* double check we haven't messed things up */ if (orig_ptr != btrfs_node_blockptr(path->nodes[level], path->slots[level])) BUG(); enospc: if (right) { btrfs_tree_unlock(right); free_extent_buffer(right); } if (left) { if (path->nodes[level] != left) btrfs_tree_unlock(left); free_extent_buffer(left); } return ret; } Commit Message: Btrfs: make xattr replace operations atomic Replacing a xattr consists of doing a lookup for its existing value, delete the current value from the respective leaf, release the search path and then finally insert the new value. This leaves a time window where readers (getxattr, listxattrs) won't see any value for the xattr. Xattrs are used to store ACLs, so this has security implications. This change also fixes 2 other existing issues which were: *) Deleting the old xattr value without verifying first if the new xattr will fit in the existing leaf item (in case multiple xattrs are packed in the same item due to name hash collision); *) Returning -EEXIST when the flag XATTR_CREATE is given and the xattr doesn't exist but we have have an existing item that packs muliple xattrs with the same name hash as the input xattr. In this case we should return ENOSPC. A test case for xfstests follows soon. Thanks to Alexandre Oliva for reporting the non-atomicity of the xattr replace implementation. Reported-by: Alexandre Oliva <[email protected]> Signed-off-by: Filipe Manana <[email protected]> Signed-off-by: Chris Mason <[email protected]> CWE ID: CWE-362 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void LayoutBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge) { LayoutBlock::computeOverflow(oldClientAfterEdge); addOverflowFromFloats(); } Commit Message: Consistently check if a block can handle pagination strut propagation. https://codereview.chromium.org/1360753002 got it right for inline child layout, but did nothing for block child layout. BUG=329421 [email protected],[email protected] Review URL: https://codereview.chromium.org/1387553002 Cr-Commit-Position: refs/heads/master@{#352429} CWE ID: CWE-22 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/131 CWE ID: CWE-125 Target: 1 Example 2: Code: struct fuse_req *fuse_get_req_for_background(struct fuse_conn *fc, unsigned npages) { return __fuse_get_req(fc, npages, true); } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xfs_set_mode(struct inode *inode, umode_t mode) { int error = 0; if (mode != inode->i_mode) { struct iattr iattr; iattr.ia_valid = ATTR_MODE | ATTR_CTIME; iattr.ia_mode = mode; iattr.ia_ctime = current_fs_time(inode->i_sb); error = xfs_setattr_nonsize(XFS_I(inode), &iattr, XFS_ATTR_NOACL); } return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void uverbs_user_mmap_disassociate(struct ib_uverbs_file *ufile) { struct rdma_umap_priv *priv, *next_priv; lockdep_assert_held(&ufile->hw_destroy_rwsem); while (1) { struct mm_struct *mm = NULL; /* Get an arbitrary mm pointer that hasn't been cleaned yet */ mutex_lock(&ufile->umap_lock); while (!list_empty(&ufile->umaps)) { int ret; priv = list_first_entry(&ufile->umaps, struct rdma_umap_priv, list); mm = priv->vma->vm_mm; ret = mmget_not_zero(mm); if (!ret) { list_del_init(&priv->list); mm = NULL; continue; } break; } mutex_unlock(&ufile->umap_lock); if (!mm) return; /* * The umap_lock is nested under mmap_sem since it used within * the vma_ops callbacks, so we have to clean the list one mm * at a time to get the lock ordering right. Typically there * will only be one mm, so no big deal. */ down_write(&mm->mmap_sem); mutex_lock(&ufile->umap_lock); list_for_each_entry_safe (priv, next_priv, &ufile->umaps, list) { struct vm_area_struct *vma = priv->vma; if (vma->vm_mm != mm) continue; list_del_init(&priv->list); zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start); vma->vm_flags &= ~(VM_SHARED | VM_MAYSHARE); } mutex_unlock(&ufile->umap_lock); up_write(&mm->mmap_sem); mmput(mm); } } Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: void RenderFrameHostImpl::OnUpdateToUniqueOrigin( bool is_potentially_trustworthy_unique_origin) { url::Origin origin; DCHECK(origin.unique()); frame_tree_node()->SetCurrentOrigin(origin, is_potentially_trustworthy_unique_origin); } 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 <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: views::ImageButton* close_button() const { return media_controls_view_->close_button_; } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FindBarController::Show() { FindManager* find_manager = tab_contents_->GetFindManager(); if (!find_manager->find_ui_active()) { MaybeSetPrepopulateText(); find_manager->set_find_ui_active(true); find_bar_->Show(true); } find_bar_->SetFocusAndSelection(); } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: int sm_restore_priority(p_fm_config_conx_hdlt hdl, fm_mgr_type_t mgr, int argc, char *argv[]) { fm_mgr_config_errno_t res; fm_msg_ret_code_t ret_code; if((res = fm_mgr_simple_query(hdl, FM_ACT_GET, FM_DT_SM_RESTORE_PRIORITY, mgr, 0, NULL, &ret_code)) != FM_CONF_OK) { fprintf(stderr, "sm_restore_priority: Failed to retrieve data: \n" "\tError:(%d) %s \n\tRet code:(%d) %s\n", res, fm_mgr_get_error_str(res),ret_code, fm_mgr_get_resp_error_str(ret_code)); } else { printf("sm_restore_priority: Successfully sent Relinquish Master control to local mgr instance\n"); } return 0; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) { const char *textStart, *textEnd; const char *next; enum XML_Error result; OPEN_INTERNAL_ENTITY *openEntity; if (parser->m_freeInternalEntities) { openEntity = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity->next; } else { openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY)); if (! openEntity) return XML_ERROR_NO_MEMORY; } entity->open = XML_TRUE; entity->processed = 0; openEntity->next = parser->m_openInternalEntities; parser->m_openInternalEntities = openEntity; openEntity->entity = entity; openEntity->startTagLevel = parser->m_tagLevel; openEntity->betweenDecl = betweenDecl; openEntity->internalEventPtr = NULL; openEntity->internalEventEndPtr = NULL; textStart = (char *)entity->textPtr; textEnd = (char *)(entity->textPtr + entity->textLen); /* Set a safe default value in case 'next' does not get set */ next = textStart; #ifdef XML_DTD if (entity->is_param) { int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, next, &next, XML_FALSE); } else #endif /* XML_DTD */ result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart, textEnd, &next, XML_FALSE); if (result == XML_ERROR_NONE) { if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { entity->processed = (int)(next - textStart); parser->m_processor = internalEntityProcessor; } else { entity->open = XML_FALSE; parser->m_openInternalEntities = openEntity->next; /* put openEntity back in list of free instances */ openEntity->next = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity; } } return result; } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate( TabContents* tab_contents, const string16& utf16_name) : PluginInfoBarDelegate(tab_contents, utf16_name) { UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown")); std::string name = UTF16ToUTF8(utf16_name); if (name == webkit::npapi::PluginGroup::kJavaGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Java")); else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime")); else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave")); else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer")); } Commit Message: Infobar Windows Media Player plug-in by default. BUG=51464 Review URL: http://codereview.chromium.org/7080048 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87500 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid) { struct smb_rqst rqst; struct smb2_flush_req *req; struct cifs_ses *ses = tcon->ses; struct kvec iov[1]; struct kvec rsp_iov; int resp_buftype; int rc = 0; int flags = 0; unsigned int total_len; cifs_dbg(FYI, "Flush\n"); if (!ses || !(ses->server)) return -EIO; rc = smb2_plain_req_init(SMB2_FLUSH, tcon, (void **) &req, &total_len); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; req->PersistentFileId = persistent_fid; req->VolatileFileId = volatile_fid; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); if (rc != 0) { cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE); trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid, rc); } free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } Commit Message: cifs: Fix use-after-free in SMB2_read There is a KASAN use-after-free: BUG: KASAN: use-after-free in SMB2_read+0x1136/0x1190 Read of size 8 at addr ffff8880b4e45e50 by task ln/1009 Should not release the 'req' because it will use in the trace. Fixes: eccb4422cf97 ("smb3: Add ftrace tracepoints for improved SMB3 debugging") Signed-off-by: ZhangXiaoxu <[email protected]> Signed-off-by: Steve French <[email protected]> CC: Stable <[email protected]> 4.18+ Reviewed-by: Pavel Shilovsky <[email protected]> CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long ParseElementHeader(IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; long len; id = ReadID(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0 || len < 1 || len > 8) { return E_FILE_FORMAT_INVALID; } const unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; return 0; // success } Commit Message: Fix ParseElementHeader to support 0 payload elements Cherry-pick'ing Change 5c83bbec9a5f6f00a349674ddad85b753d2ea219 from upstream. This fixes regression in some edge cases for mkv playback. BUG=26499283 Change-Id: I88de03219a3d941b6b2f251d384e29c36bdd4d9b CWE ID: CWE-20 Target: 1 Example 2: Code: static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc) { u32 reg; dwc->connected = true; /* * WORKAROUND: DWC3 revisions <1.88a have an issue which * would cause a missing Disconnect Event if there's a * pending Setup Packet in the FIFO. * * There's no suggested workaround on the official Bug * report, which states that "unless the driver/application * is doing any special handling of a disconnect event, * there is no functional issue". * * Unfortunately, it turns out that we _do_ some special * handling of a disconnect event, namely complete all * pending transfers, notify gadget driver of the * disconnection, and so on. * * Our suggested workaround is to follow the Disconnect * Event steps here, instead, based on a setup_packet_pending * flag. Such flag gets set whenever we have a SETUP_PENDING * status for EP0 TRBs and gets cleared on XferComplete for the * same endpoint. * * Refers to: * * STAR#9000466709: RTL: Device : Disconnect event not * generated if setup packet pending in FIFO */ if (dwc->revision < DWC3_REVISION_188A) { if (dwc->setup_packet_pending) dwc3_gadget_disconnect_interrupt(dwc); } dwc3_reset_gadget(dwc); reg = dwc3_readl(dwc->regs, DWC3_DCTL); reg &= ~DWC3_DCTL_TSTCTRL_MASK; dwc3_writel(dwc->regs, DWC3_DCTL, reg); dwc->test_mode = false; dwc3_clear_stall_all_ep(dwc); /* Reset device address to zero */ reg = dwc3_readl(dwc->regs, DWC3_DCFG); reg &= ~(DWC3_DCFG_DEVADDR_MASK); dwc3_writel(dwc->regs, DWC3_DCFG, reg); } Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue() This is a requirement which has always existed but, somehow, wasn't reflected in the documentation and problems weren't found until now when Tuba Yavuz found a possible deadlock happening between dwc3 and f_hid. She described the situation as follows: spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire /* we our function has been disabled by host */ if (!hidg->req) { free_ep_req(hidg->in_ep, hidg->req); goto try_again; } [...] status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC); => [...] => usb_gadget_giveback_request => f_hidg_req_complete => spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire Note that this happens because dwc3 would call ->complete() on a failed usb_ep_queue() due to failed Start Transfer command. This is, anyway, a theoretical situation because dwc3 currently uses "No Response Update Transfer" command for Bulk and Interrupt endpoints. It's still good to make this case impossible to happen even if the "No Reponse Update Transfer" command is changed. Reported-by: Tuba Yavuz <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-189 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void vring_used_ring_id(VirtQueue *vq, int i, uint32_t val) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, ring[i].id); stl_phys(&address_space_memory, pa, val); } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SplashOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { GfxImageColorMap *maskColorMap; Object maskDecode, decodeLow, decodeHigh; double *ctm; SplashCoord mat[6]; SplashOutMaskedImageData imgData; SplashOutImageMaskData imgMaskData; SplashColorMode srcMode; SplashBitmap *maskBitmap; Splash *maskSplash; SplashColor maskColor; GfxGray gray; GfxRGB rgb; #if SPLASH_CMYK GfxCMYK cmyk; #endif Guchar pix; int n, i; if (maskWidth > width || maskHeight > height) { decodeLow.initInt(maskInvert ? 0 : 1); decodeHigh.initInt(maskInvert ? 1 : 0); maskDecode.initArray(xref); maskDecode.arrayAdd(&decodeLow); maskDecode.arrayAdd(&decodeHigh); maskColorMap = new GfxImageColorMap(1, &maskDecode, new GfxDeviceGrayColorSpace()); maskDecode.free(); drawSoftMaskedImage(state, ref, str, width, height, colorMap, maskStr, maskWidth, maskHeight, maskColorMap); delete maskColorMap; } else { mat[0] = (SplashCoord)width; mat[1] = 0; mat[2] = 0; mat[3] = (SplashCoord)height; mat[4] = 0; mat[5] = 0; imgMaskData.imgStr = new ImageStream(maskStr, maskWidth, 1, 1); imgMaskData.imgStr->reset(); imgMaskData.invert = maskInvert ? 0 : 1; imgMaskData.width = maskWidth; imgMaskData.height = maskHeight; imgMaskData.y = 0; maskBitmap = new SplashBitmap(width, height, 1, splashModeMono1, gFalse); maskSplash = new Splash(maskBitmap, gFalse); maskColor[0] = 0; maskSplash->clear(maskColor); maskColor[0] = 0xff; maskSplash->setFillPattern(new SplashSolidColor(maskColor)); maskSplash->fillImageMask(&imageMaskSrc, &imgMaskData, maskWidth, maskHeight, mat, gFalse); delete imgMaskData.imgStr; maskStr->close(); delete maskSplash; ctm = state->getCTM(); mat[0] = ctm[0]; mat[1] = ctm[1]; mat[2] = -ctm[2]; mat[3] = -ctm[3]; mat[4] = ctm[2] + ctm[4]; mat[5] = ctm[3] + ctm[5]; imgData.imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgData.imgStr->reset(); imgData.colorMap = colorMap; imgData.mask = maskBitmap; imgData.colorMode = colorMode; imgData.width = width; imgData.height = height; imgData.y = 0; imgData.lookup = NULL; if (colorMap->getNumPixelComps() == 1) { n = 1 << colorMap->getBits(); switch (colorMode) { case splashModeMono1: case splashModeMono8: imgData.lookup = (SplashColorPtr)gmalloc(n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getGray(&pix, &gray); imgData.lookup[i] = colToByte(gray); } break; case splashModeRGB8: case splashModeBGR8: imgData.lookup = (SplashColorPtr)gmalloc(3 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[3*i] = colToByte(rgb.r); imgData.lookup[3*i+1] = colToByte(rgb.g); imgData.lookup[3*i+2] = colToByte(rgb.b); } break; case splashModeXBGR8: imgData.lookup = (SplashColorPtr)gmalloc(4 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[4*i] = colToByte(rgb.r); imgData.lookup[4*i+1] = colToByte(rgb.g); imgData.lookup[4*i+2] = colToByte(rgb.b); imgData.lookup[4*i+3] = 255; } break; #if SPLASH_CMYK case splashModeCMYK8: imgData.lookup = (SplashColorPtr)gmalloc(4 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getCMYK(&pix, &cmyk); imgData.lookup[4*i] = colToByte(cmyk.c); imgData.lookup[4*i+1] = colToByte(cmyk.m); imgData.lookup[4*i+2] = colToByte(cmyk.y); imgData.lookup[4*i+3] = colToByte(cmyk.k); } break; #endif } } if (colorMode == splashModeMono1) { srcMode = splashModeMono8; } else { srcMode = colorMode; } splash->drawImage(&maskedImageSrc, &imgData, srcMode, gTrue, width, height, mat); delete maskBitmap; gfree(imgData.lookup); delete imgData.imgStr; str->close(); } } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: void Browser::SaveWindowPlacement(const gfx::Rect& bounds, bool maximized) { if (profile()->HasSessionService()) { SessionService* session_service = profile()->GetSessionService(); if (session_service) session_service->SetWindowBounds(session_id_, bounds, maximized); } } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void chain_reply(struct smb_request *req) { size_t smblen = smb_len(req->inbuf); size_t already_used, length_needed; uint8_t chain_cmd; uint32_t chain_offset; /* uint32_t to avoid overflow */ uint8_t wct; uint16_t *vwv; uint16_t buflen; uint8_t *buf; if (IVAL(req->outbuf, smb_rcls) != 0) { fixup_chain_error_packet(req); } /* * Any of the AndX requests and replies have at least a wct of * 2. vwv[0] is the next command, vwv[1] is the offset from the * beginning of the SMB header to the next wct field. * * None of the AndX requests put anything valuable in vwv[0] and [1], * so we can overwrite it here to form the chain. */ if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) { goto error; } if (req->chain_outbuf == NULL) { /* * In req->chain_outbuf we collect all the replies. Start the * chain by copying in the first reply. * * We do the realloc because later on we depend on * talloc_get_size to determine the length of * chain_outbuf. The reply_xxx routines might have * over-allocated (reply_pipe_read_and_X used to be such an * example). */ req->chain_outbuf = TALLOC_REALLOC_ARRAY( req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4); if (req->chain_outbuf == NULL) { goto error; } req->outbuf = NULL; } else { /* * Update smb headers where subsequent chained commands req->chain_outbuf = TALLOC_REALLOC_ARRAY( req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4); if (req->chain_outbuf == NULL) { goto error; } req->outbuf = NULL; } else { CVAL(req->outbuf, smb_wct), (uint16_t *)(req->outbuf + smb_vwv), 0, smb_buflen(req->outbuf), (uint8_t *)smb_buf(req->outbuf))) { goto error; } TALLOC_FREE(req->outbuf); } /* * We use the old request's vwv field to grab the next chained command * and offset into the chained fields. */ chain_cmd = CVAL(req->vwv+0, 0); chain_offset = SVAL(req->vwv+1, 0); if (chain_cmd == 0xff) { /* * End of chain, no more requests from the client. So ship the * replies. */ smb_setlen((char *)(req->chain_outbuf), talloc_get_size(req->chain_outbuf) - 4); if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf, true, req->seqnum+1, IS_CONN_ENCRYPTED(req->conn) ||req->encrypted, &req->pcd)) { exit_server_cleanly("chain_reply: srv_send_smb " "failed."); } TALLOC_FREE(req->chain_outbuf); req->done = true; return; } /* add a new perfcounter for this element of chain */ SMB_PERFCOUNT_ADD(&req->pcd); SMB_PERFCOUNT_SET_OP(&req->pcd, chain_cmd); SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, smblen); /* * Check if the client tries to fool us. The request so far uses the * space to the end of the byte buffer in the request just * processed. The chain_offset can't point into that area. If that was * the case, we could end up with an endless processing of the chain, * we would always handle the same request. */ already_used = PTR_DIFF(req->buf+req->buflen, smb_base(req->inbuf)); if (chain_offset < already_used) { goto error; } /* * Next check: Make sure the chain offset does not point beyond the * overall smb request length. */ length_needed = chain_offset+1; /* wct */ if (length_needed > smblen) { goto error; } /* * Now comes the pointer magic. Goal here is to set up req->vwv and * req->buf correctly again to be able to call the subsequent * switch_message(). The chain offset (the former vwv[1]) points at * the new wct field. */ wct = CVAL(smb_base(req->inbuf), chain_offset); /* * Next consistency check: Make the new vwv array fits in the overall * smb request. */ length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */ if (length_needed > smblen) { goto error; } vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1); /* * Now grab the new byte buffer.... */ buflen = SVAL(vwv+wct, 0); /* * .. and check that it fits. */ length_needed += buflen; if (length_needed > smblen) { goto error; } buf = (uint8_t *)(vwv+wct+1); req->cmd = chain_cmd; req->wct = wct; req->vwv = vwv; req->buflen = buflen; req->buf = buf; switch_message(chain_cmd, req, smblen); if (req->outbuf == NULL) { /* * This happens if the chained command has suspended itself or * if it has called srv_send_smb() itself. */ return; } /* * We end up here if the chained command was not itself chained or * suspended, but for example a close() command. We now need to splice * the chained commands' outbuf into the already built up chain_outbuf * and ship the result. */ goto done; error: /* * We end up here if there's any error in the chain syntax. Report a * DOS error, just like Windows does. */ reply_force_doserror(req, ERRSRV, ERRerror); fixup_chain_error_packet(req); done: /* * This scary statement intends to set the * FLAGS2_32_BIT_ERROR_CODES flg2 field in req->chain_outbuf * to the value req->outbuf carries */ SSVAL(req->chain_outbuf, smb_flg2, (SVAL(req->chain_outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES) | (SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES)); /* * Transfer the error codes from the subrequest to the main one */ SSVAL(req->chain_outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls)); SSVAL(req->chain_outbuf, smb_err, SVAL(req->outbuf, smb_err)); if (!smb_splice_chain(&req->chain_outbuf, CVAL(req->outbuf, smb_com), CVAL(req->outbuf, smb_wct), (uint16_t *)(req->outbuf + smb_vwv), 0, smb_buflen(req->outbuf), (uint8_t *)smb_buf(req->outbuf))) { exit_server_cleanly("chain_reply: smb_splice_chain failed\n"); } TALLOC_FREE(req->outbuf); smb_setlen((char *)(req->chain_outbuf), talloc_get_size(req->chain_outbuf) - 4); show_msg((char *)(req->chain_outbuf)); if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf, true, req->seqnum+1, IS_CONN_ENCRYPTED(req->conn)||req->encrypted, &req->pcd)) { exit_server_cleanly("construct_reply: srv_send_smb failed."); } TALLOC_FREE(req->chain_outbuf); req->done = true; } Commit Message: CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __btrfs_set_acl(struct btrfs_trans_handle *trans, struct inode *inode, struct posix_acl *acl, int type) { int ret, size = 0; const char *name; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { ret = posix_acl_equiv_mode(acl, &inode->i_mode); if (ret < 0) return ret; if (ret == 0) acl = NULL; } ret = 0; break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) return acl ? -EINVAL : 0; name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) { ret = -ENOMEM; goto out; } ret = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (ret < 0) goto out; } ret = __btrfs_setxattr(trans, inode, name, value, size, 0); out: kfree(value); if (!ret) set_cached_acl(inode, type, acl); return ret; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285 Target: 1 Example 2: Code: void jas_matrix_divpow2(jas_matrix_t *matrix, int n) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { *data = (*data >= 0) ? ((*data) >> n) : (-((-(*data)) >> n)); } } } } Commit Message: Fixed an integer overflow problem. CWE ID: CWE-190 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Check verify-data in constant-time. The length OTOH is no secret */ if( len != 1 + ssl->verify_data_len || buf[0] != ssl->verify_data_len || mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data, ssl->verify_data_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { if( len != 1 || buf[0] != 0x0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; } return( 0 ); } Commit Message: Prevent bounds check bypass through overflow in PSK identity parsing The check `if( *p + n > end )` in `ssl_parse_client_psk_identity` is unsafe because `*p + n` might overflow, thus bypassing the check. As `n` is a user-specified value up to 65K, this is relevant if the library happens to be located in the last 65K of virtual memory. This commit replaces the check by a safe version. CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DOMWindow* CreateWindow(const String& url_string, const AtomicString& frame_name, const String& window_features_string, LocalDOMWindow& calling_window, LocalFrame& first_frame, LocalFrame& opener_frame, ExceptionState& exception_state) { LocalFrame* active_frame = calling_window.GetFrame(); DCHECK(active_frame); KURL completed_url = url_string.IsEmpty() ? KURL(kParsedURLString, g_empty_string) : first_frame.GetDocument()->CompleteURL(url_string); if (!completed_url.IsEmpty() && !completed_url.IsValid()) { UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL); exception_state.ThrowDOMException( kSyntaxError, "Unable to open a window with invalid URL '" + completed_url.GetString() + "'.\n"); return nullptr; } WebWindowFeatures window_features = GetWindowFeaturesFromString(window_features_string); FrameLoadRequest frame_request(calling_window.document(), ResourceRequest(completed_url), frame_name); frame_request.SetShouldSetOpener(window_features.noopener ? kNeverSetOpener : kMaybeSetOpener); frame_request.GetResourceRequest().SetFrameType( WebURLRequest::kFrameTypeAuxiliary); frame_request.GetResourceRequest().SetRequestorOrigin( SecurityOrigin::Create(active_frame->GetDocument()->Url())); frame_request.GetResourceRequest().SetHTTPReferrer( SecurityPolicy::GenerateReferrer( active_frame->GetDocument()->GetReferrerPolicy(), completed_url, active_frame->GetDocument()->OutgoingReferrer())); bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture(); bool created; Frame* new_frame = CreateWindowHelper( opener_frame, *active_frame, opener_frame, frame_request, window_features, kNavigationPolicyIgnore, created); if (!new_frame) return nullptr; if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window, completed_url)) return window_features.noopener ? nullptr : new_frame->DomWindow(); if (created) { FrameLoadRequest request(calling_window.document(), ResourceRequest(completed_url)); request.GetResourceRequest().SetHasUserGesture(has_user_gesture); new_frame->Navigate(request); } else if (!url_string.IsEmpty()) { new_frame->Navigate(*calling_window.document(), completed_url, false, has_user_gesture ? UserGestureStatus::kActive : UserGestureStatus::kNone); } return window_features.noopener ? nullptr : new_frame->DomWindow(); } Commit Message: CSP now prevents opening javascript url windows when they're not allowed spec: https://html.spec.whatwg.org/#navigate which leads to: https://w3c.github.io/webappsec-csp/#should-block-navigation-request Bug: 756040 Change-Id: I5fd62ebfb6fe1d767694b0ed6cf427c8ea95994a Reviewed-on: https://chromium-review.googlesource.com/632580 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#497338} CWE ID: Target: 1 Example 2: Code: void ServiceWorkerDevToolsAgentHost::DetachSession(DevToolsSession* session) { if (state_ == WORKER_READY && sessions().empty()) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, false)); } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { return image_transform_png_set_expand_add(this, that, colour_type, bit_depth); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DataReductionProxyConfig::InitializeOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, WarmupURLFetcher::CreateCustomProxyConfigCallback create_custom_proxy_config_callback, NetworkPropertiesManager* manager) { DCHECK(thread_checker_.CalledOnValidThread()); network_properties_manager_ = manager; network_properties_manager_->ResetWarmupURLFetchMetrics(); secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory)); warmup_url_fetcher_.reset(new WarmupURLFetcher( url_loader_factory, create_custom_proxy_config_callback, base::BindRepeating( &DataReductionProxyConfig::HandleWarmupFetcherResponse, base::Unretained(this)), base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate, base::Unretained(this)), ui_task_runner_)); if (ShouldAddDefaultProxyBypassRules()) AddDefaultProxyBypassRules(); network_connection_tracker_->AddNetworkConnectionObserver(this); network_connection_tracker_->GetConnectionType( &connection_type_, base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged, weak_factory_.GetWeakPtr())); } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20 Target: 1 Example 2: Code: static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { } 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 <[email protected]> Reported-by: Bjoern B. Brandenburg <[email protected]> Tested-by: Yong Zhang <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: [email protected] LKML-Reference: <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool BrowserView::CanTriggerOnMouse() const { return !IsImmersiveModeEnabled(); } Commit Message: Mac: turn popups into new tabs while in fullscreen. It's platform convention to show popups as new tabs while in non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.) This was implemented for Cocoa in a BrowserWindow override, but it makes sense to just stick it into Browser and remove a ton of override code put in just to support this. BUG=858929, 868416 TEST=as in bugs Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d Reviewed-on: https://chromium-review.googlesource.com/1153455 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MimeHandlerViewContainer::OnReady() { if (!render_frame() || !is_embedded_) return; blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); blink::WebAssociatedURLLoaderOptions options; DCHECK(!loader_); loader_.reset(frame->CreateAssociatedURLLoader(options)); blink::WebURLRequest request(original_url_); request.SetRequestContext(blink::WebURLRequest::kRequestContextObject); loader_->LoadAsynchronously(request, this); } Commit Message: Skip Service workers in requests for mime handler plugins BUG=808838 TEST=./browser_tests --gtest_filter=*/ServiceWorkerTest.MimeHandlerView* Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: I82e75c200091babbab648a04232db47e2938d914 Reviewed-on: https://chromium-review.googlesource.com/914150 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Istiaque Ahmed <[email protected]> Reviewed-by: Matt Falkenhagen <[email protected]> Cr-Commit-Position: refs/heads/master@{#537386} CWE ID: CWE-20 Target: 1 Example 2: Code: bool PPAPITestBase::GetHTTPDocumentRoot(FilePath* document_root) { FilePath exe_dir = CommandLine::ForCurrentProcess()->GetProgram().DirName(); FilePath src_dir; if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)) return false; if (!exe_dir.IsAbsolute()) file_util::AbsolutePath(&exe_dir); if (!src_dir.IsAbsolute()) file_util::AbsolutePath(&src_dir); if (!exe_dir.IsAbsolute()) return false; if (!src_dir.IsAbsolute()) return false; size_t match, exe_size, src_size; std::vector<FilePath::StringType> src_parts, exe_parts; exe_dir.GetComponents(&exe_parts); src_dir.GetComponents(&src_parts); exe_size = exe_parts.size(); src_size = src_parts.size(); for (match = 0; match < exe_size && match < src_size; ++match) { if (exe_parts[match] != src_parts[match]) break; } for (size_t tmp_itr = match; tmp_itr < src_size; ++tmp_itr) { *document_root = document_root->Append(FILE_PATH_LITERAL("..")); } for (; match < exe_size; ++match) { *document_root = document_root->Append(exe_parts[match]); } return true; } Commit Message: Disable OutOfProcessPPAPITest.VarDeprecated on Mac due to timeouts. BUG=121107 [email protected],[email protected] Review URL: https://chromiumcodereview.appspot.com/9950017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@129857 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const { RenderStyle* styleToUse = style(); if (!styleToUse->logicalMaxHeight().isUndefined()) { LayoutUnit maxH = computeContentLogicalHeight(styleToUse->logicalMaxHeight(), intrinsicContentHeight); if (maxH != -1) logicalHeight = min(logicalHeight, maxH); } return max(logicalHeight, computeContentLogicalHeight(styleToUse->logicalMinHeight(), intrinsicContentHeight)); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void TraceEvent::AppendAsJSON( std::string* out, const ArgumentFilterPredicate& argument_filter_predicate) const { int64 time_int64 = timestamp_.ToInternalValue(); int process_id = TraceLog::GetInstance()->process_id(); const char* category_group_name = TraceLog::GetCategoryGroupName(category_group_enabled_); DCHECK(!strchr(name_, '"')); StringAppendF(out, "{\"pid\":%i,\"tid\":%i,\"ts\":%" PRId64 "," "\"ph\":\"%c\",\"cat\":\"%s\",\"name\":\"%s\",\"args\":", process_id, thread_id_, time_int64, phase_, category_group_name, name_); bool strip_args = arg_names_[0] && !argument_filter_predicate.is_null() && !argument_filter_predicate.Run(category_group_name, name_); if (strip_args) { *out += "\"__stripped__\""; } else { *out += "{"; for (int i = 0; i < kTraceMaxNumArgs && arg_names_[i]; ++i) { if (i > 0) *out += ","; *out += "\""; *out += arg_names_[i]; *out += "\":"; if (arg_types_[i] == TRACE_VALUE_TYPE_CONVERTABLE) convertable_values_[i]->AppendAsTraceFormat(out); else AppendValueAsJSON(arg_types_[i], arg_values_[i], out); } *out += "}"; } if (phase_ == TRACE_EVENT_PHASE_COMPLETE) { int64 duration = duration_.ToInternalValue(); if (duration != -1) StringAppendF(out, ",\"dur\":%" PRId64, duration); if (!thread_timestamp_.is_null()) { int64 thread_duration = thread_duration_.ToInternalValue(); if (thread_duration != -1) StringAppendF(out, ",\"tdur\":%" PRId64, thread_duration); } } if (!thread_timestamp_.is_null()) { int64 thread_time_int64 = thread_timestamp_.ToInternalValue(); StringAppendF(out, ",\"tts\":%" PRId64, thread_time_int64); } if (flags_ & TRACE_EVENT_FLAG_ASYNC_TTS) { StringAppendF(out, ", \"use_async_tts\":1"); } if (flags_ & TRACE_EVENT_FLAG_HAS_ID) StringAppendF(out, ",\"id\":\"0x%" PRIx64 "\"", static_cast<uint64>(id_)); if (flags_ & TRACE_EVENT_FLAG_BIND_TO_ENCLOSING) StringAppendF(out, ",\"bp\":\"e\""); if ((flags_ & TRACE_EVENT_FLAG_FLOW_OUT) || (flags_ & TRACE_EVENT_FLAG_FLOW_IN)) { StringAppendF(out, ",\"bind_id\":\"0x%" PRIx64 "\"", static_cast<uint64>(bind_id_)); } if (flags_ & TRACE_EVENT_FLAG_FLOW_IN) StringAppendF(out, ",\"flow_in\":true"); if (flags_ & TRACE_EVENT_FLAG_FLOW_OUT) StringAppendF(out, ",\"flow_out\":true"); if (flags_ & TRACE_EVENT_FLAG_HAS_CONTEXT_ID) StringAppendF(out, ",\"cid\":\"0x%" PRIx64 "\"", static_cast<uint64>(context_id_)); if (phase_ == TRACE_EVENT_PHASE_INSTANT) { char scope = '?'; switch (flags_ & TRACE_EVENT_FLAG_SCOPE_MASK) { case TRACE_EVENT_SCOPE_GLOBAL: scope = TRACE_EVENT_SCOPE_NAME_GLOBAL; break; case TRACE_EVENT_SCOPE_PROCESS: scope = TRACE_EVENT_SCOPE_NAME_PROCESS; break; case TRACE_EVENT_SCOPE_THREAD: scope = TRACE_EVENT_SCOPE_NAME_THREAD; break; } StringAppendF(out, ",\"s\":\"%c\"", scope); } *out += "}"; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399 Target: 1 Example 2: Code: static struct inode *ext4_get_journal_inode(struct super_block *sb, unsigned int journal_inum) { struct inode *journal_inode; /* * Test for the existence of a valid inode on disk. Bad things * happen if we iget() an unused inode, as the subsequent iput() * will try to delete it. */ journal_inode = ext4_iget(sb, journal_inum); if (IS_ERR(journal_inode)) { ext4_msg(sb, KERN_ERR, "no journal found"); return NULL; } if (!journal_inode->i_nlink) { make_bad_inode(journal_inode); iput(journal_inode); ext4_msg(sb, KERN_ERR, "journal inode is deleted"); return NULL; } jbd_debug(2, "Journal inode found at %p: %lld bytes\n", journal_inode, journal_inode->i_size); if (!S_ISREG(journal_inode->i_mode)) { ext4_msg(sb, KERN_ERR, "invalid journal inode"); iput(journal_inode); return NULL; } return journal_inode; } Commit Message: ext4: validate s_first_meta_bg at mount time Ralf Spenneberg reported that he hit a kernel crash when mounting a modified ext4 image. And it turns out that kernel crashed when calculating fs overhead (ext4_calculate_overhead()), this is because the image has very large s_first_meta_bg (debug code shows it's 842150400), and ext4 overruns the memory in count_overhead() when setting bitmap buffer, which is PAGE_SIZE. ext4_calculate_overhead(): buf = get_zeroed_page(GFP_NOFS); <=== PAGE_SIZE buffer blks = count_overhead(sb, i, buf); count_overhead(): for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) { <=== j = 842150400 ext4_set_bit(EXT4_B2C(sbi, s++), buf); <=== buffer overrun count++; } This can be reproduced easily for me by this script: #!/bin/bash rm -f fs.img mkdir -p /mnt/ext4 fallocate -l 16M fs.img mke2fs -t ext4 -O bigalloc,meta_bg,^resize_inode -F fs.img debugfs -w -R "ssv first_meta_bg 842150400" fs.img mount -o loop fs.img /mnt/ext4 Fix it by validating s_first_meta_bg first at mount time, and refusing to mount if its value exceeds the largest possible meta_bg number. Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Eryu Guan <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Reviewed-by: Andreas Dilger <[email protected]> CWE ID: CWE-125 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GLManager::InitializeWithWorkaroundsImpl( const GLManager::Options& options, const GpuDriverBugWorkarounds& workarounds) { const SharedMemoryLimits limits; const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); DCHECK(!command_line.HasSwitch(switches::kDisableGLExtensions)); InitializeGpuPreferencesForTestingFromCommandLine(command_line, &gpu_preferences_); if (options.share_mailbox_manager) { mailbox_manager_ = options.share_mailbox_manager->mailbox_manager(); } else if (options.share_group_manager) { mailbox_manager_ = options.share_group_manager->mailbox_manager(); } else { mailbox_manager_ = &owned_mailbox_manager_; } gl::GLShareGroup* share_group = NULL; if (options.share_group_manager) { share_group = options.share_group_manager->share_group(); } else if (options.share_mailbox_manager) { share_group = options.share_mailbox_manager->share_group(); } gles2::ContextGroup* context_group = NULL; scoped_refptr<gles2::ShareGroup> client_share_group; if (options.share_group_manager) { context_group = options.share_group_manager->decoder_->GetContextGroup(); client_share_group = options.share_group_manager->gles2_implementation()->share_group(); } gl::GLContext* real_gl_context = NULL; if (options.virtual_manager && !gpu_preferences_.use_passthrough_cmd_decoder) { real_gl_context = options.virtual_manager->context(); } share_group_ = share_group ? share_group : new gl::GLShareGroup; ContextCreationAttribs attribs; attribs.red_size = 8; attribs.green_size = 8; attribs.blue_size = 8; attribs.alpha_size = 8; attribs.depth_size = 16; attribs.stencil_size = 8; attribs.context_type = options.context_type; attribs.samples = options.multisampled ? 4 : 0; attribs.sample_buffers = options.multisampled ? 1 : 0; attribs.alpha_size = options.backbuffer_alpha ? 8 : 0; attribs.should_use_native_gmb_for_backbuffer = options.image_factory != nullptr; attribs.offscreen_framebuffer_size = options.size; attribs.buffer_preserved = options.preserve_backbuffer; attribs.bind_generates_resource = options.bind_generates_resource; translator_cache_ = std::make_unique<gles2::ShaderTranslatorCache>(gpu_preferences_); if (!context_group) { scoped_refptr<gles2::FeatureInfo> feature_info = new gles2::FeatureInfo(workarounds); context_group = new gles2::ContextGroup( gpu_preferences_, true, mailbox_manager_, nullptr /* memory_tracker */, translator_cache_.get(), &completeness_cache_, feature_info, options.bind_generates_resource, &image_manager_, options.image_factory, nullptr /* progress_reporter */, GpuFeatureInfo(), &discardable_manager_); } command_buffer_.reset(new CommandBufferCheckLostContext( context_group->transfer_buffer_manager(), options.sync_point_manager, options.context_lost_allowed)); decoder_.reset(::gpu::gles2::GLES2Decoder::Create( command_buffer_.get(), command_buffer_->service(), &outputter_, context_group)); if (options.force_shader_name_hashing) { decoder_->SetForceShaderNameHashingForTest(true); } command_buffer_->set_handler(decoder_.get()); surface_ = gl::init::CreateOffscreenGLSurface(gfx::Size()); ASSERT_TRUE(surface_.get() != NULL) << "could not create offscreen surface"; if (base_context_) { context_ = scoped_refptr<gl::GLContext>(new gpu::GLContextVirtual( share_group_.get(), base_context_->get(), decoder_->AsWeakPtr())); ASSERT_TRUE(context_->Initialize( surface_.get(), GenerateGLContextAttribs(attribs, context_group))); } else { if (real_gl_context) { context_ = scoped_refptr<gl::GLContext>(new gpu::GLContextVirtual( share_group_.get(), real_gl_context, decoder_->AsWeakPtr())); ASSERT_TRUE(context_->Initialize( surface_.get(), GenerateGLContextAttribs(attribs, context_group))); } else { context_ = gl::init::CreateGLContext( share_group_.get(), surface_.get(), GenerateGLContextAttribs(attribs, context_group)); g_gpu_feature_info.ApplyToGLContext(context_.get()); } } ASSERT_TRUE(context_.get() != NULL) << "could not create GL context"; ASSERT_TRUE(context_->MakeCurrent(surface_.get())); auto result = decoder_->Initialize(surface_.get(), context_.get(), true, ::gpu::gles2::DisallowedFeatures(), attribs); if (result != gpu::ContextResult::kSuccess) return; capabilities_ = decoder_->GetCapabilities(); gles2_helper_.reset(new gles2::GLES2CmdHelper(command_buffer_.get())); ASSERT_EQ(gles2_helper_->Initialize(limits.command_buffer_size), gpu::ContextResult::kSuccess); transfer_buffer_.reset(new TransferBuffer(gles2_helper_.get())); const bool support_client_side_arrays = true; gles2_implementation_.reset(new gles2::GLES2Implementation( gles2_helper_.get(), std::move(client_share_group), transfer_buffer_.get(), options.bind_generates_resource, options.lose_context_when_out_of_memory, support_client_side_arrays, this)); ASSERT_EQ(gles2_implementation_->Initialize(limits), gpu::ContextResult::kSuccess) << "Could not init GLES2Implementation"; MakeCurrent(); } Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data. In linux and android, we are seeing an issue where texture data from one tab overwrites the texture data of another tab. This is happening for apps which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D. Due to a bug in virtual context save/restore code for above texture formats, the texture data is not properly restored while switching tabs. Hence texture data from one tab overwrites other. This CL has fix for that issue, an update for existing test expectations and a new unit test for this bug. Bug: 788448 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: Ie933984cdd2d1381f42eb4638f730c8245207a28 Reviewed-on: https://chromium-review.googlesource.com/930327 Reviewed-by: Zhenyao Mo <[email protected]> Commit-Queue: vikas soni <[email protected]> Cr-Commit-Position: refs/heads/master@{#539111} CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChromeMetricsServiceClient::RegisterMetricsServiceProviders() { PrefService* local_state = g_browser_process->local_state(); metrics_service_->RegisterMetricsProvider( std::make_unique<SubprocessMetricsProvider>()); #if BUILDFLAG(ENABLE_EXTENSIONS) metrics_service_->RegisterMetricsProvider( std::make_unique<ExtensionsMetricsProvider>(metrics_state_manager_)); #endif metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::NetworkMetricsProvider>( content::CreateNetworkConnectionTrackerAsyncGetter(), std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>())); metrics_service_->RegisterMetricsProvider( std::make_unique<OmniboxMetricsProvider>( base::Bind(&chrome::IsIncognitoSessionActive))); metrics_service_->RegisterMetricsProvider( std::make_unique<ChromeStabilityMetricsProvider>(local_state)); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::GPUMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::ScreenInfoMetricsProvider>()); metrics_service_->RegisterMetricsProvider(CreateFileMetricsProvider( metrics_state_manager_->IsMetricsReportingEnabled())); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::DriveMetricsProvider>( chrome::FILE_LOCAL_STATE)); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::CallStackProfileMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::SamplingMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<translate::TranslateRankerMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::ComponentMetricsProvider>( g_browser_process->component_updater())); #if defined(OS_ANDROID) metrics_service_->RegisterMetricsProvider( std::make_unique<AndroidMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<PageLoadMetricsProvider>()); #endif // defined(OS_ANDROID) #if defined(OS_WIN) metrics_service_->RegisterMetricsProvider( std::make_unique<GoogleUpdateMetricsProviderWin>()); base::FilePath user_data_dir; base::FilePath crash_dir; if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir) || !base::PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dir)) { user_data_dir = base::FilePath(); crash_dir = base::FilePath(); } metrics_service_->RegisterMetricsProvider( std::make_unique<browser_watcher::WatcherMetricsProviderWin>( chrome::GetBrowserExitCodesRegistryPath(), user_data_dir, crash_dir, base::Bind(&GetExecutableVersionDetails))); metrics_service_->RegisterMetricsProvider( std::make_unique<AntiVirusMetricsProvider>()); #endif // defined(OS_WIN) #if BUILDFLAG(ENABLE_PLUGINS) plugin_metrics_provider_ = new PluginMetricsProvider(local_state); metrics_service_->RegisterMetricsProvider( std::unique_ptr<metrics::MetricsProvider>(plugin_metrics_provider_)); #endif // BUILDFLAG(ENABLE_PLUGINS) #if defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( std::make_unique<ChromeOSMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<SigninStatusMetricsProviderChromeOS>()); if (metrics::GetMetricsReportingDefaultState(local_state) == metrics::EnableMetricsDefault::DEFAULT_UNKNOWN) { metrics::RecordMetricsReportingDefaultState( local_state, metrics::EnableMetricsDefault::OPT_OUT); } metrics_service_->RegisterMetricsProvider( std::make_unique<chromeos::PrinterMetricsProvider>()); #endif // defined(OS_CHROMEOS) #if !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( SigninStatusMetricsProvider::CreateInstance( std::make_unique<ChromeSigninStatusMetricsProviderDelegate>())); #endif // !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( std::make_unique<syncer::DeviceCountMetricsProvider>( base::Bind(&browser_sync::ChromeSyncClient::GetDeviceInfoTrackers))); metrics_service_->RegisterMetricsProvider( std::make_unique<HttpsEngagementMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<CertificateReportingMetricsProvider>()); #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( std::make_unique<UpgradeMetricsProvider>()); #endif //! defined(OS_ANDROID) && !defined(OS_CHROMEOS) #if defined(OS_MACOSX) metrics_service_->RegisterMetricsProvider( std::make_unique<PowerMetricsProvider>()); #endif #if BUILDFLAG(ENABLE_CROS_ASSISTANT) metrics_service_->RegisterMetricsProvider( std::make_unique<AssistantServiceMetricsProvider>()); #endif // BUILDFLAG(ENABLE_CROS_ASSISTANT) } Commit Message: Add CPU metrics provider and Add CPU/GPU provider for UKM. Bug: 907674 Change-Id: I61b88aeac8d2a7ff81d812fa5a267f48203ec7e2 Reviewed-on: https://chromium-review.googlesource.com/c/1381376 Commit-Queue: Nik Bhagat <[email protected]> Reviewed-by: Robert Kaplow <[email protected]> Cr-Commit-Position: refs/heads/master@{#618037} CWE ID: CWE-79 Target: 1 Example 2: Code: static void mddev_detach(struct mddev *mddev) { struct bitmap *bitmap = mddev->bitmap; /* wait for behind writes to complete */ if (bitmap && atomic_read(&bitmap->behind_writes) > 0) { printk(KERN_INFO "md:%s: behind writes in progress - waiting to stop.\n", mdname(mddev)); /* need to kick something here to make sure I/O goes? */ wait_event(bitmap->behind_wait, atomic_read(&bitmap->behind_writes) == 0); } if (mddev->pers && mddev->pers->quiesce) { mddev->pers->quiesce(mddev, 1); mddev->pers->quiesce(mddev, 0); } md_unregister_thread(&mddev->thread); if (mddev->queue) blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/ } 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 <[email protected]> Signed-off-by: NeilBrown <[email protected]> CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void destroy_pit_timer(struct kvm_timer *pt) { pr_debug("execute del timer!\n"); hrtimer_cancel(&pt->timer); } Commit Message: KVM: PIT: control word is write-only PIT control word (address 0x43) is write-only, reads are undefined. Cc: [email protected] Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { png_size_t copy = output_size - count; if ((png_size_t) avail < copy) copy = (png_size_t) avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: static void authentication_success(void) { int r; struct mboxevent *mboxevent; /* authstate already created by mysasl_proxy_policy() */ imapd_userisadmin = global_authisa(imapd_authstate, IMAPOPT_ADMINS); /* Create telemetry log */ imapd_logfd = telemetry_log(imapd_userid, imapd_in, imapd_out, 0); /* Set namespace */ r = mboxname_init_namespace(&imapd_namespace, imapd_userisadmin || imapd_userisproxyadmin); mboxevent_setnamespace(&imapd_namespace); if (r) { syslog(LOG_ERR, "%s", error_message(r)); fatal(error_message(r), EC_CONFIG); } /* Make a copy of the external userid for use in proxying */ proxy_userid = xstrdup(imapd_userid); /* send a Login event notification */ if ((mboxevent = mboxevent_new(EVENT_LOGIN))) { mboxevent_set_access(mboxevent, saslprops.iplocalport, saslprops.ipremoteport, imapd_userid, NULL, 1); mboxevent_notify(&mboxevent); mboxevent_free(&mboxevent); } #ifdef USE_AUTOCREATE autocreate_inbox(); #endif // USE_AUTOCREATE } Commit Message: imapd: check for isadmin BEFORE parsing sync lines CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool GetURLRowForAutocompleteMatch(Profile* profile, const AutocompleteMatch& match, history::URLRow* url_row) { DCHECK(url_row); HistoryService* history_service = profile->GetHistoryService(Profile::EXPLICIT_ACCESS); if (!history_service) return false; history::URLDatabase* url_db = history_service->InMemoryDatabase(); return url_db && (url_db->GetRowForURL(match.destination_url, url_row) != 0); } Commit Message: Removing dead code from NetworkActionPredictor. BUG=none Review URL: http://codereview.chromium.org/9358062 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@121926 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: AppControllerImpl::~AppControllerImpl() { if (apps::AppServiceProxy::Get(profile_)) app_service_proxy_->AppRegistryCache().RemoveObserver(this); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416 Target: 1 Example 2: Code: void IndexedDBDispatcher::RequestIDBObjectStoreDeleteRange( const IndexedDBKeyRange& key_range, WebIDBCallbacks* callbacks_ptr, int32 idb_object_store_id, const WebIDBTransaction& transaction, WebExceptionCode* ec) { ResetCursorPrefetchCaches(); scoped_ptr<WebIDBCallbacks> callbacks(callbacks_ptr); int32 response_id = pending_callbacks_.Add(callbacks.release()); Send(new IndexedDBHostMsg_ObjectStoreDeleteRange( idb_object_store_id, CurrentWorkerId(), response_id, key_range, TransactionId(transaction), ec)); if (*ec) pending_callbacks_.Remove(response_id); } Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created. This could happen if there are IDB objects that survive the call to didStopWorkerRunLoop. BUG=121734 TEST= Review URL: http://codereview.chromium.org/9999035 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Extension::InitFromValue(const DictionaryValue& source, int flags, std::string* error) { URLPattern::ParseOption parse_strictness = (flags & STRICT_ERROR_CHECKS ? URLPattern::PARSE_STRICT : URLPattern::PARSE_LENIENT); if (source.HasKey(keys::kPublicKey)) { std::string public_key_bytes; if (!source.GetString(keys::kPublicKey, &public_key_) || !ParsePEMKeyBytes(public_key_, &public_key_bytes) || !GenerateId(public_key_bytes, &id_)) { *error = errors::kInvalidKey; return false; } } else if (flags & REQUIRE_KEY) { *error = errors::kInvalidKey; return false; } else { id_ = Extension::GenerateIdForPath(path()); if (id_.empty()) { NOTREACHED() << "Could not create ID from path."; return false; } } manifest_value_.reset(source.DeepCopy()); extension_url_ = Extension::GetBaseURLFromExtensionId(id()); std::string version_str; if (!source.GetString(keys::kVersion, &version_str)) { *error = errors::kInvalidVersion; return false; } version_.reset(Version::GetVersionFromString(version_str)); if (!version_.get() || version_->components().size() > 4) { *error = errors::kInvalidVersion; return false; } string16 localized_name; if (!source.GetString(keys::kName, &localized_name)) { *error = errors::kInvalidName; return false; } base::i18n::AdjustStringForLocaleDirection(&localized_name); name_ = UTF16ToUTF8(localized_name); if (source.HasKey(keys::kDescription)) { if (!source.GetString(keys::kDescription, &description_)) { *error = errors::kInvalidDescription; return false; } } if (source.HasKey(keys::kHomepageURL)) { std::string tmp; if (!source.GetString(keys::kHomepageURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, ""); return false; } homepage_url_ = GURL(tmp); if (!homepage_url_.is_valid()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, tmp); return false; } } if (source.HasKey(keys::kUpdateURL)) { std::string tmp; if (!source.GetString(keys::kUpdateURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, ""); return false; } update_url_ = GURL(tmp); if (!update_url_.is_valid() || update_url_.has_ref()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, tmp); return false; } } if (source.HasKey(keys::kMinimumChromeVersion)) { std::string minimum_version_string; if (!source.GetString(keys::kMinimumChromeVersion, &minimum_version_string)) { *error = errors::kInvalidMinimumChromeVersion; return false; } scoped_ptr<Version> minimum_version( Version::GetVersionFromString(minimum_version_string)); if (!minimum_version.get()) { *error = errors::kInvalidMinimumChromeVersion; return false; } chrome::VersionInfo current_version_info; if (!current_version_info.is_valid()) { NOTREACHED(); return false; } scoped_ptr<Version> current_version( Version::GetVersionFromString(current_version_info.Version())); if (!current_version.get()) { DCHECK(false); return false; } if (current_version->CompareTo(*minimum_version) < 0) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kChromeVersionTooLow, l10n_util::GetStringUTF8(IDS_PRODUCT_NAME), minimum_version_string); return false; } } source.GetBoolean(keys::kConvertedFromUserScript, &converted_from_user_script_); if (source.HasKey(keys::kIcons)) { DictionaryValue* icons_value = NULL; if (!source.GetDictionary(keys::kIcons, &icons_value)) { *error = errors::kInvalidIcons; return false; } for (size_t i = 0; i < arraysize(kIconSizes); ++i) { std::string key = base::IntToString(kIconSizes[i]); if (icons_value->HasKey(key)) { std::string icon_path; if (!icons_value->GetString(key, &icon_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } if (!icon_path.empty() && icon_path[0] == '/') icon_path = icon_path.substr(1); if (icon_path.empty()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } icons_.Add(kIconSizes[i], icon_path); } } } is_theme_ = false; if (source.HasKey(keys::kTheme)) { if (ContainsNonThemeKeys(source)) { *error = errors::kThemesCannotContainExtensions; return false; } DictionaryValue* theme_value = NULL; if (!source.GetDictionary(keys::kTheme, &theme_value)) { *error = errors::kInvalidTheme; return false; } is_theme_ = true; DictionaryValue* images_value = NULL; if (theme_value->GetDictionary(keys::kThemeImages, &images_value)) { for (DictionaryValue::key_iterator iter = images_value->begin_keys(); iter != images_value->end_keys(); ++iter) { std::string val; if (!images_value->GetString(*iter, &val)) { *error = errors::kInvalidThemeImages; return false; } } theme_images_.reset(images_value->DeepCopy()); } DictionaryValue* colors_value = NULL; if (theme_value->GetDictionary(keys::kThemeColors, &colors_value)) { for (DictionaryValue::key_iterator iter = colors_value->begin_keys(); iter != colors_value->end_keys(); ++iter) { ListValue* color_list = NULL; double alpha = 0.0; int color = 0; if (!colors_value->GetListWithoutPathExpansion(*iter, &color_list) || ((color_list->GetSize() != 3) && ((color_list->GetSize() != 4) || !color_list->GetDouble(3, &alpha))) || !color_list->GetInteger(0, &color) || !color_list->GetInteger(1, &color) || !color_list->GetInteger(2, &color)) { *error = errors::kInvalidThemeColors; return false; } } theme_colors_.reset(colors_value->DeepCopy()); } DictionaryValue* tints_value = NULL; if (theme_value->GetDictionary(keys::kThemeTints, &tints_value)) { for (DictionaryValue::key_iterator iter = tints_value->begin_keys(); iter != tints_value->end_keys(); ++iter) { ListValue* tint_list = NULL; double v = 0.0; if (!tints_value->GetListWithoutPathExpansion(*iter, &tint_list) || tint_list->GetSize() != 3 || !tint_list->GetDouble(0, &v) || !tint_list->GetDouble(1, &v) || !tint_list->GetDouble(2, &v)) { *error = errors::kInvalidThemeTints; return false; } } theme_tints_.reset(tints_value->DeepCopy()); } DictionaryValue* display_properties_value = NULL; if (theme_value->GetDictionary(keys::kThemeDisplayProperties, &display_properties_value)) { theme_display_properties_.reset( display_properties_value->DeepCopy()); } return true; } if (source.HasKey(keys::kPlugins)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPlugins, &list_value)) { *error = errors::kInvalidPlugins; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* plugin_value = NULL; std::string path_str; bool is_public = false; if (!list_value->GetDictionary(i, &plugin_value)) { *error = errors::kInvalidPlugins; return false; } if (!plugin_value->GetString(keys::kPluginsPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPath, base::IntToString(i)); return false; } if (plugin_value->HasKey(keys::kPluginsPublic)) { if (!plugin_value->GetBoolean(keys::kPluginsPublic, &is_public)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPublic, base::IntToString(i)); return false; } } #if !defined(OS_CHROMEOS) plugins_.push_back(PluginInfo()); plugins_.back().path = path().AppendASCII(path_str); plugins_.back().is_public = is_public; #endif } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kNaClModules)) { ListValue* list_value = NULL; if (!source.GetList(keys::kNaClModules, &list_value)) { *error = errors::kInvalidNaClModules; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* module_value = NULL; std::string path_str; std::string mime_type; if (!list_value->GetDictionary(i, &module_value)) { *error = errors::kInvalidNaClModules; return false; } if (!module_value->GetString(keys::kNaClModulesPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesPath, base::IntToString(i)); return false; } if (!module_value->GetString(keys::kNaClModulesMIMEType, &mime_type)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesMIMEType, base::IntToString(i)); return false; } nacl_modules_.push_back(NaClModuleInfo()); nacl_modules_.back().url = GetResourceURL(path_str); nacl_modules_.back().mime_type = mime_type; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kToolstrips)) { ListValue* list_value = NULL; if (!source.GetList(keys::kToolstrips, &list_value)) { *error = errors::kInvalidToolstrips; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { GURL toolstrip; DictionaryValue* toolstrip_value = NULL; std::string toolstrip_path; if (list_value->GetString(i, &toolstrip_path)) { toolstrip = GetResourceURL(toolstrip_path); } else if (list_value->GetDictionary(i, &toolstrip_value)) { if (!toolstrip_value->GetString(keys::kToolstripPath, &toolstrip_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrip = GetResourceURL(toolstrip_path); } else { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrips_.push_back(toolstrip); } } if (source.HasKey(keys::kContentScripts)) { ListValue* list_value; if (!source.GetList(keys::kContentScripts, &list_value)) { *error = errors::kInvalidContentScriptsList; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* content_script = NULL; if (!list_value->GetDictionary(i, &content_script)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidContentScript, base::IntToString(i)); return false; } UserScript script; if (!LoadUserScriptHelper(content_script, i, flags, error, &script)) return false; // Failed to parse script context definition. script.set_extension_id(id()); if (converted_from_user_script_) { script.set_emulate_greasemonkey(true); script.set_match_all_frames(true); // Greasemonkey matches all frames. } content_scripts_.push_back(script); } } DictionaryValue* page_action_value = NULL; if (source.HasKey(keys::kPageActions)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPageActions, &list_value)) { *error = errors::kInvalidPageActionsList; return false; } size_t list_value_length = list_value->GetSize(); if (list_value_length == 0u) { } else if (list_value_length == 1u) { if (!list_value->GetDictionary(0, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } else { // list_value_length > 1u. *error = errors::kInvalidPageActionsListSize; return false; } } else if (source.HasKey(keys::kPageAction)) { if (!source.GetDictionary(keys::kPageAction, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } if (page_action_value) { page_action_.reset( LoadExtensionActionHelper(page_action_value, error)); if (!page_action_.get()) return false; // Failed to parse page action definition. } if (source.HasKey(keys::kBrowserAction)) { DictionaryValue* browser_action_value = NULL; if (!source.GetDictionary(keys::kBrowserAction, &browser_action_value)) { *error = errors::kInvalidBrowserAction; return false; } browser_action_.reset( LoadExtensionActionHelper(browser_action_value, error)); if (!browser_action_.get()) return false; // Failed to parse browser action definition. } if (source.HasKey(keys::kFileBrowserHandlers)) { ListValue* file_browser_handlers_value = NULL; if (!source.GetList(keys::kFileBrowserHandlers, &file_browser_handlers_value)) { *error = errors::kInvalidFileBrowserHandler; return false; } file_browser_handlers_.reset( LoadFileBrowserHandlers(file_browser_handlers_value, error)); if (!file_browser_handlers_.get()) return false; // Failed to parse file browser actions definition. } if (!LoadIsApp(manifest_value_.get(), error) || !LoadExtent(manifest_value_.get(), keys::kWebURLs, &extent_, errors::kInvalidWebURLs, errors::kInvalidWebURL, parse_strictness, error) || !EnsureNotHybridApp(manifest_value_.get(), error) || !LoadLaunchURL(manifest_value_.get(), error) || !LoadLaunchContainer(manifest_value_.get(), error) || !LoadAppIsolation(manifest_value_.get(), error)) { return false; } if (source.HasKey(keys::kOptionsPage)) { std::string options_str; if (!source.GetString(keys::kOptionsPage, &options_str)) { *error = errors::kInvalidOptionsPage; return false; } if (is_hosted_app()) { GURL options_url(options_str); if (!options_url.is_valid() || !(options_url.SchemeIs("http") || options_url.SchemeIs("https"))) { *error = errors::kInvalidOptionsPageInHostedApp; return false; } options_url_ = options_url; } else { GURL absolute(options_str); if (absolute.is_valid()) { *error = errors::kInvalidOptionsPageExpectUrlInPackage; return false; } options_url_ = GetResourceURL(options_str); if (!options_url_.is_valid()) { *error = errors::kInvalidOptionsPage; return false; } } } if (source.HasKey(keys::kPermissions)) { ListValue* permissions = NULL; if (!source.GetList(keys::kPermissions, &permissions)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissions, ""); return false; } for (size_t i = 0; i < permissions->GetSize(); ++i) { std::string permission_str; if (!permissions->GetString(i, &permission_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermission, base::IntToString(i)); return false; } if (!IsComponentOnlyPermission(permission_str) #ifndef NDEBUG && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kExposePrivateExtensionApi) #endif ) { continue; } if (permission_str == kOldUnlimitedStoragePermission) permission_str = kUnlimitedStoragePermission; if (web_extent().is_empty() || location() == Extension::COMPONENT) { if (IsAPIPermission(permission_str)) { if (permission_str == Extension::kExperimentalPermission && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && location() != Extension::COMPONENT) { *error = errors::kExperimentalFlagRequired; return false; } api_permissions_.insert(permission_str); continue; } } else { if (IsHostedAppPermission(permission_str)) { api_permissions_.insert(permission_str); continue; } } URLPattern pattern = URLPattern(CanExecuteScriptEverywhere() ? URLPattern::SCHEME_ALL : kValidHostPermissionSchemes); URLPattern::ParseResult parse_result = pattern.Parse(permission_str, parse_strictness); if (parse_result == URLPattern::PARSE_SUCCESS) { if (!CanSpecifyHostPermission(pattern)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissionScheme, base::IntToString(i)); return false; } pattern.SetPath("/*"); if (pattern.MatchesScheme(chrome::kFileScheme) && !CanExecuteScriptEverywhere()) { wants_file_access_ = true; if (!(flags & ALLOW_FILE_ACCESS)) pattern.set_valid_schemes( pattern.valid_schemes() & ~URLPattern::SCHEME_FILE); } host_permissions_.push_back(pattern); } } } if (source.HasKey(keys::kBackground)) { std::string background_str; if (!source.GetString(keys::kBackground, &background_str)) { *error = errors::kInvalidBackground; return false; } if (is_hosted_app()) { if (api_permissions_.find(kBackgroundPermission) == api_permissions_.end()) { *error = errors::kBackgroundPermissionNeeded; return false; } GURL bg_page(background_str); if (!bg_page.is_valid()) { *error = errors::kInvalidBackgroundInHostedApp; return false; } if (!(bg_page.SchemeIs("https") || (CommandLine::ForCurrentProcess()->HasSwitch( switches::kAllowHTTPBackgroundPage) && bg_page.SchemeIs("http")))) { *error = errors::kInvalidBackgroundInHostedApp; return false; } background_url_ = bg_page; } else { background_url_ = GetResourceURL(background_str); } } if (source.HasKey(keys::kDefaultLocale)) { if (!source.GetString(keys::kDefaultLocale, &default_locale_) || !l10n_util::IsValidLocaleSyntax(default_locale_)) { *error = errors::kInvalidDefaultLocale; return false; } } if (source.HasKey(keys::kChromeURLOverrides)) { DictionaryValue* overrides = NULL; if (!source.GetDictionary(keys::kChromeURLOverrides, &overrides)) { *error = errors::kInvalidChromeURLOverrides; return false; } for (DictionaryValue::key_iterator iter = overrides->begin_keys(); iter != overrides->end_keys(); ++iter) { std::string page = *iter; std::string val; if ((page != chrome::kChromeUINewTabHost && #if defined(TOUCH_UI) page != chrome::kChromeUIKeyboardHost && #endif #if defined(OS_CHROMEOS) page != chrome::kChromeUIActivationMessageHost && #endif page != chrome::kChromeUIBookmarksHost && page != chrome::kChromeUIHistoryHost) || !overrides->GetStringWithoutPathExpansion(*iter, &val)) { *error = errors::kInvalidChromeURLOverrides; return false; } chrome_url_overrides_[page] = GetResourceURL(val); } if (overrides->size() > 1) { *error = errors::kMultipleOverrides; return false; } } if (source.HasKey(keys::kOmnibox)) { if (!source.GetString(keys::kOmniboxKeyword, &omnibox_keyword_) || omnibox_keyword_.empty()) { *error = errors::kInvalidOmniboxKeyword; return false; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kContentSecurityPolicy)) { std::string content_security_policy; if (!source.GetString(keys::kContentSecurityPolicy, &content_security_policy)) { *error = errors::kInvalidContentSecurityPolicy; return false; } const char kBadCSPCharacters[] = {'\r', '\n', '\0'}; if (content_security_policy.find_first_of(kBadCSPCharacters, 0, arraysize(kBadCSPCharacters)) != std::string::npos) { *error = errors::kInvalidContentSecurityPolicy; return false; } content_security_policy_ = content_security_policy; } if (source.HasKey(keys::kDevToolsPage)) { std::string devtools_str; if (!source.GetString(keys::kDevToolsPage, &devtools_str)) { *error = errors::kInvalidDevToolsPage; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kDevToolsExperimental; return false; } devtools_url_ = GetResourceURL(devtools_str); } if (source.HasKey(keys::kSidebar)) { DictionaryValue* sidebar_value = NULL; if (!source.GetDictionary(keys::kSidebar, &sidebar_value)) { *error = errors::kInvalidSidebar; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kSidebarExperimental; return false; } sidebar_defaults_.reset(LoadExtensionSidebarDefaults(sidebar_value, error)); if (!sidebar_defaults_.get()) return false; // Failed to parse sidebar definition. } if (source.HasKey(keys::kTts)) { DictionaryValue* tts_dict = NULL; if (!source.GetDictionary(keys::kTts, &tts_dict)) { *error = errors::kInvalidTts; return false; } if (tts_dict->HasKey(keys::kTtsVoices)) { ListValue* tts_voices = NULL; if (!tts_dict->GetList(keys::kTtsVoices, &tts_voices)) { *error = errors::kInvalidTtsVoices; return false; } for (size_t i = 0; i < tts_voices->GetSize(); i++) { DictionaryValue* one_tts_voice = NULL; if (!tts_voices->GetDictionary(i, &one_tts_voice)) { *error = errors::kInvalidTtsVoices; return false; } TtsVoice voice_data; if (one_tts_voice->HasKey(keys::kTtsVoicesVoiceName)) { if (!one_tts_voice->GetString( keys::kTtsVoicesVoiceName, &voice_data.voice_name)) { *error = errors::kInvalidTtsVoicesVoiceName; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesLocale)) { if (!one_tts_voice->GetString( keys::kTtsVoicesLocale, &voice_data.locale) || !l10n_util::IsValidLocaleSyntax(voice_data.locale)) { *error = errors::kInvalidTtsVoicesLocale; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesGender)) { if (!one_tts_voice->GetString( keys::kTtsVoicesGender, &voice_data.gender) || (voice_data.gender != keys::kTtsGenderMale && voice_data.gender != keys::kTtsGenderFemale)) { *error = errors::kInvalidTtsVoicesGender; return false; } } tts_voices_.push_back(voice_data); } } } incognito_split_mode_ = is_app(); if (source.HasKey(keys::kIncognito)) { std::string value; if (!source.GetString(keys::kIncognito, &value)) { *error = errors::kInvalidIncognitoBehavior; return false; } if (value == values::kIncognitoSpanning) { incognito_split_mode_ = false; } else if (value == values::kIncognitoSplit) { incognito_split_mode_ = true; } else { *error = errors::kInvalidIncognitoBehavior; return false; } } if (HasMultipleUISurfaces()) { *error = errors::kOneUISurfaceOnly; return false; } InitEffectiveHostPermissions(); DCHECK(source.Equals(manifest_value_.get())); return true; } Commit Message: Prevent extensions from defining homepages with schemes other than valid web extents. BUG=84402 TEST=ExtensionManifestTest.ParseHomepageURLs Review URL: http://codereview.chromium.org/7089014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87722 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2) { int l1,l2; DICT_NOTUSED(privdata); l1 = sdslen((sds)key1); l2 = sdslen((sds)key2); if (l1 != l2) return 0; return memcmp(key1, key2, l1) == 0; } Commit Message: Security: Cross Protocol Scripting protection. This is an attempt at mitigating problems due to cross protocol scripting, an attack targeting services using line oriented protocols like Redis that can accept HTTP requests as valid protocol, by discarding the invalid parts and accepting the payloads sent, for example, via a POST request. For this to be effective, when we detect POST and Host: and terminate the connection asynchronously, the networking code was modified in order to never process further input. It was later verified that in a pipelined request containing a POST command, the successive commands are not executed. CWE ID: CWE-254 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebPluginDelegateProxy::SendUpdateGeometry( bool bitmaps_changed) { PluginMsg_UpdateGeometry_Param param; param.window_rect = plugin_rect_; param.clip_rect = clip_rect_; param.windowless_buffer0 = TransportDIB::DefaultHandleValue(); param.windowless_buffer1 = TransportDIB::DefaultHandleValue(); param.windowless_buffer_index = back_buffer_index(); param.background_buffer = TransportDIB::DefaultHandleValue(); param.transparent = transparent_; #if defined(OS_POSIX) if (bitmaps_changed) #endif { if (transport_stores_[0].dib.get()) CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(), &param.windowless_buffer0); if (transport_stores_[1].dib.get()) CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(), &param.windowless_buffer1); if (background_store_.dib.get()) CopyTransportDIBHandleForMessage(background_store_.dib->handle(), &param.background_buffer); } IPC::Message* msg; #if defined(OS_WIN) if (UseSynchronousGeometryUpdates()) { msg = new PluginMsg_UpdateGeometrySync(instance_id_, param); } else // NOLINT #endif { msg = new PluginMsg_UpdateGeometry(instance_id_, param); msg->set_unblock(true); } Send(msg); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType DecodeImage(Image *image,unsigned char *luma, unsigned char *chroma1,unsigned char *chroma2,ExceptionInfo *exception) { #define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL) #define PCDGetBits(n) \ { \ sum=(sum << n) & 0xffffffff; \ bits-=n; \ while (bits <= 24) \ { \ if (p >= (buffer+0x800)) \ { \ count=ReadBlob(image,0x800,buffer); \ p=buffer; \ } \ sum|=((unsigned int) (*p) << (24-bits)); \ bits+=8; \ p++; \ } \ } typedef struct PCDTable { unsigned int length, sequence; MagickStatusType mask; unsigned char key; } PCDTable; PCDTable *pcd_table[3]; register ssize_t i, j; register PCDTable *r; register unsigned char *p, *q; size_t bits, length, plane, pcd_length[3], row, sum; ssize_t count, quantum; unsigned char *buffer; /* Initialize Huffman tables. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(luma != (unsigned char *) NULL); assert(chroma1 != (unsigned char *) NULL); assert(chroma2 != (unsigned char *) NULL); buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); sum=0; bits=32; p=buffer+0x800; for (i=0; i < 3; i++) { pcd_table[i]=(PCDTable *) NULL; pcd_length[i]=0; } for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) { PCDGetBits(8); length=(sum & 0xff)+1; pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length, sizeof(*pcd_table[i])); if (pcd_table[i] == (PCDTable *) NULL) { buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } r=pcd_table[i]; for (j=0; j < (ssize_t) length; j++) { PCDGetBits(8); r->length=(unsigned int) (sum & 0xff)+1; if (r->length > 16) { buffer=(unsigned char *) RelinquishMagickMemory(buffer); return(MagickFalse); } PCDGetBits(16); r->sequence=(unsigned int) (sum & 0xffff) << 16; PCDGetBits(8); r->key=(unsigned char) (sum & 0xff); r->mask=(~((1U << (32-r->length))-1)); r++; } pcd_length[i]=(size_t) length; } /* Search for Sync byte. */ for (i=0; i < 1; i++) PCDGetBits(16); for (i=0; i < 1; i++) PCDGetBits(16); while ((sum & 0x00fff000UL) != 0x00fff000UL) PCDGetBits(8); while (IsSync(sum) == 0) PCDGetBits(1); /* Recover the Huffman encoded luminance and chrominance deltas. */ count=0; length=0; plane=0; row=0; q=luma; for ( ; ; ) { if (IsSync(sum) != 0) { /* Determine plane and row number. */ PCDGetBits(16); row=((sum >> 9) & 0x1fff); if (row == image->rows) break; PCDGetBits(8); plane=sum >> 30; PCDGetBits(16); switch (plane) { case 0: { q=luma+row*image->columns; count=(ssize_t) image->columns; break; } case 2: { q=chroma1+(row >> 1)*image->columns; count=(ssize_t) (image->columns >> 1); plane--; break; } case 3: { q=chroma2+(row >> 1)*image->columns; count=(ssize_t) (image->columns >> 1); plane--; break; } default: { for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowBinaryException(CorruptImageError,"CorruptImage", image->filename); } } length=pcd_length[plane]; continue; } /* Decode luminance or chrominance deltas. */ r=pcd_table[plane]; for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++) r++; if ((row > image->rows) || (r == (PCDTable *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename); while ((sum & 0x00fff000) != 0x00fff000) PCDGetBits(8); while (IsSync(sum) == 0) PCDGetBits(1); continue; } if (r->key < 128) quantum=(ssize_t) (*q)+r->key; else quantum=(ssize_t) (*q)+r->key-256; *q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum); q++; PCDGetBits(r->length); count--; } /* Relinquish resources. */ for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); buffer=(unsigned char *) RelinquishMagickMemory(buffer); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1450 CWE ID: CWE-399 Target: 1 Example 2: Code: status_t Camera3Device::triggerAutofocus(uint32_t id) { ATRACE_CALL(); Mutex::Autolock il(mInterfaceLock); ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id); RequestTrigger trigger[] = { { ANDROID_CONTROL_AF_TRIGGER, ANDROID_CONTROL_AF_TRIGGER_START }, { ANDROID_CONTROL_AF_TRIGGER_ID, static_cast<int32_t>(id) } }; return mRequestThread->queueTrigger(trigger, sizeof(trigger)/sizeof(trigger[0])); } Commit Message: Camera3Device: Validate template ID Validate template ID before creating a default request. Bug: 26866110 Bug: 27568958 Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d CWE ID: CWE-264 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void aes_crypt_ecb( aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16] ) { int i; unsigned long *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; #if defined(XYSSL_PADLOCK_C) && defined(XYSSL_HAVE_X86) if( padlock_supports( PADLOCK_ACE ) ) { if( padlock_xcryptecb( ctx, mode, input, output ) == 0 ) return; } #endif RK = ctx->rk; GET_ULONG_LE( X0, input, 0 ); X0 ^= *RK++; if( mode == AES_DECRYPT ) { for( i = (ctx->nr >> 1) - 1; i > 0; i-- ) { AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 ); } AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); X0 = *RK++ ^ ( RSb[ ( Y0 ) & 0xFF ] ) ^ ( RSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^ ( RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)RSb[ ( Y1 >> 24 ) & 0xFF ]) << 24 ); X1 = *RK++ ^ ( RSb[ ( Y1 ) & 0xFF ] ) ^ ( RSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^ ( RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)RSb[ ( Y2 >> 24 ) & 0xFF ]) << 24 ); X2 = *RK++ ^ ( RSb[ ( Y2 ) & 0xFF ] ) ^ ( RSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^ ( RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)RSb[ ( Y3 >> 24 ) & 0xFF ]) << 24 ); X3 = *RK++ ^ ( RSb[ ( Y3 ) & 0xFF ] ) ^ ( RSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^ ( RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)RSb[ ( Y0 >> 24 ) & 0xFF ]) << 24 ); } else /* AES_ENCRYPT */ { for( i = (ctx->nr >> 1) - 1; i > 0; i-- ) { AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 ); } AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); X0 = *RK++ ^ ( FSb[ ( Y0 ) & 0xFF ] ) ^ ( FSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^ ( FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)FSb[ ( Y3 >> 24 ) & 0xFF ]) << 24 ); X1 = *RK++ ^ ( FSb[ ( Y1 ) & 0xFF ] ) ^ ( FSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^ ( FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)FSb[ ( Y0 >> 24 ) & 0xFF ]) << 24 ); X2 = *RK++ ^ ( FSb[ ( Y2 ) & 0xFF ] ) ^ ( FSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^ ( FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)FSb[ ( Y1 >> 24 ) & 0xFF ]) << 24 ); X3 = *RK++ ^ ( FSb[ ( Y3 ) & 0xFF ] ) ^ ( FSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^ ( FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^ ( ((unsigned int)FSb[ ( Y2 >> 24 ) & 0xFF ]) << 24 ); } PUT_ULONG_LE( X0, output, 0 ); PUT_ULONG_LE( X1, output, 4 ); PUT_ULONG_LE( X2, output, 8 ); PUT_ULONG_LE( X3, output, 12 ); } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GDataDirectoryService::GDataDirectoryService() : blocking_task_runner_(NULL), serialized_size_(0), largest_changestamp_(0), origin_(UNINITIALIZED), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { root_.reset(new GDataDirectory(NULL, this)); if (!util::IsDriveV2ApiEnabled()) InitializeRootEntry(kGDataRootDirectoryResourceId); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: const uint8_t *ATSParser::PSISection::data() const { return mBuffer == NULL ? NULL : mBuffer->data(); } Commit Message: Check section size when verifying CRC Bug: 28333006 Change-Id: Ief7a2da848face78f0edde21e2f2009316076679 CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *name) { char clip_mask[MaxTextExtent]; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(clip_mask,MaxTextExtent,"%s",name); value=GetImageArtifact(image,clip_mask); if (value == (const char *) NULL) return(MagickFalse); if (image->clip_mask == (Image *) NULL) { Image *clip_mask; clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue, &image->exception); if (clip_mask == (Image *) NULL) return(MagickFalse); (void) SetImageClipMask(image,clip_mask); clip_mask=DestroyImage(clip_mask); } (void) QueryColorDatabase("#00000000",&image->clip_mask->background_color, &image->exception); image->clip_mask->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(image->clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", draw_info->clip_mask); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,value); (void) QueryColorDatabase("#ffffff",&clone_info->fill,&image->exception); clone_info->clip_mask=(char *) NULL; status=DrawImage(image->clip_mask,clone_info); status&=NegateImage(image->clip_mask,MagickFalse); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: Prevent buffer overflow (bug report from Max Thrane) CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool parse_reconnect(struct pool *pool, json_t *val) { char *sockaddr_url, *stratum_port, *tmp; char *url, *port, address[256]; memset(address, 0, 255); url = (char *)json_string_value(json_array_get(val, 0)); if (!url) url = pool->sockaddr_url; else { char *dot_pool, *dot_reconnect; dot_pool = strchr(pool->sockaddr_url, '.'); if (!dot_pool) { applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'", pool->sockaddr_url); return false; } dot_reconnect = strchr(url, '.'); if (!dot_reconnect) { applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'", url); return false; } if (strcmp(dot_pool, dot_reconnect)) { applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'", pool->sockaddr_url); return false; } } port = (char *)json_string_value(json_array_get(val, 1)); if (!port) port = pool->stratum_port; sprintf(address, "%s:%s", url, port); if (!extract_sockaddr(address, &sockaddr_url, &stratum_port)) return false; applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address); clear_pool_work(pool); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); tmp = pool->sockaddr_url; pool->sockaddr_url = sockaddr_url; pool->stratum_url = pool->sockaddr_url; free(tmp); tmp = pool->stratum_port; pool->stratum_port = stratum_port; free(tmp); mutex_unlock(&pool->stratum_lock); if (!restart_stratum(pool)) { pool_failed(pool); return false; } return true; } Commit Message: Do some random sanity checking for stratum message parsing CWE ID: CWE-119 Target: 1 Example 2: Code: static bool login_via_cert(PgSocket *client) { struct tls *tls = client->sbuf.tls; struct tls_cert *cert; struct tls_cert_dname *subj; if (!tls) { disconnect_client(client, true, "TLS connection required"); return false; } if (tls_get_peer_cert(client->sbuf.tls, &cert, NULL) < 0 || !cert) { disconnect_client(client, true, "TLS client certificate required"); return false; } subj = &cert->subject; log_debug("TLS cert login: CN=%s/C=%s/L=%s/ST=%s/O=%s/OU=%s", subj->common_name ? subj->common_name : "(null)", subj->country_name ? subj->country_name : "(null)", subj->locality_name ? subj->locality_name : "(null)", subj->state_or_province_name ? subj->state_or_province_name : "(null)", subj->organization_name ? subj->organization_name : "(null)", subj->organizational_unit_name ? subj->organizational_unit_name : "(null)"); if (!subj->common_name) { disconnect_client(client, true, "Invalid TLS certificate"); goto fail; } if (strcmp(subj->common_name, client->auth_user->name) != 0) { disconnect_client(client, true, "TLS certificate name mismatch"); goto fail; } tls_cert_free(cert); /* login successful */ return finish_client_login(client); fail: tls_cert_free(cert); return false; } Commit Message: Remove too early set of auth_user When query returns 0 rows (user not found), this user stays as login user... Should fix #69. CWE ID: CWE-287 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int sm_looptest_show_loop_paths(p_fm_config_conx_hdlt hdl, fm_mgr_type_t mgr, int argc, char *argv[]) { fm_mgr_config_errno_t res; fm_msg_ret_code_t ret_code; fm_config_interation_data_t interationData; uint8_t data[BUF_SZ]; int index = -1; int start; if (argc > 1) { printf("Error: only 1 argument expected\n"); return 0; } if (argc == 1) { index = atol(argv[0]); } memset(&interationData, 0, sizeof(fm_config_interation_data_t)); interationData.start = start = 1; interationData.index = index; while (!interationData.done) { memcpy(data, &interationData, sizeof(fm_config_interation_data_t)); if((res = fm_mgr_simple_query(hdl, FM_ACT_GET, FM_DT_SM_LOOP_TEST_SHOW_PATHS, mgr, BUF_SZ, data, &ret_code)) != FM_CONF_OK) { fprintf(stderr, "sm_looptest_show_loop_paths: Failed to retrieve data: \n" "\tError:(%d) %s \n\tRet code:(%d) %s\n", res, fm_mgr_get_error_str(res),ret_code, fm_mgr_get_resp_error_str(ret_code)); return 0; } if (start) { if (index == -1) printf("Successfully sent Loop Test Path show for node index (all) to local SM instance\n"); else printf("Successfully sent Loop Test Path show for node index %d to local SM instance\n", index); start = 0; } memcpy(&interationData, data, sizeof(fm_config_interation_data_t)); printf("%s", interationData.intermediateBuffer); } return 0; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int userfaultfd_unregister(struct userfaultfd_ctx *ctx, unsigned long arg) { struct mm_struct *mm = ctx->mm; struct vm_area_struct *vma, *prev, *cur; int ret; struct uffdio_range uffdio_unregister; unsigned long new_flags; bool found; unsigned long start, end, vma_end; const void __user *buf = (void __user *)arg; ret = -EFAULT; if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister))) goto out; ret = validate_range(mm, uffdio_unregister.start, uffdio_unregister.len); if (ret) goto out; start = uffdio_unregister.start; end = start + uffdio_unregister.len; ret = -ENOMEM; if (!mmget_not_zero(mm)) goto out; down_write(&mm->mmap_sem); vma = find_vma_prev(mm, start, &prev); if (!vma) goto out_unlock; /* check that there's at least one vma in the range */ ret = -EINVAL; if (vma->vm_start >= end) goto out_unlock; /* * If the first vma contains huge pages, make sure start address * is aligned to huge page size. */ if (is_vm_hugetlb_page(vma)) { unsigned long vma_hpagesize = vma_kernel_pagesize(vma); if (start & (vma_hpagesize - 1)) goto out_unlock; } /* * Search for not compatible vmas. */ found = false; ret = -EINVAL; for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { cond_resched(); BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); /* * Check not compatible vmas, not strictly required * here as not compatible vmas cannot have an * userfaultfd_ctx registered on them, but this * provides for more strict behavior to notice * unregistration errors. */ if (!vma_can_userfault(cur)) goto out_unlock; found = true; } BUG_ON(!found); if (vma->vm_start < start) prev = vma; ret = 0; do { cond_resched(); BUG_ON(!vma_can_userfault(vma)); /* * Nothing to do: this vma is already registered into this * userfaultfd and with the right tracking mode too. */ if (!vma->vm_userfaultfd_ctx.ctx) goto skip; if (vma->vm_start > start) start = vma->vm_start; vma_end = min(end, vma->vm_end); if (userfaultfd_missing(vma)) { /* * Wake any concurrent pending userfault while * we unregister, so they will not hang * permanently and it avoids userland to call * UFFDIO_WAKE explicitly. */ struct userfaultfd_wake_range range; range.start = start; range.len = vma_end - start; wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range); } new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP); prev = vma_merge(mm, prev, start, vma_end, new_flags, vma->anon_vma, vma->vm_file, vma->vm_pgoff, vma_policy(vma), NULL_VM_UFFD_CTX); if (prev) { vma = prev; goto next; } if (vma->vm_start < start) { ret = split_vma(mm, vma, start, 1); if (ret) break; } if (vma->vm_end > end) { ret = split_vma(mm, vma, end, 0); if (ret) break; } next: /* * In the vma_merge() successful mprotect-like case 8: * the next vma was merged into the current one and * the current one has not been updated yet. */ vma->vm_flags = new_flags; vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; skip: prev = vma; start = vma->vm_end; vma = vma->vm_next; } while (vma && vma->vm_start < end); out_unlock: up_write(&mm->mmap_sem); mmput(mm); out: return ret; } Commit Message: userfaultfd: shmem/hugetlbfs: only allow to register VM_MAYWRITE vmas After the VMA to register the uffd onto is found, check that it has VM_MAYWRITE set before allowing registration. This way we inherit all common code checks before allowing to fill file holes in shmem and hugetlbfs with UFFDIO_COPY. The userfaultfd memory model is not applicable for readonly files unless it's a MAP_PRIVATE. Link: http://lkml.kernel.org/r/[email protected] Fixes: ff62a3421044 ("hugetlb: implement memfd sealing") Signed-off-by: Andrea Arcangeli <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Hugh Dickins <[email protected]> Reported-by: Jann Horn <[email protected]> Fixes: 4c27fe4c4c84 ("userfaultfd: shmem: add shmem_mcopy_atomic_pte for userfaultfd support") Cc: <[email protected]> Cc: "Dr. David Alan Gilbert" <[email protected]> Cc: Mike Kravetz <[email protected]> Cc: Peter Xu <[email protected]> Cc: [email protected] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: Target: 1 Example 2: Code: nlmsvc_notify_blocked(struct file_lock *fl) { struct nlm_block *block; dprintk("lockd: VFS unblock notification for block %p\n", fl); spin_lock(&nlm_blocked_lock); list_for_each_entry(block, &nlm_blocked, b_list) { if (nlm_compare_locks(&block->b_call->a_args.lock.fl, fl)) { nlmsvc_insert_block_locked(block, 0); spin_unlock(&nlm_blocked_lock); svc_wake_up(block->b_daemon); return; } } spin_unlock(&nlm_blocked_lock); printk(KERN_WARNING "lockd: notification for unknown block!\n"); } 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 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHPAPI php_stream *_php_stream_memory_create(int mode STREAMS_DC TSRMLS_DC) { php_stream_memory_data *self; php_stream *stream; self = emalloc(sizeof(*self)); self->data = NULL; self->fpos = 0; self->fsize = 0; self->smax = ~0u; self->mode = mode; stream = php_stream_alloc_rel(&php_stream_memory_ops, self, 0, mode & TEMP_STREAM_READONLY ? "rb" : "w+b"); stream->flags |= PHP_STREAM_FLAG_NO_BUFFER; return stream; } Commit Message: CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { int i; if (old->curframe != cur->curframe) return false; /* for states to be equal callsites have to be the same * and all frame states need to be equivalent */ for (i = 0; i <= old->curframe; i++) { if (old->frame[i]->callsite != cur->frame[i]->callsite) return false; if (!func_states_equal(old->frame[i], cur->frame[i])) return false; } return true; } Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: static inline long calc_load_fold_idle(void) { return 0; } 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 <[email protected]> Reported-by: Bjoern B. Brandenburg <[email protected]> Tested-by: Yong Zhang <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: [email protected] LKML-Reference: <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool LayerTreeCoordinator::layerTreeTileUpdatesAllowed() const { return !m_isSuspended && !m_waitingForUIProcess; } Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases https://bugs.webkit.org/show_bug.cgi?id=95072 Reviewed by Jocelyn Turcotte. Release graphic buffers that haven't been used for a while in order to save memory. This way we can give back memory to the system when no user interaction happens after a period of time, for example when we are in the background. * Shared/ShareableBitmap.h: * WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp: (WebKit::LayerTreeCoordinator::LayerTreeCoordinator): (WebKit::LayerTreeCoordinator::beginContentUpdate): (WebKit): (WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases): (WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired): * WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h: (LayerTreeCoordinator): * WebProcess/WebPage/UpdateAtlas.cpp: (WebKit::UpdateAtlas::UpdateAtlas): (WebKit::UpdateAtlas::didSwapBuffers): Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer and this way we can track whether this atlas is used with m_areaAllocator. (WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer): * WebProcess/WebPage/UpdateAtlas.h: (WebKit::UpdateAtlas::addTimeInactive): (WebKit::UpdateAtlas::isInactive): (WebKit::UpdateAtlas::isInUse): (UpdateAtlas): git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool LauncherView::IsShowingMenu() const { #if !defined(OS_MACOSX) return (overflow_menu_runner_.get() && overflow_menu_runner_->IsRunning()) || (launcher_menu_runner_.get() && launcher_menu_runner_->IsRunning()); #endif return false; } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: long FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp) { char *ospath; fileHandle_t f = 0; if ( !fs_searchpaths ) { Com_Error( ERR_FATAL, "Filesystem call made without initialization" ); } f = FS_HandleForFile(); fsh[f].zipFile = qfalse; Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); S_ClearSoundBuffer(); ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); ospath[strlen(ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath ); } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" ); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { if (Q_stricmp(fs_homepath->string,fs_basepath->string)) { ospath = FS_BuildOSPath( fs_basepath->string, filename, "" ); ospath[strlen(ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath ); } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" ); fsh[f].handleSync = qfalse; } if (!fsh[f].handleFiles.file.o && fs_steampath->string[0]) { ospath = FS_BuildOSPath( fs_steampath->string, filename, "" ); ospath[strlen(ospath)-1] = '\0'; if ( fs_debug->integer ) { Com_Printf( "FS_SV_FOpenFileRead (fs_steampath): %s\n", ospath ); } fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" ); fsh[f].handleSync = qfalse; } if ( !fsh[f].handleFiles.file.o ) { f = 0; } } *fp = f; if (f) { return FS_filelength(f); } return -1; } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct kvm_assigned_dev_kernel *kvm_find_assigned_dev(struct list_head *head, int assigned_dev_id) { struct list_head *ptr; struct kvm_assigned_dev_kernel *match; list_for_each(ptr, head) { match = list_entry(ptr, struct kvm_assigned_dev_kernel, list); if (match->assigned_dev_id == assigned_dev_id) return match; } return NULL; } Commit Message: KVM: Device assignment permission checks (cherry picked from commit 3d27e23b17010c668db311140b17bbbb70c78fb9) Only allow KVM device assignment to attach to devices which: - Are not bridges - Have BAR resources (assume others are special devices) - The user has permissions to use Assigning a bridge is a configuration error, it's not supported, and typically doesn't result in the behavior the user is expecting anyway. Devices without BAR resources are typically chipset components that also don't have host drivers. We don't want users to hold such devices captive or cause system problems by fencing them off into an iommu domain. We determine "permission to use" by testing whether the user has access to the PCI sysfs resource files. By default a normal user will not have access to these files, so it provides a good indication that an administration agent has granted the user access to the device. [Yang Bai: add missing #include] [avi: fix comment style] Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Yang Bai <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __vcpu_run(struct kvm_vcpu *vcpu) { int r; struct kvm *kvm = vcpu->kvm; vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); r = vapic_enter(vcpu); if (r) { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); return r; } r = 1; while (r > 0) { if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE && !vcpu->arch.apf.halted) r = vcpu_enter_guest(vcpu); else { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); kvm_vcpu_block(vcpu); vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) { kvm_apic_accept_events(vcpu); switch(vcpu->arch.mp_state) { case KVM_MP_STATE_HALTED: vcpu->arch.pv.pv_unhalted = false; vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; case KVM_MP_STATE_RUNNABLE: vcpu->arch.apf.halted = false; break; case KVM_MP_STATE_INIT_RECEIVED: break; default: r = -EINTR; break; } } } if (r <= 0) break; clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests); if (kvm_cpu_has_pending_timer(vcpu)) kvm_inject_pending_timer_irqs(vcpu); if (dm_request_for_irq_injection(vcpu)) { r = -EINTR; vcpu->run->exit_reason = KVM_EXIT_INTR; ++vcpu->stat.request_irq_exits; } kvm_check_async_pf_completion(vcpu); if (signal_pending(current)) { r = -EINTR; vcpu->run->exit_reason = KVM_EXIT_INTR; ++vcpu->stat.signal_exits; } if (need_resched()) { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); kvm_resched(vcpu); vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); } } srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); vapic_exit(vcpu); return r; } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static struct inode *alloc_inode(struct super_block *sb) { struct inode *inode; if (sb->s_op->alloc_inode) inode = sb->s_op->alloc_inode(sb); else inode = kmem_cache_alloc(inode_cachep, GFP_KERNEL); if (!inode) return NULL; if (unlikely(inode_init_always(sb, inode))) { if (inode->i_sb->s_op->destroy_inode) inode->i_sb->s_op->destroy_inode(inode); else kmem_cache_free(inode_cachep, inode); return NULL; } return inode; } Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid The kernel has no concept of capabilities with respect to inodes; inodes exist independently of namespaces. For example, inode_capable(inode, CAP_LINUX_IMMUTABLE) would be nonsense. This patch changes inode_capable to check for uid and gid mappings and renames it to capable_wrt_inode_uidgid, which should make it more obvious what it does. Fixes CVE-2014-4014. Cc: Theodore Ts'o <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Dave Chinner <[email protected]> Cc: [email protected] Signed-off-by: Andy Lutomirski <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) { char *s; char *c; int challenge = 0; MSG_BeginReadingOOB( msg ); MSG_ReadLong( msg ); // skip the -1 s = MSG_ReadStringLine( msg ); Cmd_TokenizeString( s ); c = Cmd_Argv( 0 ); Com_DPrintf ("CL packet %s: %s\n", NET_AdrToStringwPort(from), c); if (!Q_stricmp(c, "challengeResponse")) { char *strver; int ver; if (clc.state != CA_CONNECTING) { Com_DPrintf("Unwanted challenge response received. Ignored.\n"); return; } c = Cmd_Argv( 2 ); if(*c) challenge = atoi(c); strver = Cmd_Argv( 3 ); if(*strver) { ver = atoi(strver); if(ver != com_protocol->integer) { #ifdef LEGACY_PROTOCOL if(com_legacyprotocol->integer > 0) { clc.compat = qtrue; Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, " "we have %d. Trying legacy protocol %d.\n", ver, com_protocol->integer, com_legacyprotocol->integer); } else #endif { Com_Printf(S_COLOR_YELLOW "Warning: Server reports protocol version %d, we have %d. " "Trying anyways.\n", ver, com_protocol->integer); } } } #ifdef LEGACY_PROTOCOL else clc.compat = qtrue; if(clc.compat) { if(!NET_CompareAdr(from, clc.serverAddress)) { if(!*c || challenge != clc.challenge) { Com_DPrintf("Challenge response received from unexpected source. Ignored.\n"); return; } } } else #endif { if(!*c || challenge != clc.challenge) { Com_Printf("Bad challenge for challengeResponse. Ignored.\n"); return; } } clc.challenge = atoi(Cmd_Argv(1)); clc.state = CA_CHALLENGING; clc.connectPacketCount = 0; clc.connectTime = -99999; clc.serverAddress = from; Com_DPrintf ("challengeResponse: %d\n", clc.challenge); return; } if ( !Q_stricmp( c, "connectResponse" ) ) { if ( clc.state >= CA_CONNECTED ) { Com_Printf( "Dup connect received. Ignored.\n" ); return; } if ( clc.state != CA_CHALLENGING ) { Com_Printf( "connectResponse packet while not connecting. Ignored.\n" ); return; } if ( !NET_CompareAdr( from, clc.serverAddress ) ) { Com_Printf( "connectResponse from wrong address. Ignored.\n" ); return; } #ifdef LEGACY_PROTOCOL if(!clc.compat) #endif { c = Cmd_Argv(1); if(*c) challenge = atoi(c); else { Com_Printf("Bad connectResponse received. Ignored.\n"); return; } if(challenge != clc.challenge) { Com_Printf("ConnectResponse with bad challenge received. Ignored.\n"); return; } } #ifdef LEGACY_PROTOCOL Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"), clc.challenge, clc.compat); #else Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport"), clc.challenge, qfalse); #endif clc.state = CA_CONNECTED; clc.lastPacketSentTime = -9999; // send first packet immediately return; } if ( !Q_stricmp( c, "infoResponse" ) ) { CL_ServerInfoPacket( from, msg ); return; } if ( !Q_stricmp( c, "statusResponse" ) ) { CL_ServerStatusResponse( from, msg ); return; } if ( !Q_stricmp( c, "echo" ) ) { NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv( 1 ) ); return; } if ( !Q_stricmp( c, "keyAuthorize" ) ) { return; } if ( !Q_stricmp( c, "motd" ) ) { CL_MotdPacket( from ); return; } if ( !Q_stricmp( c, "print" ) ) { s = MSG_ReadString( msg ); Q_strncpyz( clc.serverMessage, s, sizeof( clc.serverMessage ) ); Com_Printf( "%s", s ); return; } if ( !Q_strncmp( c, "getserversResponse", 18 ) ) { CL_ServersResponsePacket( &from, msg, qfalse ); return; } if ( !Q_strncmp(c, "getserversExtResponse", 21) ) { CL_ServersResponsePacket( &from, msg, qtrue ); return; } Com_DPrintf( "Unknown connectionless packet command.\n" ); } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChromeMockRenderThread::OnMsgOpenChannelToExtension( int routing_id, const std::string& source_extension_id, const std::string& target_extension_id, const std::string& channel_name, int* port_id) { *port_id = 0; } 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 Target: 1 Example 2: Code: char *am_htmlencode(request_rec *r, const char *str) { const char *cp; char *output; apr_size_t outputlen; int i; outputlen = 0; for (cp = str; *cp; cp++) { switch (*cp) { case '&': outputlen += 5; break; case '"': outputlen += 6; break; default: outputlen += 1; break; } } i = 0; output = apr_palloc(r->pool, outputlen + 1); for (cp = str; *cp; cp++) { switch (*cp) { case '&': (void)strcpy(&output[i], "&amp;"); i += 5; break; case '"': (void)strcpy(&output[i], "&quot;"); i += 6; break; default: output[i] = *cp; i += 1; break; } } output[i] = '\0'; return output; } Commit Message: Fix redirect URL validation bypass It turns out that browsers silently convert backslash characters into forward slashes, while apr_uri_parse() does not. This mismatch allows an attacker to bypass the redirect URL validation by using an URL like: https://sp.example.org/mellon/logout?ReturnTo=https:%5c%5cmalicious.example.org/ mod_auth_mellon will assume that it is a relative URL and allow the request to pass through, while the browsers will use it as an absolute url and redirect to https://malicious.example.org/ . This patch fixes this issue by rejecting all redirect URLs with backslashes. CWE ID: CWE-601 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void InitializePrinting(content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PRINT_PREVIEW) printing::PrintViewManager::CreateForWebContents(web_contents); printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents); #else printing::PrintViewManagerBasic::CreateForWebContents(web_contents); #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void gamma_composition_test(png_modifier *pm, PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth, PNG_CONST int palette_number, PNG_CONST int interlace_type, PNG_CONST double file_gamma, PNG_CONST double screen_gamma, PNG_CONST int use_input_precision, PNG_CONST int do_background, PNG_CONST int expand_16) { size_t pos = 0; png_const_charp base; double bg; char name[128]; png_color_16 background; /* Make up a name and get an appropriate background gamma value. */ switch (do_background) { default: base = ""; bg = 4; /* should not be used */ break; case PNG_BACKGROUND_GAMMA_SCREEN: base = " bckg(Screen):"; bg = 1/screen_gamma; break; case PNG_BACKGROUND_GAMMA_FILE: base = " bckg(File):"; bg = file_gamma; break; case PNG_BACKGROUND_GAMMA_UNIQUE: base = " bckg(Unique):"; /* This tests the handling of a unique value, the math is such that the * value tends to be <1, but is neither screen nor file (even if they * match!) */ bg = (file_gamma + screen_gamma) / 3; break; #ifdef PNG_READ_ALPHA_MODE_SUPPORTED case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG: base = " alpha(PNG)"; bg = 4; /* should not be used */ break; case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD: base = " alpha(Porter-Duff)"; bg = 4; /* should not be used */ break; case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED: base = " alpha(Optimized)"; bg = 4; /* should not be used */ break; case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN: base = " alpha(Broken)"; bg = 4; /* should not be used */ break; #endif } /* Use random background values - the background is always presented in the * output space (8 or 16 bit components). */ if (expand_16 || bit_depth == 16) { png_uint_32 r = random_32(); background.red = (png_uint_16)r; background.green = (png_uint_16)(r >> 16); r = random_32(); background.blue = (png_uint_16)r; background.gray = (png_uint_16)(r >> 16); /* In earlier libpng versions, those where DIGITIZE is set, any background * gamma correction in the expand16 case was done using 8-bit gamma * correction tables, resulting in larger errors. To cope with those * cases use a 16-bit background value which will handle this gamma * correction. */ # if DIGITIZE if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE || do_background == PNG_BACKGROUND_GAMMA_FILE) && fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD) { /* The background values will be looked up in an 8-bit table to do * the gamma correction, so only select values which are an exact * match for the 8-bit table entries: */ background.red = (png_uint_16)((background.red >> 8) * 257); background.green = (png_uint_16)((background.green >> 8) * 257); background.blue = (png_uint_16)((background.blue >> 8) * 257); background.gray = (png_uint_16)((background.gray >> 8) * 257); } # endif } else /* 8 bit colors */ { png_uint_32 r = random_32(); background.red = (png_byte)r; background.green = (png_byte)(r >> 8); background.blue = (png_byte)(r >> 16); background.gray = (png_byte)(r >> 24); } background.index = 193; /* rgb(193,193,193) to detect errors */ if (!(colour_type & PNG_COLOR_MASK_COLOR)) { /* Grayscale input, we do not convert to RGB (TBD), so we must set the * background to gray - else libpng seems to fail. */ background.red = background.green = background.blue = background.gray; } pos = safecat(name, sizeof name, pos, "gamma "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "->"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); pos = safecat(name, sizeof name, pos, base); if (do_background < ALPHA_MODE_OFFSET) { /* Include the background color and gamma in the name: */ pos = safecat(name, sizeof name, pos, "("); /* This assumes no expand gray->rgb - the current code won't handle that! */ if (colour_type & PNG_COLOR_MASK_COLOR) { pos = safecatn(name, sizeof name, pos, background.red); pos = safecat(name, sizeof name, pos, ","); pos = safecatn(name, sizeof name, pos, background.green); pos = safecat(name, sizeof name, pos, ","); pos = safecatn(name, sizeof name, pos, background.blue); } else pos = safecatn(name, sizeof name, pos, background.gray); pos = safecat(name, sizeof name, pos, ")^"); pos = safecatd(name, sizeof name, pos, bg, 3); } gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type, file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision, 0/*strip 16*/, expand_16, do_background, &background, bg); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: armv6pmu_disable_event(struct hw_perf_event *hwc, int idx) { unsigned long val, mask, evt, flags; if (ARMV6_CYCLE_COUNTER == idx) { mask = ARMV6_PMCR_CCOUNT_IEN; evt = 0; } else if (ARMV6_COUNTER0 == idx) { mask = ARMV6_PMCR_COUNT0_IEN | ARMV6_PMCR_EVT_COUNT0_MASK; evt = ARMV6_PERFCTR_NOP << ARMV6_PMCR_EVT_COUNT0_SHIFT; } else if (ARMV6_COUNTER1 == idx) { mask = ARMV6_PMCR_COUNT1_IEN | ARMV6_PMCR_EVT_COUNT1_MASK; evt = ARMV6_PERFCTR_NOP << ARMV6_PMCR_EVT_COUNT1_SHIFT; } else { WARN_ONCE(1, "invalid counter number (%d)\n", idx); return; } /* * Mask out the current event and set the counter to count the number * of ETM bus signal assertion cycles. The external reporting should * be disabled and so this should never increment. */ raw_spin_lock_irqsave(&pmu_lock, flags); val = armv6_pmcr_read(); val &= ~mask; val |= evt; armv6_pmcr_write(val); raw_spin_unlock_irqrestore(&pmu_lock, flags); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WorkerProcessLauncherTest::LaunchProcess( IPC::Listener* delegate, ScopedHandle* process_exit_event_out) { process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL)); if (!process_exit_event_.IsValid()) return false; channel_name_ = GenerateIpcChannelName(this); if (!CreateIpcChannel(channel_name_, kIpcSecurityDescriptor, task_runner_, delegate, &channel_server_)) { return false; } exit_code_ = STILL_ACTIVE; return DuplicateHandle(GetCurrentProcess(), process_exit_event_, GetCurrentProcess(), process_exit_event_out->Receive(), 0, FALSE, DUPLICATE_SAME_ACCESS) != FALSE; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EntrySync* EntrySync::moveTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const { RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create(); m_fileSystem->move(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return helper->getResult(exceptionState); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose) { return X509_PURPOSE_set(&param->purpose, purpose); } Commit Message: Call strlen() if name length provided is 0, like OpenSSL does. Issue notice by Christian Heimes <[email protected]> ok deraadt@ jsing@ CWE ID: CWE-295 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ssize_t partial_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_PARTIAL); } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const { return url.SchemeIs(chrome::kChromeDevToolsScheme) || url.SchemeIs(chrome::kChromeInternalScheme) || url.SchemeIs(chrome::kChromeUIScheme); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: static void *zend_mm_alloc_huge(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { #ifdef ZEND_WIN32 /* On Windows we don't have ability to extend huge blocks in-place. * We allocate them with 2MB size granularity, to avoid many * reallocations when they are extended by small pieces */ size_t new_size = ZEND_MM_ALIGNED_SIZE_EX(size, MAX(REAL_PAGE_SIZE, ZEND_MM_CHUNK_SIZE)); #else size_t new_size = ZEND_MM_ALIGNED_SIZE_EX(size, REAL_PAGE_SIZE); #endif void *ptr; #if ZEND_MM_LIMIT if (UNEXPECTED(heap->real_size + new_size > heap->limit)) { if (zend_mm_gc(heap) && heap->real_size + new_size <= heap->limit) { /* pass */ } else if (heap->overflow == 0) { #if ZEND_DEBUG zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)", heap->limit, __zend_filename, __zend_lineno, size); #else zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)", heap->limit, size); #endif return NULL; } } #endif ptr = zend_mm_chunk_alloc(heap, new_size, ZEND_MM_CHUNK_SIZE); if (UNEXPECTED(ptr == NULL)) { /* insufficient memory */ if (zend_mm_gc(heap) && (ptr = zend_mm_chunk_alloc(heap, new_size, ZEND_MM_CHUNK_SIZE)) != NULL) { /* pass */ } else { #if !ZEND_MM_LIMIT zend_mm_safe_error(heap, "Out of memory"); #elif ZEND_DEBUG zend_mm_safe_error(heap, "Out of memory (allocated %zu) at %s:%d (tried to allocate %zu bytes)", heap->real_size, __zend_filename, __zend_lineno, size); #else zend_mm_safe_error(heap, "Out of memory (allocated %zu) (tried to allocate %zu bytes)", heap->real_size, size); #endif return NULL; } } #if ZEND_DEBUG zend_mm_add_huge_block(heap, ptr, new_size, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #else zend_mm_add_huge_block(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #endif #if ZEND_MM_STAT do { size_t size = heap->real_size + new_size; size_t peak = MAX(heap->real_peak, size); heap->real_size = size; heap->real_peak = peak; } while (0); do { size_t size = heap->size + new_size; size_t peak = MAX(heap->peak, size); heap->size = size; heap->peak = peak; } while (0); #elif ZEND_MM_LIMIT heap->real_size += new_size; #endif return ptr; } Commit Message: Fix bug #72742 - memory allocator fails to realloc small block to large one CWE ID: CWE-190 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> setter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::Local<v8::Value> argv[] = { v8Value }; v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(setter), scriptState->getExecutionContext(), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className); block.ReThrow(); return false; } return true; } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; } Commit Message: avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error Fixes: Null pointer dereference Fixes: CVE-2017-9608 Found-by: Yihan Lian Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: GF_Err gf_isom_svc_config_del(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex) { return gf_isom_svc_mvc_config_del(the_file, trackNumber, DescriptionIndex, GF_FALSE); } Commit Message: fix some exploitable overflows (#994, #997) CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool layoutTestMode() { return LayoutTestSupport::isRunningLayoutTest(); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (!src_known && opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { __mark_reg_unknown(dst_reg); return 0; } switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_ARSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* Upon reaching here, src_known is true and * umax_val is equal to umin_val. */ dst_reg->smin_value >>= umin_val; dst_reg->smax_value >>= umin_val; dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); /* blow away the dst_reg umin_value/umax_value and rely on * dst_reg var_off to refine the result. */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } Commit Message: bpf: 32-bit RSH verification must truncate input before the ALU op When I wrote commit 468f6eafa6c4 ("bpf: fix 32-bit ALU op verification"), I assumed that, in order to emulate 64-bit arithmetic with 32-bit logic, it is sufficient to just truncate the output to 32 bits; and so I just moved the register size coercion that used to be at the start of the function to the end of the function. That assumption is true for almost every op, but not for 32-bit right shifts, because those can propagate information towards the least significant bit. Fix it by always truncating inputs for 32-bit ops to 32 bits. Also get rid of the coerce_reg_to_size() after the ALU op, since that has no effect. Fixes: 468f6eafa6c4 ("bpf: fix 32-bit ALU op verification") Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: void transit_unintern(struct transit *transit) { if (transit->refcnt) transit->refcnt--; if (transit->refcnt == 0) { hash_release(transit_hash, transit); transit_free(transit); } } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[email protected]> CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TouchEventHandler::doFatFingers(Platform::TouchPoint& point) { m_lastScreenPoint = point.m_screenPos; m_lastFatFingersResult.reset(); // Theoretically this shouldn't be required. Keep it just in case states get mangled. IntPoint contentPos(m_webPage->mapFromViewportToContents(point.m_pos)); m_webPage->postponeDocumentStyleRecalc(); m_lastFatFingersResult = FatFingers(m_webPage, contentPos, FatFingers::ClickableElement).findBestPoint(); m_webPage->resumeDocumentStyleRecalc(); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: int SetSSLVersion(int connection_status, int version) { connection_status &= ~(net::SSL_CONNECTION_VERSION_MASK << net::SSL_CONNECTION_VERSION_SHIFT); int bitmask = version << net::SSL_CONNECTION_VERSION_SHIFT; return bitmask | connection_status; } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), web_gl_version_(web_gl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: spnego_gss_get_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token) { OM_uint32 ret; ret = gss_get_mic(minor_status, context_handle, qop_req, message_buffer, message_token); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18 Target: 1 Example 2: Code: static void blitter_set_rectangle(struct vrend_blitter_ctx *blit_ctx, int x1, int y1, int x2, int y2, float depth) { int i; /* set vertex positions */ blit_ctx->vertices[0][0][0] = (float)x1 / blit_ctx->dst_width * 2.0f - 1.0f; /*v0.x*/ blit_ctx->vertices[0][0][1] = (float)y1 / blit_ctx->dst_height * 2.0f - 1.0f; /*v0.y*/ blit_ctx->vertices[1][0][0] = (float)x2 / blit_ctx->dst_width * 2.0f - 1.0f; /*v1.x*/ blit_ctx->vertices[1][0][1] = (float)y1 / blit_ctx->dst_height * 2.0f - 1.0f; /*v1.y*/ blit_ctx->vertices[2][0][0] = (float)x2 / blit_ctx->dst_width * 2.0f - 1.0f; /*v2.x*/ blit_ctx->vertices[2][0][1] = (float)y2 / blit_ctx->dst_height * 2.0f - 1.0f; /*v2.y*/ blit_ctx->vertices[3][0][0] = (float)x1 / blit_ctx->dst_width * 2.0f - 1.0f; /*v3.x*/ blit_ctx->vertices[3][0][1] = (float)y2 / blit_ctx->dst_height * 2.0f - 1.0f; /*v3.y*/ for (i = 0; i < 4; i++) blit_ctx->vertices[i][0][2] = depth; /*z*/ glViewport(0, 0, blit_ctx->dst_width, blit_ctx->dst_height); } Commit Message: CWE ID: CWE-772 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) { OnUpdateWebPreferences(preferences); } Commit Message: Let the browser handle external navigations from DevTools. BUG=180555 Review URL: https://chromiumcodereview.appspot.com/12531004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@186793 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->GetAppListTargetVisibility()) return AUTO_HIDE_SHOWN; if (shell->system_tray() && shell->system_tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; if (launcher_widget()->IsActive() || status_->IsActive()) return AUTO_HIDE_SHOWN; if (event_filter_.get() && event_filter_->in_mouse_drag()) return AUTO_HIDE_HIDDEN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: std::unique_ptr<base::DictionaryValue> SerializeTarget( scoped_refptr<DevToolsAgentHost> host) { std::unique_ptr<base::DictionaryValue> dictionary( new base::DictionaryValue()); dictionary->SetString(kTargetIdField, host->GetId()); dictionary->SetString(kTargetTitleField, host->GetTitle()); dictionary->SetBoolean(kTargetAttachedField, host->IsAttached()); dictionary->SetString(kTargetUrlField, host->GetURL().spec()); std::string type = host->GetType(); if (type == DevToolsAgentHost::kTypePage) { int tab_id = extensions::ExtensionTabUtil::GetTabId(host->GetWebContents()); dictionary->SetInteger(kTargetTabIdField, tab_id); } else if (type == ChromeDevToolsManagerDelegate::kTypeBackgroundPage) { dictionary->SetString(kTargetExtensionIdField, host->GetURL().host()); } if (type == DevToolsAgentHost::kTypeServiceWorker || type == DevToolsAgentHost::kTypeSharedWorker) { type = kTargetTypeWorker; } dictionary->SetString(kTargetTypeField, type); GURL favicon_url = host->GetFaviconURL(); if (favicon_url.is_valid()) dictionary->SetString(kTargetFaviconUrlField, favicon_url.spec()); return dictionary; } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int nfs4_xdr_dec_open_downgrade(struct rpc_rqst *rqstp, __be32 *p, struct nfs_closeres *res) { struct xdr_stream xdr; struct compound_hdr hdr; int status; xdr_init_decode(&xdr, &rqstp->rq_rcv_buf, p); status = decode_compound_hdr(&xdr, &hdr); if (status) goto out; status = decode_putfh(&xdr); if (status) goto out; status = decode_open_downgrade(&xdr, res); if (status != 0) goto out; decode_getfattr(&xdr, res->fattr, res->server); out: return status; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs) { pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel); void *memory; if (dma_alloc_from_coherent(dev, size, handle, &memory)) return memory; return __dma_alloc(dev, size, handle, gfp, prot, false, __builtin_return_address(0)); } Commit Message: ARM: dma-mapping: don't allow DMA mappings to be marked executable DMA mapping permissions were being derived from pgprot_kernel directly without using PAGE_KERNEL. This causes them to be marked with executable permission, which is not what we want. Fix this. Signed-off-by: Russell King <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void OnHttpHeaderReceived(const std::string& header, const std::string& value, int child_process_id, content::ResourceContext* resource_context, OnHeaderProcessedCallback callback) { std::move(callback).Run(HeaderInterceptorResult::KILL); } Commit Message: Lock down blob/filesystem URL creation with a stronger CPSP::CanCommitURL() ChildProcessSecurityPolicy::CanCommitURL() is a security check that's supposed to tell whether a given renderer process is allowed to commit a given URL. It is currently used to validate (1) blob and filesystem URL creation, and (2) Origin headers. Currently, it has scheme-based checks that disallow things like web renderers creating blob/filesystem URLs in chrome-extension: origins, but it cannot stop one web origin from creating those URLs for another origin. This CL locks down its use for (1) to also consult CanAccessDataForOrigin(). With site isolation, this will check origin locks and ensure that foo.com cannot create blob/filesystem URLs for other origins. For now, this CL does not provide the same enforcements for (2), Origin header validation, which has additional constraints that need to be solved first (see https://crbug.com/515309). Bug: 886976, 888001 Change-Id: I743ef05469e4000b2c0bee840022162600cc237f Reviewed-on: https://chromium-review.googlesource.com/1235343 Commit-Queue: Alex Moshchuk <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#594914} CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static authz_status lua_authz_check(request_rec *r, const char *require_line, const void *parsed_require_line) { apr_pool_t *pool; ap_lua_vm_spec *spec; lua_State *L; ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config, &lua_module); const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config, &lua_module); const lua_authz_provider_spec *prov_spec = parsed_require_line; int result; int nargs = 0; spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name, NULL, 0, prov_spec->function_name, "authz provider"); L = ap_lua_get_lua_state(pool, spec, r); if (L == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314) "Unable to compile VM for authz provider %s", prov_spec->name); return AUTHZ_GENERAL_ERROR; } lua_getglobal(L, prov_spec->function_name); if (!lua_isfunction(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319) "Unable to find entry function '%s' in %s (not a valid function)", prov_spec->function_name, prov_spec->file_name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } ap_lua_run_lua_request(L, r); if (prov_spec->args) { int i; if (!lua_checkstack(L, prov_spec->args->nelts)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315) "Error: authz provider %s: too many arguments", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } for (i = 0; i < prov_spec->args->nelts; i++) { const char *arg = APR_ARRAY_IDX(prov_spec->args, i, const char *); lua_pushstring(L, arg); } nargs = prov_spec->args->nelts; } if (lua_pcall(L, 1 + nargs, 1, 0)) { const char *err = lua_tostring(L, -1); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316) "Error executing authz provider %s: %s", prov_spec->name, err); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } if (!lua_isnumber(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317) "Error: authz provider %s did not return integer", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } result = lua_tointeger(L, -1); ap_lua_release_state(L, spec, r); switch (result) { case AUTHZ_DENIED: case AUTHZ_GRANTED: case AUTHZ_NEUTRAL: case AUTHZ_GENERAL_ERROR: case AUTHZ_DENIED_NO_USER: return result; default: ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318) "Error: authz provider %s: invalid return value %d", prov_spec->name, result); } return AUTHZ_GENERAL_ERROR; } Commit Message: Merge r1642499 from trunk: *) SECURITY: CVE-2014-8109 (cve.mitre.org) mod_lua: Fix handling of the Require line when a LuaAuthzProvider is used in multiple Require directives with different arguments. PR57204 [Edward Lu <Chaosed0 gmail.com>] Submitted By: Edward Lu Committed By: covener Submitted by: covener Reviewed/backported by: jim git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool HTMLFormElement::prepareForSubmission(Event* event) { Frame* frame = document().frame(); if (m_isSubmittingOrPreparingForSubmission || !frame) return m_isSubmittingOrPreparingForSubmission; m_isSubmittingOrPreparingForSubmission = true; m_shouldSubmit = false; if (!validateInteractively(event)) { m_isSubmittingOrPreparingForSubmission = false; return false; } StringPairVector controlNamesAndValues; getTextFieldValues(controlNamesAndValues); RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), NotSubmittedByJavaScript); frame->loader()->client()->dispatchWillSendSubmitEvent(formState.release()); if (dispatchEvent(Event::createCancelableBubble(eventNames().submitEvent))) m_shouldSubmit = true; m_isSubmittingOrPreparingForSubmission = false; if (m_shouldSubmit) submit(event, true, true, NotSubmittedByJavaScript); return m_shouldSubmit; } Commit Message: Fix a crash in HTMLFormElement::prepareForSubmission. BUG=297478 TEST=automated with ASAN. Review URL: https://chromiumcodereview.appspot.com/24910003 git-svn-id: svn://svn.chromium.org/blink/trunk@158428 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: static void perf_group_detach(struct perf_event *event) { struct perf_event *sibling, *tmp; struct list_head *list = NULL; /* * We can have double detach due to exit/hot-unplug + close. */ if (!(event->attach_state & PERF_ATTACH_GROUP)) return; event->attach_state &= ~PERF_ATTACH_GROUP; /* * If this is a sibling, remove it from its group. */ if (event->group_leader != event) { list_del_init(&event->group_entry); event->group_leader->nr_siblings--; goto out; } if (!list_empty(&event->group_entry)) list = &event->group_entry; /* * If this was a group event with sibling events then * upgrade the siblings to singleton events by adding them * to whatever list we are on. */ list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) { if (list) list_move_tail(&sibling->group_entry, list); sibling->group_leader = sibling; /* Inherit group flags from the previous leader */ sibling->group_flags = event->group_flags; WARN_ON_ONCE(sibling->ctx != event->ctx); } out: perf_event__header_size(event->group_leader); list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry) perf_event__header_size(tmp); } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SpeechRecognitionManagerImpl::OnRecognitionResults( int session_id, const std::vector<blink::mojom::SpeechRecognitionResultPtr>& results) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!SessionExists(session_id)) return; if (SpeechRecognitionEventListener* delegate_listener = GetDelegateListener()) delegate_listener->OnRecognitionResults(session_id, results); if (SpeechRecognitionEventListener* listener = GetListener(session_id)) listener->OnRecognitionResults(session_id, results); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: const char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } Commit Message: Support all the new variables added CWE ID: CWE-264 Target: 1 Example 2: Code: void ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild) { ASSERT(newChild); ASSERT(nextChild.parentNode() == this); ASSERT(!newChild->isDocumentFragment()); ASSERT(!isHTMLTemplateElement(this)); if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do return; if (!checkParserAcceptChild(*newChild)) return; RefPtrWillBeRawPtr<Node> protect(this); while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode()) parent->parserRemoveChild(*newChild); if (nextChild.parentNode() != this) return; if (document() != newChild->document()) document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION); { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; treeScope().adoptIfNeeded(*newChild); insertBeforeCommon(nextChild, *newChild); newChild->updateAncestorConnectedSubframeCountForInsertion(); ChildListMutationScope(*this).childAdded(*newChild); } notifyNodeInserted(*newChild, ChildrenChangeSourceParser); } Commit Message: Fix an optimisation in ContainerNode::notifyNodeInsertedInternal [email protected] BUG=544020 Review URL: https://codereview.chromium.org/1420653003 Cr-Commit-Position: refs/heads/master@{#355240} CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int nfs4_setup_sequence(const struct nfs_server *server, struct nfs4_sequence_args *args, struct nfs4_sequence_res *res, int cache_reply, struct rpc_task *task) { struct nfs4_session *session = nfs4_get_session(server); int ret = 0; if (session == NULL) { args->sa_session = NULL; res->sr_session = NULL; goto out; } dprintk("--> %s clp %p session %p sr_slot %td\n", __func__, session->clp, session, res->sr_slot ? res->sr_slot - session->fc_slot_table.slots : -1); ret = nfs41_setup_sequence(session, args, res, cache_reply, task); out: dprintk("<-- %s status=%d\n", __func__, ret); return ret; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: [email protected] Signed-off-by: Andy Adamson <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void serveloop(GArray* servers) { struct sockaddr_storage addrin; socklen_t addrinlen=sizeof(addrin); int i; int max; fd_set mset; fd_set rset; /* * Set up the master fd_set. The set of descriptors we need * to select() for never changes anyway and it buys us a *lot* * of time to only build this once. However, if we ever choose * to not fork() for clients anymore, we may have to revisit * this. */ max=0; FD_ZERO(&mset); for(i=0;i<servers->len;i++) { int sock; if((sock=(g_array_index(servers, SERVER, i)).socket) >= 0) { FD_SET(sock, &mset); max=sock>max?sock:max; } } for(i=0;i<modernsocks->len;i++) { int sock = g_array_index(modernsocks, int, i); FD_SET(sock, &mset); max=sock>max?sock:max; } for(;;) { /* SIGHUP causes the root server process to reconfigure * itself and add new export servers for each newly * found export configuration group, i.e. spawn new * server processes for each previously non-existent * export. This does not alter old runtime configuration * but just appends new exports. */ if (is_sighup_caught) { int n; GError *gerror = NULL; msg(LOG_INFO, "reconfiguration request received"); is_sighup_caught = 0; /* Reset to allow catching * it again. */ n = append_new_servers(servers, &gerror); if (n == -1) msg(LOG_ERR, "failed to append new servers: %s", gerror->message); for (i = servers->len - n; i < servers->len; ++i) { const SERVER server = g_array_index(servers, SERVER, i); if (server.socket >= 0) { FD_SET(server.socket, &mset); max = server.socket > max ? server.socket : max; } msg(LOG_INFO, "reconfigured new server: %s", server.servename); } } memcpy(&rset, &mset, sizeof(fd_set)); if(select(max+1, &rset, NULL, NULL, NULL)>0) { int net; DEBUG("accept, "); for(i=0; i < modernsocks->len; i++) { int sock = g_array_index(modernsocks, int, i); if(!FD_ISSET(sock, &rset)) { continue; } CLIENT *client; if((net=accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0) { err_nonfatal("accept: %m"); continue; } client = negotiate(net, NULL, servers, NEG_INIT | NEG_MODERN); if(!client) { close(net); continue; } handle_connection(servers, net, client->server, client); } for(i=0; i < servers->len; i++) { SERVER *serve; serve=&(g_array_index(servers, SERVER, i)); if(serve->socket < 0) { continue; } if(FD_ISSET(serve->socket, &rset)) { if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) { err_nonfatal("accept: %m"); continue; } handle_connection(servers, net, serve, NULL); } } } } } Commit Message: nbd-server: handle modern-style negotiation in a child process Previously, the modern style negotiation was carried out in the root server (listener) process before forking the actual client handler. This made it possible for a malfunctioning or evil client to terminate the root process simply by querying a non-existent export or aborting in the middle of the negotation process (caused SIGPIPE in the server). This commit moves the negotiation process to the child to keep the root process up and running no matter what happens during the negotiation. See http://sourceforge.net/mailarchive/message.php?msg_id=30410146 Signed-off-by: Tuomas Räsänen <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static ssize_t lbs_failcount_read(struct file *file, char __user *userbuf, size_t count, loff_t *ppos) { return lbs_threshold_read(TLV_TYPE_FAILCOUNT, CMD_SUBSCRIBE_FAILCOUNT, file, userbuf, count, ppos); } Commit Message: libertas: potential oops in debugfs If we do a zero size allocation then it will oops. Also we can't be sure the user passes us a NUL terminated string so I've added a terminator. This code can only be triggered by root. Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Acked-by: Dan Williams <[email protected]> Signed-off-by: John W. Linville <[email protected]> CWE ID: CWE-189 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; void *shared_kaddr; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info *guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->time_page) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master <monotonic time, tsc value> tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; shared_kaddr = kmap_atomic(vcpu->time_page); guest_hv_clock = shared_kaddr + vcpu->time_offset; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); kunmap_atomic(shared_kaddr); mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT); return 0; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); const struct uac_to_guid { uint32_t uac; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; const char *error_string; } map[] = { { }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } }; Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: static int udf_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { int ret; ret = block_write_begin(mapping, pos, len, flags, pagep, udf_get_block); if (unlikely(ret)) udf_write_failed(mapping, pos + len); return ret; } Commit Message: udf: Avoid infinite loop when processing indirect ICBs We did not implement any bound on number of indirect ICBs we follow when loading inode. Thus corrupted medium could cause kernel to go into an infinite loop, possibly causing a stack overflow. Fix the possible stack overflow by removing recursion from __udf_read_inode() and limit number of indirect ICBs we follow to avoid infinite loops. Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-399 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice, UWORD8 u1_nal_ref_idc, dec_struct_t *ps_dec /* Decoder parameters */ ) { dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; dec_pic_params_t *ps_pps; dec_seq_params_t *ps_seq; dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; pocstruct_t s_tmp_poc; WORD32 i_delta_poc[2]; WORD32 i4_poc = 0; UWORD16 u2_first_mb_in_slice, u2_frame_num; UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type; UWORD32 u4_idr_pic_id = 0; UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type; UWORD8 u1_nal_unit_type; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; WORD8 i1_is_end_of_poc; WORD32 ret, end_of_frame; WORD32 prev_slice_err, num_mb_skipped; UWORD8 u1_mbaff; pocstruct_t *ps_cur_poc; UWORD32 u4_temp; WORD32 i_temp; UWORD32 u4_call_end_of_pic = 0; /* read FirstMbInSlice and slice type*/ ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0; u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u2_first_mb_in_slice > (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)) { return ERROR_CORRUPTED_SLICE; } /*we currently don not support ASO*/ if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) <= ps_dec->u2_cur_mb_addr) && (ps_dec->u4_first_slice_in_pic == 0)) { return ERROR_CORRUPTED_SLICE; } COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > 9) return ERROR_INV_SLC_TYPE_T; u1_slice_type = u4_temp; COPYTHECONTEXT("SH: slice_type",(u1_slice_type)); ps_dec->u1_sl_typ_5_9 = 0; /* Find Out the Slice Type is 5 to 9 or not then Set the Flag */ /* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/ /* will be of same type of current */ if(u1_slice_type > 4) { u1_slice_type -= 5; ps_dec->u1_sl_typ_5_9 = 1; } { UWORD32 skip; if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB) || (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB)) { UWORD32 u4_bit_stream_offset = 0; if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else if((I_SLICE == u1_slice_type) && (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames)) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else { skip = 1; } /* If one frame worth of data is already skipped, do not skip the next one */ if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped)) { skip = 0; } if(skip) { ps_dec->u4_prev_nal_skipped = 1; ps_dec->i4_dec_skip_mode = IVD_SKIP_PB; return 0; } else { /* If the previous NAL was skipped, then do not process that buffer in this call. Return to app and process it in the next call. This is necessary to handle cases where I/IDR is not complete in the current buffer and application intends to fill the remaining part of the bitstream later. This ensures we process only frame worth of data in every call */ if(1 == ps_dec->u4_prev_nal_skipped) { ps_dec->u4_return_to_app = 1; return 0; } } } } u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp & MASK_ERR_PIC_SET_ID) return ERROR_INV_SLICE_HDR_T; /* discard slice if pic param is invalid */ COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp); ps_pps = &ps_dec->ps_pps[u4_temp]; if(FALSE == ps_pps->u1_is_valid) { return ERROR_INV_SLICE_HDR_T; } ps_seq = ps_pps->ps_sps; if(!ps_seq) return ERROR_INV_SLICE_HDR_T; if(FALSE == ps_seq->u1_is_valid) return ERROR_INV_SLICE_HDR_T; /* Get the frame num */ u2_frame_num = ih264d_get_bits_h264(ps_bitstrm, ps_seq->u1_bits_in_frm_num); COPYTHECONTEXT("SH: frame_num", u2_frame_num); if(!ps_dec->u1_first_slice_in_stream && (ps_dec->u4_first_slice_in_pic == 2)) { pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc; pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; if((0 == u1_is_idr_slice) && ps_cur_slice->u1_nal_ref_idc) ps_dec->u2_prev_ref_frame_num = ps_cur_slice->u2_frame_num; if(u1_is_idr_slice || ps_cur_slice->u1_mmco_equalto5) ps_dec->u2_prev_ref_frame_num = 0; if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag) { ih264d_decode_gaps_in_frame_num(ps_dec, u2_frame_num); } ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; ps_prev_poc->u2_frame_num = ps_cur_poc->u2_frame_num; ps_prev_poc->u1_mmco_equalto5 = ps_cur_slice->u1_mmco_equalto5; if(ps_cur_slice->u1_nal_ref_idc) { ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0]; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1]; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field; } ps_dec->u2_total_mbs_coded = 0; } /* Get the field related flags */ if(!ps_seq->u1_frame_mbs_only_flag) { u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag); u1_bottom_field_flag = 0; if(u1_field_pic_flag) { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld; u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag); } else { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } } else { u1_field_pic_flag = 0; u1_bottom_field_flag = 0; ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } u1_nal_unit_type = SLICE_NAL; if(u1_is_idr_slice) { if(0 == u1_field_pic_flag) { ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; } u1_nal_unit_type = IDR_SLICE_NAL; u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_idr_pic_id > 65535) return ERROR_INV_SLICE_HDR_T; COPYTHECONTEXT("SH: ", u4_idr_pic_id); } /* read delta pic order count information*/ i_delta_poc[0] = i_delta_poc[1] = 0; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type; if(u1_pic_order_cnt_type == 0) { i_temp = ih264d_get_bits_h264( ps_bitstrm, ps_seq->u1_log2_max_pic_order_cnt_lsb_minus); if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb) return ERROR_INV_SLICE_HDR_T; s_tmp_poc.i4_pic_order_cnt_lsb = i_temp; COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb); if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag)) { s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom", s_tmp_poc.i4_delta_pic_order_cnt_bottom); } } s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; if(u1_pic_order_cnt_type == 1 && (!ps_seq->u1_delta_pic_order_always_zero_flag)) { s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[0]", s_tmp_poc.i4_delta_pic_order_cnt[0]); if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag) { s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[1]", s_tmp_poc.i4_delta_pic_order_cnt[1]); } } if(ps_pps->u1_redundant_pic_cnt_present_flag) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_REDUNDANT_PIC_CNT) return ERROR_INV_SLICE_HDR_T; u1_redundant_pic_cnt = u4_temp; COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt); } /*--------------------------------------------------------------------*/ /* Check if the slice is part of new picture */ /*--------------------------------------------------------------------*/ /* First slice of a picture is always considered as part of new picture */ i1_is_end_of_poc = 1; ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC; if(ps_dec->u4_first_slice_in_pic != 2) { i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc, &s_tmp_poc, &ps_dec->s_cur_pic_poc, ps_cur_slice, u1_pic_order_cnt_type, u1_nal_unit_type, u4_idr_pic_id, u1_field_pic_flag, u1_bottom_field_flag); if(i1_is_end_of_poc) { ps_dec->u1_first_slice_in_stream = 0; return ERROR_INCOMPLETE_FRAME; } } /*--------------------------------------------------------------------*/ /* Check for error in slice and parse the missing/corrupted MB's */ /* as skip-MB's in an inserted P-slice */ /*--------------------------------------------------------------------*/ u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); prev_slice_err = 0; if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream) { if(u2_frame_num != ps_dec->u2_prv_frame_num && ps_dec->u1_top_bottom_decoded != 0 && ps_dec->u1_top_bottom_decoded != (TOP_FIELD_ONLY | BOT_FIELD_ONLY)) { ps_dec->u1_dangling_field = 1; if(ps_dec->u4_first_slice_in_pic) { prev_slice_err = 1; } else { prev_slice_err = 2; } if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY) ps_cur_slice->u1_bottom_field_flag = 1; else ps_cur_slice->u1_bottom_field_flag = 0; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &ps_dec->s_cur_pic_poc; u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL; } else if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice > 0) { prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; ps_cur_poc = &s_tmp_poc; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); } } else { if(ps_dec->u4_first_slice_in_pic) { /* if valid slice header is not decoded do start of pic processing * since in the current process call, frame num is not updated in the slice structure yet * ih264d_is_end_of_pic is checked with valid frame num of previous process call, * although i1_is_end_of_poc is set there could be more slices in the frame, * so conceal only till cur slice */ prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; } else { /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame * completely */ prev_slice_err = 2; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; } ps_cur_poc = &s_tmp_poc; } } else { if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded) { prev_slice_err = 2; num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &s_tmp_poc; } else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded) { return ERROR_CORRUPTED_SLICE; } } if(prev_slice_err) { ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err); if(ps_dec->u1_dangling_field == 1) { ps_dec->u1_second_field = 1 - ps_dec->u1_second_field; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_dec->u2_prv_frame_num = u2_frame_num; ps_dec->u1_first_slice_in_stream = 0; return ERROR_DANGLING_FIELD_IN_PIC; } if(prev_slice_err == 2) { ps_dec->u1_first_slice_in_stream = 0; return ERROR_INCOMPLETE_FRAME; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { /* return if all MBs in frame are parsed*/ ps_dec->u1_first_slice_in_stream = 0; return ERROR_IN_LAST_SLICE_OF_PIC; } if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return ERROR_NEW_FRAME_EXPECTED; } if(ret != OK) return ret; i1_is_end_of_poc = 0; } if (ps_dec->u4_first_slice_in_pic == 0) { ps_dec->ps_parse_cur_slice++; ps_dec->u2_cur_slice_num++; } if((ps_dec->u1_separate_parse == 0) && (ps_dec->u4_first_slice_in_pic == 0)) { ps_dec->ps_decode_cur_slice++; } ps_dec->u1_slice_header_done = 0; if(u1_field_pic_flag) { ps_dec->u2_prv_frame_num = u2_frame_num; } if(ps_cur_slice->u1_mmco_equalto5) { WORD32 i4_temp_poc; WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair { i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; i4_temp_poc = MIN(i4_top_field_order_poc, i4_bot_field_order_poc); } else if(!ps_cur_slice->u1_bottom_field_flag) i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; else i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_top_field_order_cnt; ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_poc = i4_temp_poc; ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; } if(ps_dec->u4_first_slice_in_pic == 2) { ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num, &ps_dec->s_prev_pic_poc, &s_tmp_poc, ps_cur_slice, ps_pps, u1_nal_ref_idc, u1_bottom_field_flag, u1_field_pic_flag, &i4_poc); if(ret != OK) return ret; /* Display seq no calculations */ if(i4_poc >= ps_dec->i4_max_poc) ps_dec->i4_max_poc = i4_poc; /* IDR Picture or POC wrap around */ if(i4_poc == 0) { ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering + 1; ps_dec->i4_max_poc = 0; } } /*--------------------------------------------------------------------*/ /* Copy the values read from the bitstream to the slice header and then*/ /* If the slice is first slice in picture, then do Start of Picture */ /* processing. */ /*--------------------------------------------------------------------*/ ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0]; ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1]; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->u1_slice_type = u1_slice_type; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; if(ps_seq->u1_frame_mbs_only_flag) ps_cur_slice->u1_direct_8x8_inference_flag = ps_seq->u1_direct_8x8_inference_flag; else ps_cur_slice->u1_direct_8x8_inference_flag = 1; if(u1_slice_type == B_SLICE) { ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag", ps_cur_slice->u1_direct_spatial_mv_pred_flag); if(ps_cur_slice->u1_direct_spatial_mv_pred_flag) ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct; else ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct; if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB; } else { if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; } if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice == 0) { ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps); if(ret != OK) return ret; } ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } /* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */ { UWORD8 uc_nofield_nombaff; uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0) && (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0) && (u1_slice_type != B_SLICE) && (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0)); /* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */ if(uc_nofield_nombaff) { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; } else { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp; ps_dec->p_motion_compensate = ih264d_motion_compensate_mp; } } /* * Decide whether to decode the current picture or not */ { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_err->u4_frm_sei_sync == u2_frame_num) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT; } ps_err->u4_cur_frm = u2_frame_num; } /* Decision for decoding if the picture is to be skipped */ { WORD32 i4_skip_b_pic, i4_skip_p_pic; i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT) && (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT) && (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); /**************************************************************/ /* Skip the B picture if skip mask is set for B picture and */ /* Current B picture is a non reference B picture or there is */ /* no user for reference B picture */ /**************************************************************/ if(i4_skip_b_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; /* Don't decode the picture in SKIP-B mode if that picture is B */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } /**************************************************************/ /* Skip the P picture if skip mask is set for P picture and */ /* Current P picture is a non reference P picture or there is */ /* no user for reference P picture */ /**************************************************************/ if(i4_skip_p_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; /* Don't decode the picture in SKIP-P mode if that picture is P */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } } { UWORD16 u2_mb_x, u2_mb_y; ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE) - SUB_BLK_SIZE; if(u2_first_mb_in_slice) { UWORD8 u1_mb_aff; UWORD8 u1_field_pic; UWORD16 u2_frm_wd_in_mbs; u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag; u1_field_pic = ps_cur_slice->u1_field_pic_flag; { UWORD32 x_offset; UWORD32 y_offset; UWORD32 u4_frame_stride; tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y <<= u1_mb_aff; if((u2_mb_x > u2_frm_wd_in_mbs - 1) || (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1)) { return ERROR_CORRUPTED_SLICE; } u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic; x_offset = u2_mb_x << 4; y_offset = (u2_mb_y * u4_frame_stride) << 4; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset + y_offset; u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic; x_offset >>= 1; y_offset = (u2_mb_y * u4_frame_stride) << 3; x_offset *= YUV420SP_FACTOR; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset + y_offset; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset + y_offset; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; if(ps_dec->u1_separate_parse == 1) { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } else { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff); ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv + ((u2_first_mb_in_slice << u1_mb_aff) << 4); } } else { tfr_ctxt_t *ps_trns_addr; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = 0xffff; u2_mb_y = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; } ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->u2_mbx = (MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby = (DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; } /* RBSP stop bit is used for CABAC decoding*/ ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode; ps_dec->u1_B = (u1_slice_type == B_SLICE); ps_dec->u4_next_mb_skip = 0; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->ps_cur_slice->u2_first_mb_in_slice; ps_dec->ps_parse_cur_slice->slice_type = ps_dec->ps_cur_slice->u1_slice_type; ps_dec->u4_start_recon_deblk = 1; { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); num_entries = 2 * ((2 * num_entries) + 1); size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf; } if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } if(u1_slice_type == I_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT; ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice); if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE) ps_dec->i4_pic_type = I_SLICE; } else if(u1_slice_type == P_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; if(ps_dec->i4_pic_type != B_SLICE) ps_dec->i4_pic_type = P_SLICE; } else if(u1_slice_type == B_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; ps_dec->i4_pic_type = B_SLICE; } else return ERROR_INV_SLC_TYPE_T; if(ps_dec->u1_slice_header_done) { /* set to zero to indicate a valid slice has been decoded */ /* first slice header successfully decoded */ ps_dec->u4_first_slice_in_pic = 0; ps_dec->u1_first_slice_in_stream = 0; } if(ret != OK) return ret; /* storing last Mb X and MbY of the slice */ ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; /* End of Picture detection */ if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1)) { ps_dec->u1_pic_decode_done = 1; } { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if((ps_err->u1_err_flag & REJECT_PB_PICS) && (ps_err->u1_cur_pic_type == PIC_TYPE_I)) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; } } PRINT_BIN_BIT_RATIO(ps_dec) return ret; } Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static PHP_RINIT_FUNCTION(libxml) { if (_php_libxml_per_request_initialization) { /* report errors via handler rather than stderr */ xmlSetGenericErrorFunc(NULL, php_libxml_error_handler); xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename); } return SUCCESS; } Commit Message: CWE ID: Target: 1 Example 2: Code: void ChromeContentBrowserClient::OnNetworkServiceCreated( network::mojom::NetworkService* network_service) { if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) return; if (!SystemNetworkContextManager::GetInstance()) { DCHECK(!g_browser_process); DCHECK(chrome_feature_list_creator_->local_state()); SystemNetworkContextManager::CreateInstance( chrome_feature_list_creator_->local_state()); } SystemNetworkContextManager::GetInstance()->OnNetworkServiceCreated( network_service); } Commit Message: service worker: Make navigate/openWindow go through more security checks. WindowClient.navigate() and Clients.openWindow() were implemented in a way that directly navigated to the URL without going through some checks that the normal navigation path goes through. This CL attempts to fix that: - WindowClient.navigate() now goes through Navigator::RequestOpenURL() instead of directly through WebContents::OpenURL(). - Clients.openWindow() now calls more ContentBrowserClient functions for manipulating the navigation before invoking ContentBrowserClient::OpenURL(). Bug: 904219 Change-Id: Ic38978aee98c09834fdbbc240164068faa3fd4f5 Reviewed-on: https://chromium-review.googlesource.com/c/1345686 Commit-Queue: Matt Falkenhagen <[email protected]> Reviewed-by: Arthur Sonzogni <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Cr-Commit-Position: refs/heads/master@{#610753} CWE ID: CWE-264 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int Track::Info::Copy(Info& dst) const { if (&dst == this) return 0; dst.type = type; dst.number = number; dst.defaultDuration = defaultDuration; dst.codecDelay = codecDelay; dst.seekPreRoll = seekPreRoll; dst.uid = uid; dst.lacing = lacing; dst.settings = settings; if (int status = CopyStr(&Info::nameAsUTF8, dst)) return status; if (int status = CopyStr(&Info::language, dst)) return status; if (int status = CopyStr(&Info::codecId, dst)) return status; if (int status = CopyStr(&Info::codecNameAsUTF8, dst)) return status; if (codecPrivateSize > 0) { if (codecPrivate == NULL) return -1; if (dst.codecPrivate) return -1; if (dst.codecPrivateSize != 0) return -1; dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize]; if (dst.codecPrivate == NULL) return -1; memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize); dst.codecPrivateSize = codecPrivateSize; } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy(RTCPeerConnectionHandlerClient* client) : m_client(client) { ASSERT_UNUSED(m_client, m_client); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: GLboolean WebGLRenderingContextBase::isFramebuffer( WebGLFramebuffer* framebuffer) { if (!framebuffer || isContextLost()) return 0; if (!framebuffer->HasEverBeenBound()) return 0; if (framebuffer->IsDeleted()) return 0; return ContextGL()->IsFramebuffer(framebuffer->Object()); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ffs_sb_make_inode(struct super_block *sb, void *data, const struct file_operations *fops, const struct inode_operations *iops, struct ffs_file_perms *perms) { struct inode *inode; ENTER(); inode = new_inode(sb); if (likely(inode)) { struct timespec current_time = CURRENT_TIME; inode->i_ino = get_next_ino(); inode->i_mode = perms->mode; inode->i_uid = perms->uid; inode->i_gid = perms->gid; inode->i_atime = current_time; inode->i_mtime = current_time; inode->i_ctime = current_time; inode->i_private = data; if (fops) inode->i_fop = fops; if (iops) inode->i_op = iops; } return inode; } Commit Message: usb: gadget: f_fs: Fix use-after-free When using asynchronous read or write operations on the USB endpoints the issuer of the IO request is notified by calling the ki_complete() callback of the submitted kiocb when the URB has been completed. Calling this ki_complete() callback will free kiocb. Make sure that the structure is no longer accessed beyond that point, otherwise undefined behaviour might occur. Fixes: 2e4c7553cd6f ("usb: gadget: f_fs: add aio support") Cc: <[email protected]> # v3.15+ Signed-off-by: Lars-Peter Clausen <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper, NaClSubprocess* subprocess, const Manifest* manifest, bool should_report_uma, ErrorInfo* error_info, pp::CompletionCallback init_done_cb, pp::CompletionCallback crash_cb) { ServiceRuntime* new_service_runtime = new ServiceRuntime(this, manifest, should_report_uma, init_done_cb, crash_cb); subprocess->set_service_runtime(new_service_runtime); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n", static_cast<void*>(new_service_runtime))); if (NULL == new_service_runtime) { error_info->SetReport(ERROR_SEL_LDR_INIT, "sel_ldr init failure " + subprocess->description()); return false; } bool service_runtime_started = new_service_runtime->Start(wrapper, error_info, manifest_base_url()); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n", service_runtime_started)); if (!service_runtime_started) { return false; } const PPB_NaCl_Private* ppb_nacl = GetNaclInterface(); if (ppb_nacl->StartPpapiProxy(pp_instance())) { using_ipc_proxy_ = true; CHECK(init_done_cb.pp_completion_callback().func != NULL); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon, started ipc proxy.\n")); pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb, PP_OK); } return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: const Extension* AutomationProvider::GetEnabledExtension(int extension_handle) { const Extension* extension = extension_tracker_->GetResource(extension_handle); ExtensionService* service = profile_->GetExtensionService(); if (extension && service && service->GetExtensionById(extension->id(), false)) return extension; return NULL; } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: add_job(cupsd_client_t *con, /* I - Client connection */ cupsd_printer_t *printer, /* I - Destination printer */ mime_type_t *filetype) /* I - First print file type, if any */ { http_status_t status; /* Policy status */ ipp_attribute_t *attr, /* Current attribute */ *auth_info; /* auth-info attribute */ const char *mandatory; /* Current mandatory job attribute */ const char *val; /* Default option value */ int priority; /* Job priority */ cupsd_job_t *job; /* Current job */ char job_uri[HTTP_MAX_URI]; /* Job URI */ int kbytes; /* Size of print file */ int i; /* Looping var */ int lowerpagerange; /* Page range bound */ int exact; /* Did we have an exact match? */ ipp_attribute_t *media_col, /* media-col attribute */ *media_margin; /* media-*-margin attribute */ ipp_t *unsup_col; /* media-col in unsupported response */ static const char * const readonly[] =/* List of read-only attributes */ { "date-time-at-completed", "date-time-at-creation", "date-time-at-processing", "job-detailed-status-messages", "job-document-access-errors", "job-id", "job-impressions-completed", "job-k-octets-completed", "job-media-sheets-completed", "job-pages-completed", "job-printer-up-time", "job-printer-uri", "job-state", "job-state-message", "job-state-reasons", "job-uri", "number-of-documents", "number-of-intervening-jobs", "output-device-assigned", "time-at-completed", "time-at-creation", "time-at-processing" }; cupsdLogMessage(CUPSD_LOG_DEBUG2, "add_job(%p[%d], %p(%s), %p(%s/%s))", con, con->number, printer, printer->name, filetype, filetype ? filetype->super : "none", filetype ? filetype->type : "none"); /* * Check remote printing to non-shared printer... */ if (!printer->shared && _cups_strcasecmp(con->http->hostname, "localhost") && _cups_strcasecmp(con->http->hostname, ServerName)) { send_ipp_status(con, IPP_NOT_AUTHORIZED, _("The printer or class is not shared.")); return (NULL); } /* * Check policy... */ auth_info = ippFindAttribute(con->request, "auth-info", IPP_TAG_TEXT); if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK) { send_http_error(con, status, printer); return (NULL); } else if (printer->num_auth_info_required == 1 && !strcmp(printer->auth_info_required[0], "negotiate") && !con->username[0]) { send_http_error(con, HTTP_UNAUTHORIZED, printer); return (NULL); } #ifdef HAVE_SSL else if (auth_info && !con->http->tls && !httpAddrLocalhost(con->http->hostaddr)) { /* * Require encryption of auth-info over non-local connections... */ send_http_error(con, HTTP_UPGRADE_REQUIRED, printer); return (NULL); } #endif /* HAVE_SSL */ /* * See if the printer is accepting jobs... */ if (!printer->accepting) { send_ipp_status(con, IPP_NOT_ACCEPTING, _("Destination \"%s\" is not accepting jobs."), printer->name); return (NULL); } /* * Validate job template attributes; for now just document-format, * copies, job-sheets, number-up, page-ranges, mandatory attributes, and * media... */ for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++) { if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL) { ippDeleteAttribute(con->request, attr); if (StrictConformance) { send_ipp_status(con, IPP_BAD_REQUEST, _("The '%s' Job Status attribute cannot be supplied in a job creation request."), readonly[i]); return (NULL); } cupsdLogMessage(CUPSD_LOG_INFO, "Unexpected '%s' Job Status attribute in a job creation request.", readonly[i]); } } if (printer->pc) { for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory); mandatory; mandatory = (char *)cupsArrayNext(printer->pc->mandatory)) { if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO)) { /* * Missing a required attribute... */ send_ipp_status(con, IPP_CONFLICT, _("The \"%s\" attribute is required for print jobs."), mandatory); return (NULL); } } } if (filetype && printer->filetypes && !cupsArrayFind(printer->filetypes, filetype)) { char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2]; /* MIME media type string */ snprintf(mimetype, sizeof(mimetype), "%s/%s", filetype->super, filetype->type); send_ipp_status(con, IPP_DOCUMENT_FORMAT, _("Unsupported format \"%s\"."), mimetype); ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE, "document-format", NULL, mimetype); return (NULL); } if ((attr = ippFindAttribute(con->request, "copies", IPP_TAG_INTEGER)) != NULL) { if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad copies value %d."), attr->values[0].integer); ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "copies", attr->values[0].integer); return (NULL); } } if ((attr = ippFindAttribute(con->request, "job-sheets", IPP_TAG_ZERO)) != NULL) { if (attr->value_tag != IPP_TAG_KEYWORD && attr->value_tag != IPP_TAG_NAME) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value type.")); return (NULL); } if (attr->num_values > 2) { send_ipp_status(con, IPP_BAD_REQUEST, _("Too many job-sheets values (%d > 2)."), attr->num_values); return (NULL); } for (i = 0; i < attr->num_values; i ++) if (strcmp(attr->values[i].string.text, "none") && !cupsdFindBanner(attr->values[i].string.text)) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad job-sheets value \"%s\"."), attr->values[i].string.text); return (NULL); } } if ((attr = ippFindAttribute(con->request, "number-up", IPP_TAG_INTEGER)) != NULL) { if (attr->values[0].integer != 1 && attr->values[0].integer != 2 && attr->values[0].integer != 4 && attr->values[0].integer != 6 && attr->values[0].integer != 9 && attr->values[0].integer != 16) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad number-up value %d."), attr->values[0].integer); ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, "number-up", attr->values[0].integer); return (NULL); } } if ((attr = ippFindAttribute(con->request, "page-ranges", IPP_TAG_RANGE)) != NULL) { for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++) { if (attr->values[i].range.lower < lowerpagerange || attr->values[i].range.lower > attr->values[i].range.upper) { send_ipp_status(con, IPP_BAD_REQUEST, _("Bad page-ranges values %d-%d."), attr->values[i].range.lower, attr->values[i].range.upper); return (NULL); } lowerpagerange = attr->values[i].range.upper + 1; } } /* * Do media selection as needed... */ if (!ippFindAttribute(con->request, "PageRegion", IPP_TAG_ZERO) && !ippFindAttribute(con->request, "PageSize", IPP_TAG_ZERO) && _ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact)) { if (!exact && (media_col = ippFindAttribute(con->request, "media-col", IPP_TAG_BEGIN_COLLECTION)) != NULL) { send_ipp_status(con, IPP_OK_SUBST, _("Unsupported margins.")); unsup_col = ippNew(); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-bottom-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-bottom-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-left-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-left-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-right-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-right-margin", media_margin->values[0].integer); if ((media_margin = ippFindAttribute(media_col->values[0].collection, "media-top-margin", IPP_TAG_INTEGER)) != NULL) ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, "media-top-margin", media_margin->values[0].integer); ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, "media-col", unsup_col); ippDelete(unsup_col); } } /* * Make sure we aren't over our limit... */ if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) cupsdCleanJobs(); if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) { send_ipp_status(con, IPP_NOT_POSSIBLE, _("Too many active jobs.")); return (NULL); } if ((i = check_quotas(con, printer)) < 0) { send_ipp_status(con, IPP_NOT_POSSIBLE, _("Quota limit reached.")); return (NULL); } else if (i == 0) { send_ipp_status(con, IPP_NOT_AUTHORIZED, _("Not allowed to print.")); return (NULL); } /* * Create the job and set things up... */ if ((attr = ippFindAttribute(con->request, "job-priority", IPP_TAG_INTEGER)) != NULL) priority = attr->values[0].integer; else { if ((val = cupsGetOption("job-priority", printer->num_options, printer->options)) != NULL) priority = atoi(val); else priority = 50; ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority", priority); } if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_ZERO)) == NULL) ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, "job-name", NULL, "Untitled"); else if ((attr->value_tag != IPP_TAG_NAME && attr->value_tag != IPP_TAG_NAMELANG) || attr->num_values != 1) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: Wrong type or count.")); if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; return (NULL); } else if (!ippValidateAttribute(attr)) { send_ipp_status(con, IPP_ATTRIBUTES, _("Bad job-name value: %s"), cupsLastErrorString()); if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; return (NULL); } if ((job = cupsdAddJob(priority, printer->name)) == NULL) { send_ipp_status(con, IPP_INTERNAL_ERROR, _("Unable to add job for destination \"%s\"."), printer->name); return (NULL); } job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE); job->attrs = con->request; job->dirty = 1; con->request = ippNewRequest(job->attrs->request.op.operation_id); cupsdMarkDirty(CUPSD_DIRTY_JOBS); add_job_uuid(job); apply_printer_defaults(printer, job); attr = ippFindAttribute(job->attrs, "requesting-user-name", IPP_TAG_NAME); if (con->username[0]) { cupsdSetString(&job->username, con->username); if (attr) ippSetString(job->attrs, &attr, 0, con->username); } else if (attr) { cupsdLogMessage(CUPSD_LOG_DEBUG, "add_job: requesting-user-name=\"%s\"", attr->values[0].string.text); cupsdSetString(&job->username, attr->values[0].string.text); } else cupsdSetString(&job->username, "anonymous"); if (!attr) ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-user-name", NULL, job->username); else { ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); ippSetName(job->attrs, &attr, "job-originating-user-name"); } if (con->username[0] || auth_info) { save_auth_info(con, job, auth_info); /* * Remove the auth-info attribute from the attribute data... */ if (auth_info) ippDeleteAttribute(job->attrs, auth_info); } if ((attr = ippFindAttribute(con->request, "job-name", IPP_TAG_NAME)) != NULL) cupsdSetString(&(job->name), attr->values[0].string.text); if ((attr = ippFindAttribute(job->attrs, "job-originating-host-name", IPP_TAG_ZERO)) != NULL) { /* * Request contains a job-originating-host-name attribute; validate it... */ if (attr->value_tag != IPP_TAG_NAME || attr->num_values != 1 || strcmp(con->http->hostname, "localhost")) { /* * Can't override the value if we aren't connected via localhost. * Also, we can only have 1 value and it must be a name value. */ ippDeleteAttribute(job->attrs, attr); ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname); } else ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); } else { /* * No job-originating-host-name attribute, so use the hostname from * the connection... */ ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-originating-host-name", NULL, con->http->hostname); } ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-completed"); ippAddDate(job->attrs, IPP_TAG_JOB, "date-time-at-creation", ippTimeToDate(time(NULL))); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "date-time-at-processing"); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-completed"); ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "time-at-creation", time(NULL)); ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, "time-at-processing"); /* * Add remaining job attributes... */ ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id); job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", IPP_JOB_STOPPED); job->state_value = (ipp_jstate_t)job->state->values[0].integer; job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, "job-incoming"); job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0); job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-media-sheets-completed", 0); ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL, printer->uri); if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL) attr->values[0].integer = 0; else ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-k-octets", 0); if ((attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_KEYWORD)) == NULL) attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME); if (!attr) { if ((val = cupsGetOption("job-hold-until", printer->num_options, printer->options)) == NULL) val = "no-hold"; attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-hold-until", NULL, val); } if (printer->holding_new_jobs) { /* * Hold all new jobs on this printer... */ if (attr && strcmp(attr->values[0].string.text, "no-hold")) cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0); else cupsdSetJobHoldUntil(job, "indefinite", 0); job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; ippSetString(job->attrs, &job->reasons, 0, "job-held-on-create"); } else if (attr && strcmp(attr->values[0].string.text, "no-hold")) { /* * Hold job until specified time... */ cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0); job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified"); } else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB) { job->hold_until = time(NULL) + MultipleOperationTimeout; job->state->values[0].integer = IPP_JOB_HELD; job->state_value = IPP_JOB_HELD; } else { job->state->values[0].integer = IPP_JOB_PENDING; job->state_value = IPP_JOB_PENDING; ippSetString(job->attrs, &job->reasons, 0, "none"); } if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification) { /* * Add job sheets options... */ if ((attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) == NULL) { cupsdLogMessage(CUPSD_LOG_DEBUG, "Adding default job-sheets values \"%s,%s\"...", printer->job_sheets[0], printer->job_sheets[1]); attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, "job-sheets", 2, NULL, NULL); ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]); ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]); } job->job_sheets = attr; /* * Enforce classification level if set... */ if (Classification) { cupsdLogMessage(CUPSD_LOG_INFO, "Classification=\"%s\", ClassifyOverride=%d", Classification ? Classification : "(null)", ClassifyOverride); if (ClassifyOverride) { if (!strcmp(attr->values[0].string.text, "none") && (attr->num_values == 1 || !strcmp(attr->values[1].string.text, "none"))) { /* * Force the leading banner to have the classification on it... */ ippSetString(job->attrs, &attr, 0, Classification); cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,none\", " "job-originating-user-name=\"%s\"", Classification, job->username); } else if (attr->num_values == 2 && strcmp(attr->values[0].string.text, attr->values[1].string.text) && strcmp(attr->values[0].string.text, "none") && strcmp(attr->values[1].string.text, "none")) { /* * Can't put two different security markings on the same document! */ ippSetString(job->attrs, &attr, 1, attr->values[0].string.text); cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); } else if (strcmp(attr->values[0].string.text, Classification) && strcmp(attr->values[0].string.text, "none") && (attr->num_values == 1 || (strcmp(attr->values[1].string.text, Classification) && strcmp(attr->values[1].string.text, "none")))) { if (attr->num_values == 1) cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION OVERRIDDEN " "job-sheets=\"%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, job->username); else cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION OVERRIDDEN " "job-sheets=\"%s,%s\",fffff " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); } } else if (strcmp(attr->values[0].string.text, Classification) && (attr->num_values == 1 || strcmp(attr->values[1].string.text, Classification))) { /* * Force the banner to have the classification on it... */ if (attr->num_values > 1 && !strcmp(attr->values[0].string.text, attr->values[1].string.text)) { ippSetString(job->attrs, &attr, 0, Classification); ippSetString(job->attrs, &attr, 1, Classification); } else { if (attr->num_values == 1 || strcmp(attr->values[0].string.text, "none")) ippSetString(job->attrs, &attr, 0, Classification); if (attr->num_values > 1 && strcmp(attr->values[1].string.text, "none")) ippSetString(job->attrs, &attr, 1, Classification); } if (attr->num_values > 1) cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s,%s\", " "job-originating-user-name=\"%s\"", attr->values[0].string.text, attr->values[1].string.text, job->username); else cupsdLogJob(job, CUPSD_LOG_NOTICE, "CLASSIFICATION FORCED " "job-sheets=\"%s\", " "job-originating-user-name=\"%s\"", Classification, job->username); } } /* * See if we need to add the starting sheet... */ if (!(printer->type & CUPS_PRINTER_REMOTE)) { cupsdLogJob(job, CUPSD_LOG_INFO, "Adding start banner page \"%s\".", attr->values[0].string.text); if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0) { cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE, "Aborting job because the start banner could not be " "copied."); return (NULL); } cupsdUpdateQuota(printer, job->username, 0, kbytes); } } else if ((attr = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) != NULL) job->job_sheets = attr; /* * Fill in the response info... */ httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), "ipp", NULL, con->clientname, con->clientport, "/jobs/%d", job->id); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, "job-uri", NULL, job_uri); ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-id", job->id); ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, "job-state", job->state_value); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, "job-state-message", NULL, ""); ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-state-reasons", NULL, job->reasons->values[0].string.text); con->response->request.status.status_code = IPP_OK; /* * Add any job subscriptions... */ add_job_subscriptions(con, job); /* * Set all but the first two attributes to the job attributes group... */ for (attr = job->attrs->attrs->next->next; attr; attr = attr->next) attr->group_tag = IPP_TAG_JOB; /* * Fire the "job created" event... */ cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, "Job created."); /* * Return the new job... */ return (job); } Commit Message: DBUS notifications could crash the scheduler (Issue #5143) - scheduler/ipp.c: Make sure requesting-user-name string is valid UTF-8. CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; if (inHeader == NULL) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; continue; } PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); ++mInputBufferCount; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } return; } uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset; uint32_t *start_code = (uint32_t *)bitstream; bool volHeader = *start_code == 0xB0010000; if (volHeader) { PVCleanUpVideoDecoder(mHandle); mInitialized = false; } if (!mInitialized) { uint8_t *vol_data[1]; int32_t vol_size = 0; vol_data[0] = NULL; if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) { vol_data[0] = bitstream; vol_size = inHeader->nFilledLen; } MP4DecodingMode mode = (mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE; Bool success = PVInitVideoDecoder( mHandle, vol_data, &vol_size, 1, outputBufferWidth(), outputBufferHeight(), mode); if (!success) { ALOGW("PVInitVideoDecoder failed. Unsupported content?"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle); if (mode != actualMode) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } PVSetPostProcType((VideoDecControls *) mHandle, 0); bool hasFrameData = false; if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } else if (volHeader) { hasFrameData = true; } mInitialized = true; if (mode == MPEG4_MODE && handlePortSettingsChange()) { return; } if (!hasFrameData) { continue; } } if (!mFramesConfigured) { PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader; PVSetReferenceYUV(mHandle, outHeader->pBuffer); mFramesConfigured = true; } uint32_t useExtTimestamp = (inHeader->nOffset == 0); uint32_t timestamp = 0xFFFFFFFF; if (useExtTimestamp) { mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp); timestamp = mPvTime; mPvTime++; } int32_t bufferSize = inHeader->nFilledLen; int32_t tmp = bufferSize; OMX_U32 frameSize = (mWidth * mHeight * 3) / 2; if (outHeader->nAllocLen < frameSize) { android_errorWriteLog(0x534e4554, "27833616"); ALOGE("Insufficient output buffer size"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (PVDecodeVideoFrame( mHandle, &bitstream, &timestamp, &tmp, &useExtTimestamp, outHeader->pBuffer) != PV_TRUE) { ALOGE("failed to decode video frame."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (handlePortSettingsChange()) { return; } outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp); mPvToOmxTimeMap.removeItem(timestamp); inHeader->nOffset += bufferSize; inHeader->nFilledLen = 0; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; } else { outHeader->nFlags = 0; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } ++mInputBufferCount; outHeader->nOffset = 0; outHeader->nFilledLen = frameSize; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mNumSamplesOutput; } } Commit Message: SoftMPEG4: Check the buffer size before writing the reference frame. Also prevent overflow in SoftMPEG4 and division by zero in SoftMPEG4Encoder. Bug: 30033990 Change-Id: I7701f5fc54c2670587d122330e5dc851f64ed3c2 (cherry picked from commit 695123195034402ca76169b195069c28c30342d3) CWE ID: CWE-264 Target: 1 Example 2: Code: COMPS_MRTree * comps_mrtree_create(void* (*data_constructor)(void*), void* (*data_cloner)(void*), void (*data_destructor)(void*)) { COMPS_MRTree *ret; if ((ret = malloc(sizeof(COMPS_MRTree))) == NULL) return NULL; ret->subnodes = comps_hslist_create(); comps_hslist_init(ret->subnodes, NULL, NULL, &comps_mrtree_data_destroy_v); if (ret->subnodes == NULL) { free(ret); return NULL; } ret->data_constructor = data_constructor; ret->data_cloner = data_cloner; ret->data_destructor = data_destructor; return ret; } Commit Message: Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste. CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: set_umask(const char *optarg) { long umask_long; mode_t umask_val; char *endptr; umask_long = strtoll(optarg, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { fprintf(stderr, "Invalid --umask option %s", optarg); return; } umask_val = umask_long & 0777; umask(umask_val); umask_cmdline = true; return umask_val; } Commit Message: Fix compile warning introduced in commit c6247a9 Commit c6247a9 - "Add command line and configuration option to set umask" introduced a compile warning, although the code would have worked OK. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xfs_attr3_leaf_getvalue( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; int valuelen; leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); ASSERT(args->index < ichdr.count); entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); ASSERT(name_loc->namelen == args->namelen); ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0); valuelen = be16_to_cpu(name_loc->valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; memcpy(args->value, &name_loc->nameval[args->namelen], valuelen); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); ASSERT(name_rmt->namelen == args->namelen); ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0); valuelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount, valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; } return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: mojom::NavigationClient* NavigationRequest::GetCommitNavigationClient() { if (commit_navigation_client_ && commit_navigation_client_.is_bound()) return commit_navigation_client_.get(); commit_navigation_client_ = render_frame_host_->GetNavigationClientFromInterfaceProvider(); return commit_navigation_client_.get(); } Commit Message: Show an error page if a URL redirects to a javascript: URL. BUG=935175 Change-Id: Id4a9198d5dff823bc3d324b9de9bff2ee86dc499 Reviewed-on: https://chromium-review.googlesource.com/c/1488152 Commit-Queue: Charlie Reis <[email protected]> Reviewed-by: Arthur Sonzogni <[email protected]> Cr-Commit-Position: refs/heads/master@{#635848} CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int DetectEngineContentInspection(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const Signature *s, const SigMatchData *smd, Flow *f, uint8_t *buffer, uint32_t buffer_len, uint32_t stream_start_offset, uint8_t inspection_mode, void *data) { SCEnter(); KEYWORD_PROFILING_START; det_ctx->inspection_recursion_counter++; if (det_ctx->inspection_recursion_counter == de_ctx->inspection_recursion_limit) { det_ctx->discontinue_matching = 1; KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); } if (smd == NULL || buffer_len == 0) { KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); } /* \todo unify this which is phase 2 of payload inspection unification */ if (smd->type == DETECT_CONTENT) { DetectContentData *cd = (DetectContentData *)smd->ctx; SCLogDebug("inspecting content %"PRIu32" buffer_len %"PRIu32, cd->id, buffer_len); /* we might have already have this content matched by the mpm. * (if there is any other reason why we'd want to avoid checking * it here, please fill it in) */ /* rule parsers should take care of this */ #ifdef DEBUG BUG_ON(cd->depth != 0 && cd->depth <= cd->offset); #endif /* search for our pattern, checking the matches recursively. * if we match we look for the next SigMatch as well */ uint8_t *found = NULL; uint32_t offset = 0; uint32_t depth = buffer_len; uint32_t prev_offset = 0; /**< used in recursive searching */ uint32_t prev_buffer_offset = det_ctx->buffer_offset; do { if ((cd->flags & DETECT_CONTENT_DISTANCE) || (cd->flags & DETECT_CONTENT_WITHIN)) { SCLogDebug("det_ctx->buffer_offset %"PRIu32, det_ctx->buffer_offset); offset = prev_buffer_offset; depth = buffer_len; int distance = cd->distance; if (cd->flags & DETECT_CONTENT_DISTANCE) { if (cd->flags & DETECT_CONTENT_DISTANCE_BE) { distance = det_ctx->bj_values[cd->distance]; } if (distance < 0 && (uint32_t)(abs(distance)) > offset) offset = 0; else offset += distance; SCLogDebug("cd->distance %"PRIi32", offset %"PRIu32", depth %"PRIu32, distance, offset, depth); } if (cd->flags & DETECT_CONTENT_WITHIN) { if (cd->flags & DETECT_CONTENT_WITHIN_BE) { if ((int32_t)depth > (int32_t)(prev_buffer_offset + det_ctx->bj_values[cd->within] + distance)) { depth = prev_buffer_offset + det_ctx->bj_values[cd->within] + distance; } } else { if ((int32_t)depth > (int32_t)(prev_buffer_offset + cd->within + distance)) { depth = prev_buffer_offset + cd->within + distance; } SCLogDebug("cd->within %"PRIi32", det_ctx->buffer_offset %"PRIu32", depth %"PRIu32, cd->within, prev_buffer_offset, depth); } if (stream_start_offset != 0 && prev_buffer_offset == 0) { if (depth <= stream_start_offset) { goto no_match; } else if (depth >= (stream_start_offset + buffer_len)) { ; } else { depth = depth - stream_start_offset; } } } if (cd->flags & DETECT_CONTENT_DEPTH_BE) { if ((det_ctx->bj_values[cd->depth] + prev_buffer_offset) < depth) { depth = prev_buffer_offset + det_ctx->bj_values[cd->depth]; } } else { if (cd->depth != 0) { if ((cd->depth + prev_buffer_offset) < depth) { depth = prev_buffer_offset + cd->depth; } SCLogDebug("cd->depth %"PRIu32", depth %"PRIu32, cd->depth, depth); } } if (cd->flags & DETECT_CONTENT_OFFSET_BE) { if (det_ctx->bj_values[cd->offset] > offset) offset = det_ctx->bj_values[cd->offset]; } else { if (cd->offset > offset) { offset = cd->offset; SCLogDebug("setting offset %"PRIu32, offset); } } } else { /* implied no relative matches */ /* set depth */ if (cd->flags & DETECT_CONTENT_DEPTH_BE) { depth = det_ctx->bj_values[cd->depth]; } else { if (cd->depth != 0) { depth = cd->depth; } } if (stream_start_offset != 0 && cd->flags & DETECT_CONTENT_DEPTH) { if (depth <= stream_start_offset) { goto no_match; } else if (depth >= (stream_start_offset + buffer_len)) { ; } else { depth = depth - stream_start_offset; } } /* set offset */ if (cd->flags & DETECT_CONTENT_OFFSET_BE) offset = det_ctx->bj_values[cd->offset]; else offset = cd->offset; prev_buffer_offset = 0; } /* update offset with prev_offset if we're searching for * matches after the first occurence. */ SCLogDebug("offset %"PRIu32", prev_offset %"PRIu32, offset, prev_offset); if (prev_offset != 0) offset = prev_offset; SCLogDebug("offset %"PRIu32", depth %"PRIu32, offset, depth); if (depth > buffer_len) depth = buffer_len; /* if offset is bigger than depth we can never match on a pattern. * We can however, "match" on a negated pattern. */ if (offset > depth || depth == 0) { if (cd->flags & DETECT_CONTENT_NEGATED) { goto match; } else { goto no_match; } } uint8_t *sbuffer = buffer + offset; uint32_t sbuffer_len = depth - offset; uint32_t match_offset = 0; SCLogDebug("sbuffer_len %"PRIu32, sbuffer_len); #ifdef DEBUG BUG_ON(sbuffer_len > buffer_len); #endif /* \todo Add another optimization here. If cd->content_len is * greater than sbuffer_len found is anyways NULL */ /* do the actual search */ found = SpmScan(cd->spm_ctx, det_ctx->spm_thread_ctx, sbuffer, sbuffer_len); /* next we evaluate the result in combination with the * negation flag. */ SCLogDebug("found %p cd negated %s", found, cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false"); if (found == NULL && !(cd->flags & DETECT_CONTENT_NEGATED)) { goto no_match; } else if (found == NULL && (cd->flags & DETECT_CONTENT_NEGATED)) { goto match; } else if (found != NULL && (cd->flags & DETECT_CONTENT_NEGATED)) { SCLogDebug("content %"PRIu32" matched at offset %"PRIu32", but negated so no match", cd->id, match_offset); /* don't bother carrying recursive matches now, for preceding * relative keywords */ if (DETECT_CONTENT_IS_SINGLE(cd)) det_ctx->discontinue_matching = 1; goto no_match; } else { match_offset = (uint32_t)((found - buffer) + cd->content_len); SCLogDebug("content %"PRIu32" matched at offset %"PRIu32"", cd->id, match_offset); det_ctx->buffer_offset = match_offset; /* Match branch, add replace to the list if needed */ if (cd->flags & DETECT_CONTENT_REPLACE) { if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) { /* we will need to replace content if match is confirmed */ det_ctx->replist = DetectReplaceAddToList(det_ctx->replist, found, cd); } else { SCLogWarning(SC_ERR_INVALID_VALUE, "Can't modify payload without packet"); } } if (!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT)) { SCLogDebug("no relative match coming up, so this is a match"); goto match; } /* bail out if we have no next match. Technically this is an * error, as the current cd has the DETECT_CONTENT_RELATIVE_NEXT * flag set. */ if (smd->is_last) { goto no_match; } SCLogDebug("content %"PRIu32, cd->id); KEYWORD_PROFILING_END(det_ctx, smd->type, 1); /* see if the next buffer keywords match. If not, we will * search for another occurence of this content and see * if the others match then until we run out of matches */ int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); if (r == 1) { SCReturnInt(1); } if (det_ctx->discontinue_matching) goto no_match; /* set the previous match offset to the start of this match + 1 */ prev_offset = (match_offset - (cd->content_len - 1)); SCLogDebug("trying to see if there is another match after prev_offset %"PRIu32, prev_offset); } } while(1); } else if (smd->type == DETECT_ISDATAAT) { SCLogDebug("inspecting isdataat"); DetectIsdataatData *id = (DetectIsdataatData *)smd->ctx; if (id->flags & ISDATAAT_RELATIVE) { if (det_ctx->buffer_offset + id->dataat > buffer_len) { SCLogDebug("det_ctx->buffer_offset + id->dataat %"PRIu32" > %"PRIu32, det_ctx->buffer_offset + id->dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; } else { SCLogDebug("relative isdataat match"); if (id->flags & ISDATAAT_NEGATED) goto no_match; goto match; } } else { if (id->dataat < buffer_len) { SCLogDebug("absolute isdataat match"); if (id->flags & ISDATAAT_NEGATED) goto no_match; goto match; } else { SCLogDebug("absolute isdataat mismatch, id->isdataat %"PRIu32", buffer_len %"PRIu32"", id->dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; } } } else if (smd->type == DETECT_PCRE) { SCLogDebug("inspecting pcre"); DetectPcreData *pe = (DetectPcreData *)smd->ctx; uint32_t prev_buffer_offset = det_ctx->buffer_offset; uint32_t prev_offset = 0; int r = 0; det_ctx->pcre_match_start_offset = 0; do { Packet *p = NULL; if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) p = (Packet *)data; r = DetectPcrePayloadMatch(det_ctx, s, smd, p, f, buffer, buffer_len); if (r == 0) { goto no_match; } if (!(pe->flags & DETECT_PCRE_RELATIVE_NEXT)) { SCLogDebug("no relative match coming up, so this is a match"); goto match; } KEYWORD_PROFILING_END(det_ctx, smd->type, 1); /* save it, in case we need to do a pcre match once again */ prev_offset = det_ctx->pcre_match_start_offset; /* see if the next payload keywords match. If not, we will * search for another occurence of this pcre and see * if the others match, until we run out of matches */ r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); if (r == 1) { SCReturnInt(1); } if (det_ctx->discontinue_matching) goto no_match; det_ctx->buffer_offset = prev_buffer_offset; det_ctx->pcre_match_start_offset = prev_offset; } while (1); } else if (smd->type == DETECT_BYTETEST) { DetectBytetestData *btd = (DetectBytetestData *)smd->ctx; uint8_t flags = btd->flags; int32_t offset = btd->offset; uint64_t value = btd->value; if (flags & DETECT_BYTETEST_OFFSET_BE) { offset = det_ctx->bj_values[offset]; } if (flags & DETECT_BYTETEST_VALUE_BE) { value = det_ctx->bj_values[value]; } /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if (flags & DETECT_BYTETEST_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ? DETECT_BYTETEST_LITTLE: 0); } if (DetectBytetestDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags, offset, value) != 1) { goto no_match; } goto match; } else if (smd->type == DETECT_BYTEJUMP) { DetectBytejumpData *bjd = (DetectBytejumpData *)smd->ctx; uint8_t flags = bjd->flags; int32_t offset = bjd->offset; if (flags & DETECT_BYTEJUMP_OFFSET_BE) { offset = det_ctx->bj_values[offset]; } /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if (flags & DETECT_BYTEJUMP_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ? DETECT_BYTEJUMP_LITTLE: 0); } if (DetectBytejumpDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags, offset) != 1) { goto no_match; } goto match; } else if (smd->type == DETECT_BYTE_EXTRACT) { DetectByteExtractData *bed = (DetectByteExtractData *)smd->ctx; uint8_t endian = bed->endian; /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if ((bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) && endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ endian |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] == 0x10) ? DETECT_BYTE_EXTRACT_ENDIAN_LITTLE : DETECT_BYTE_EXTRACT_ENDIAN_BIG); } if (DetectByteExtractDoMatch(det_ctx, smd, s, buffer, buffer_len, &det_ctx->bj_values[bed->local_id], endian) != 1) { goto no_match; } goto match; /* we should never get here, but bail out just in case */ } else if (smd->type == DETECT_AL_URILEN) { SCLogDebug("inspecting uri len"); int r = 0; DetectUrilenData *urilend = (DetectUrilenData *) smd->ctx; switch (urilend->mode) { case DETECT_URILEN_EQ: if (buffer_len == urilend->urilen1) r = 1; break; case DETECT_URILEN_LT: if (buffer_len < urilend->urilen1) r = 1; break; case DETECT_URILEN_GT: if (buffer_len > urilend->urilen1) r = 1; break; case DETECT_URILEN_RA: if (buffer_len > urilend->urilen1 && buffer_len < urilend->urilen2) { r = 1; } break; } if (r == 1) { goto match; } det_ctx->discontinue_matching = 0; goto no_match; #ifdef HAVE_LUA } else if (smd->type == DETECT_LUA) { SCLogDebug("lua starting"); if (DetectLuaMatchBuffer(det_ctx, s, smd, buffer, buffer_len, det_ctx->buffer_offset, f) != 1) { SCLogDebug("lua no_match"); goto no_match; } SCLogDebug("lua match"); goto match; #endif /* HAVE_LUA */ } else if (smd->type == DETECT_BASE64_DECODE) { if (DetectBase64DecodeDoMatch(det_ctx, s, smd, buffer, buffer_len)) { if (s->sm_arrays[DETECT_SM_LIST_BASE64_DATA] != NULL) { KEYWORD_PROFILING_END(det_ctx, smd->type, 1); if (DetectBase64DataDoMatch(de_ctx, det_ctx, s, f)) { /* Base64 is a terminal list. */ goto final_match; } } } } else { SCLogDebug("sm->type %u", smd->type); #ifdef DEBUG BUG_ON(1); #endif } no_match: KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); match: /* this sigmatch matched, inspect the next one. If it was the last, * the buffer portion of the signature matched. */ if (!smd->is_last) { KEYWORD_PROFILING_END(det_ctx, smd->type, 1); int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); SCReturnInt(r); } final_match: KEYWORD_PROFILING_END(det_ctx, smd->type, 1); SCReturnInt(1); } Commit Message: detect: avoid needless recursive scanning Don't recursively inspect a detect list if the recursion doesn't increase chance of success. CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CL_Init( void ) { Com_Printf( "----- Client Initialization -----\n" ); Con_Init (); if(!com_fullyInitialized) { CL_ClearState(); clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cl_oldGameSet = qfalse; } cls.realtime = 0; CL_InitInput (); cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); #ifdef UPDATE_SERVER_NAME cl_motd = Cvar_Get ("cl_motd", "1", 0); #endif cl_timeout = Cvar_Get ("cl_timeout", "200", 0); cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP ); cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP ); cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP ); rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP ); cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); cl_timedemo = Cvar_Get ("timedemo", "0", 0); cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE); cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE); cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE); cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0); rconAddress = Cvar_Get ("rconAddress", "", 0); cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE); cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE); cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0); cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE ); cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE ); cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE); cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE); cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE); cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE ); cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE ); cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE ); Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0); cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE); #endif cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); #ifdef __APPLE__ cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE); #else cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE); #endif cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0); Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE); m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE); m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE); m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE); m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE); #ifdef __APPLE__ m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE); #else m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE); #endif j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE); j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE); j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE); j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE); j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE); j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE); j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE); j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE); j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE); j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE); Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE ); cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE ); cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("teamtask", "0", CVAR_USERINFO ); Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("password", "", CVAR_USERINFO); Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); #ifdef USE_MUMBLE cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH); cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE); #endif #ifdef USE_VOIP cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0); cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0); cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE); cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE); cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE); cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE); cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE); cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE); Cvar_CheckRange( cl_voip, 0, 1, qtrue ); cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM); #endif Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE ); Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); Cmd_AddCommand ("cmd", CL_ForwardToServer_f); Cmd_AddCommand ("configstrings", CL_Configstrings_f); Cmd_AddCommand ("clientinfo", CL_Clientinfo_f); Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f); Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f); Cmd_AddCommand ("disconnect", CL_Disconnect_f); Cmd_AddCommand ("record", CL_Record_f); Cmd_AddCommand ("demo", CL_PlayDemo_f); Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName ); Cmd_AddCommand ("cinematic", CL_PlayCinematic_f); Cmd_AddCommand ("stoprecord", CL_StopRecord_f); Cmd_AddCommand ("connect", CL_Connect_f); Cmd_AddCommand ("reconnect", CL_Reconnect_f); Cmd_AddCommand ("localservers", CL_LocalServers_f); Cmd_AddCommand ("globalservers", CL_GlobalServers_f); Cmd_AddCommand ("rcon", CL_Rcon_f); Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon ); Cmd_AddCommand ("ping", CL_Ping_f ); Cmd_AddCommand ("serverstatus", CL_ServerStatus_f ); Cmd_AddCommand ("showip", CL_ShowIP_f ); Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f ); Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f ); Cmd_AddCommand ("model", CL_SetModel_f ); Cmd_AddCommand ("video", CL_Video_f ); Cmd_AddCommand ("stopvideo", CL_StopVideo_f ); if( !com_dedicated->integer ) { Cmd_AddCommand ("sayto", CL_Sayto_f ); Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName ); } CL_InitRef(); SCR_Init (); Cvar_Set( "cl_running", "1" ); CL_GenerateQKey(); Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM ); CL_UpdateGUID( NULL, 0 ); Com_Printf( "----- Client Initialization Complete -----\n" ); } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269 Target: 1 Example 2: Code: int snd_seq_port_disconnect(struct snd_seq_client *connector, struct snd_seq_client *src_client, struct snd_seq_client_port *src_port, struct snd_seq_client *dest_client, struct snd_seq_client_port *dest_port, struct snd_seq_port_subscribe *info) { struct snd_seq_port_subs_info *src = &src_port->c_src; struct snd_seq_subscribers *subs; int err = -ENOENT; down_write(&src->list_mutex); /* look for the connection */ list_for_each_entry(subs, &src->list_head, src_list) { if (match_subs_info(info, &subs->info)) { atomic_dec(&subs->ref_count); /* mark as not ready */ err = 0; break; } } up_write(&src->list_mutex); if (err < 0) return err; delete_and_unsubscribe_port(src_client, src_port, subs, true, connector->number != src_client->number); delete_and_unsubscribe_port(dest_client, dest_port, subs, false, connector->number != dest_client->number); kfree(subs); return 0; } Commit Message: ALSA: seq: Fix use-after-free at creating a port There is a potential race window opened at creating and deleting a port via ioctl, as spotted by fuzzing. snd_seq_create_port() creates a port object and returns its pointer, but it doesn't take the refcount, thus it can be deleted immediately by another thread. Meanwhile, snd_seq_ioctl_create_port() still calls the function snd_seq_system_client_ev_port_start() with the created port object that is being deleted, and this triggers use-after-free like: BUG: KASAN: use-after-free in snd_seq_ioctl_create_port+0x504/0x630 [snd_seq] at addr ffff8801f2241cb1 ============================================================================= BUG kmalloc-512 (Tainted: G B ): kasan: bad access detected ----------------------------------------------------------------------------- INFO: Allocated in snd_seq_create_port+0x94/0x9b0 [snd_seq] age=1 cpu=3 pid=4511 ___slab_alloc+0x425/0x460 __slab_alloc+0x20/0x40 kmem_cache_alloc_trace+0x150/0x190 snd_seq_create_port+0x94/0x9b0 [snd_seq] snd_seq_ioctl_create_port+0xd1/0x630 [snd_seq] snd_seq_do_ioctl+0x11c/0x190 [snd_seq] snd_seq_ioctl+0x40/0x80 [snd_seq] do_vfs_ioctl+0x54b/0xda0 SyS_ioctl+0x79/0x90 entry_SYSCALL_64_fastpath+0x16/0x75 INFO: Freed in port_delete+0x136/0x1a0 [snd_seq] age=1 cpu=2 pid=4717 __slab_free+0x204/0x310 kfree+0x15f/0x180 port_delete+0x136/0x1a0 [snd_seq] snd_seq_delete_port+0x235/0x350 [snd_seq] snd_seq_ioctl_delete_port+0xc8/0x180 [snd_seq] snd_seq_do_ioctl+0x11c/0x190 [snd_seq] snd_seq_ioctl+0x40/0x80 [snd_seq] do_vfs_ioctl+0x54b/0xda0 SyS_ioctl+0x79/0x90 entry_SYSCALL_64_fastpath+0x16/0x75 Call Trace: [<ffffffff81b03781>] dump_stack+0x63/0x82 [<ffffffff81531b3b>] print_trailer+0xfb/0x160 [<ffffffff81536db4>] object_err+0x34/0x40 [<ffffffff815392d3>] kasan_report.part.2+0x223/0x520 [<ffffffffa07aadf4>] ? snd_seq_ioctl_create_port+0x504/0x630 [snd_seq] [<ffffffff815395fe>] __asan_report_load1_noabort+0x2e/0x30 [<ffffffffa07aadf4>] snd_seq_ioctl_create_port+0x504/0x630 [snd_seq] [<ffffffffa07aa8f0>] ? snd_seq_ioctl_delete_port+0x180/0x180 [snd_seq] [<ffffffff8136be50>] ? taskstats_exit+0xbc0/0xbc0 [<ffffffffa07abc5c>] snd_seq_do_ioctl+0x11c/0x190 [snd_seq] [<ffffffffa07abd10>] snd_seq_ioctl+0x40/0x80 [snd_seq] [<ffffffff8136d433>] ? acct_account_cputime+0x63/0x80 [<ffffffff815b515b>] do_vfs_ioctl+0x54b/0xda0 ..... We may fix this in a few different ways, and in this patch, it's fixed simply by taking the refcount properly at snd_seq_create_port() and letting the caller unref the object after use. Also, there is another potential use-after-free by sprintf() call in snd_seq_create_port(), and this is moved inside the lock. This fix covers CVE-2017-15265. Reported-and-tested-by: Michael23 Yu <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void a2dp_open_ctrl_path(struct a2dp_stream_common *common) { int i; /* retry logic to catch any timing variations on control channel */ for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { /* connect control channel if not already connected */ if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0) { /* success, now check if stack is ready */ if (check_a2dp_ready(common) == 0) break; ERROR("error : a2dp not ready, wait 250 ms and retry"); usleep(250000); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; } /* ctrl channel not ready, wait a bit */ usleep(250000); } } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char *argv[]) { char *fin, *fout; FILE *fpin, *fpout; uint8_t *inbuf, *outbuf; uint8_t *inbuf_u, *outbuf_u; uint8_t *inbuf_v, *outbuf_v; int f, frames; int width, height, target_width, target_height; if (argc < 5) { printf("Incorrect parameters:\n"); usage(argv[0]); return 1; } fin = argv[1]; fout = argv[4]; if (!parse_dim(argv[2], &width, &height)) { printf("Incorrect parameters: %s\n", argv[2]); usage(argv[0]); return 1; } if (!parse_dim(argv[3], &target_width, &target_height)) { printf("Incorrect parameters: %s\n", argv[3]); usage(argv[0]); return 1; } fpin = fopen(fin, "rb"); if (fpin == NULL) { printf("Can't open file %s to read\n", fin); usage(argv[0]); return 1; } fpout = fopen(fout, "wb"); if (fpout == NULL) { printf("Can't open file %s to write\n", fout); usage(argv[0]); return 1; } if (argc >= 6) frames = atoi(argv[5]); else frames = INT_MAX; printf("Input size: %dx%d\n", width, height); printf("Target size: %dx%d, Frames: ", target_width, target_height); if (frames == INT_MAX) printf("All\n"); else printf("%d\n", frames); inbuf = (uint8_t*)malloc(width * height * 3 / 2); outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2); inbuf_u = inbuf + width * height; inbuf_v = inbuf_u + width * height / 4; outbuf_u = outbuf + target_width * target_height; outbuf_v = outbuf_u + target_width * target_height / 4; f = 0; while (f < frames) { if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1) break; vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2, height, width, outbuf, target_width, outbuf_u, outbuf_v, target_width / 2, target_height, target_width); fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout); f++; } printf("%d frames processed\n", f); fclose(fpin); fclose(fpout); free(inbuf); free(outbuf); return 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: init_ssl_lib (void) { crypto_init_lib (); } Commit Message: Use constant time memcmp when comparing HMACs in openvpn_decrypt. Signed-off-by: Steffan Karger <[email protected]> Acked-by: Gert Doering <[email protected]> Signed-off-by: Gert Doering <[email protected]> CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { return gss_verify_mic_iov(minor_status, context_handle, qop_state, iov, iov_count); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE omx_vdec::update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn) { OMX_ERRORTYPE eRet = OMX_ErrorNone; struct v4l2_format fmt; if (!portDefn) { return OMX_ErrorBadParameter; } DEBUG_PRINT_LOW("omx_vdec::update_portdef"); portDefn->nVersion.nVersion = OMX_SPEC_VERSION; portDefn->nSize = sizeof(portDefn); portDefn->eDomain = OMX_PortDomainVideo; if (drv_ctx.frame_rate.fps_denominator > 0) portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator) << 16; //Q16 format else { DEBUG_PRINT_ERROR("Error: Divide by zero"); return OMX_ErrorBadParameter; } memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (0 == portDefn->nPortIndex) { portDefn->eDir = OMX_DirInput; portDefn->nBufferCountActual = drv_ctx.ip_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.ip_buf.mincount; portDefn->nBufferSize = drv_ctx.ip_buf.buffer_size; portDefn->format.video.eColorFormat = OMX_COLOR_FormatUnused; portDefn->format.video.eCompressionFormat = eCompressionFormat; portDefn->bEnabled = m_inp_bEnabled; portDefn->bPopulated = m_inp_bPopulated; fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.pixelformat = output_capability; } else if (1 == portDefn->nPortIndex) { unsigned int buf_size = 0; if (!client_buffers.update_buffer_req()) { DEBUG_PRINT_ERROR("client_buffers.update_buffer_req Failed"); return OMX_ErrorHardware; } if (!client_buffers.get_buffer_req(buf_size)) { DEBUG_PRINT_ERROR("update buffer requirements"); return OMX_ErrorHardware; } portDefn->nBufferSize = buf_size; portDefn->eDir = OMX_DirOutput; portDefn->nBufferCountActual = drv_ctx.op_buf.actualcount; portDefn->nBufferCountMin = drv_ctx.op_buf.mincount; portDefn->format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; portDefn->bEnabled = m_out_bEnabled; portDefn->bPopulated = m_out_bPopulated; if (!client_buffers.get_color_format(portDefn->format.video.eColorFormat)) { DEBUG_PRINT_ERROR("Error in getting color format"); return OMX_ErrorHardware; } fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; } else { portDefn->eDir = OMX_DirMax; DEBUG_PRINT_LOW(" get_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } if (is_down_scalar_enabled) { int ret = 0; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("update_portdef : Error in getting port resolution"); return OMX_ErrorHardware; } else { portDefn->format.video.nFrameWidth = fmt.fmt.pix_mp.width; portDefn->format.video.nFrameHeight = fmt.fmt.pix_mp.height; portDefn->format.video.nStride = fmt.fmt.pix_mp.plane_fmt[0].bytesperline; portDefn->format.video.nSliceHeight = fmt.fmt.pix_mp.plane_fmt[0].reserved[0]; } } else { portDefn->format.video.nFrameHeight = drv_ctx.video_resolution.frame_height; portDefn->format.video.nFrameWidth = drv_ctx.video_resolution.frame_width; portDefn->format.video.nStride = drv_ctx.video_resolution.stride; portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.scan_lines; } if ((portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420Planar) || (portDefn->format.video.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)) { portDefn->format.video.nStride = ALIGN(drv_ctx.video_resolution.frame_width, 16); portDefn->format.video.nSliceHeight = drv_ctx.video_resolution.frame_height; } DEBUG_PRINT_HIGH("update_portdef(%u): Width = %u Height = %u Stride = %d " "SliceHeight = %u eColorFormat = %d nBufSize %u nBufCnt %u", (unsigned int)portDefn->nPortIndex, (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nStride, (unsigned int)portDefn->format.video.nSliceHeight, (unsigned int)portDefn->format.video.eColorFormat, (unsigned int)portDefn->nBufferSize, (unsigned int)portDefn->nBufferCountActual); 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 Target: 1 Example 2: Code: const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void) { return ((OPENSSL_ia32cap_P[1] & AESNI_CAPABLE) && aesni_cbc_sha256_enc(NULL, NULL, 0, NULL, NULL, NULL, NULL) ? &aesni_128_cbc_hmac_sha256_cipher : NULL); } Commit Message: CWE ID: CWE-310 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; state = (struct inflate_state FAR *)strm->state; return ((long)(state->back) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } Commit Message: Avoid shifts of negative values inflateMark(). The C standard says that bit shifts of negative integers is undefined. This casts to unsigned values to assure a known result. CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WORD32 ixheaacd_real_synth_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer, WORD32 num_columns, FLOAT32 qmf_buf_real[][64], FLOAT32 qmf_buf_imag[][64]) { WORD32 i, j, k, l, idx; FLOAT32 g[640]; FLOAT32 w[640]; FLOAT32 synth_out[128]; FLOAT32 accu_r; WORD32 synth_size = ptr_hbe_txposer->synth_size; FLOAT32 *ptr_cos_tab_trans_qmf = (FLOAT32 *)&ixheaacd_cos_table_trans_qmf[0][0] + ptr_hbe_txposer->k_start * 32; FLOAT32 *buffer = ptr_hbe_txposer->synth_buf; for (idx = 0; idx < num_columns; idx++) { FLOAT32 loc_qmf_buf[64]; FLOAT32 *synth_buf_r = loc_qmf_buf; FLOAT32 *out_buf = ptr_hbe_txposer->ptr_input_buf + (idx + 1) * ptr_hbe_txposer->synth_size; FLOAT32 *synth_cos_tab = ptr_hbe_txposer->synth_cos_tab; const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->synth_wind_coeff; if (ptr_hbe_txposer->k_start < 0) return -1; for (k = 0; k < synth_size; k++) { WORD32 ki = ptr_hbe_txposer->k_start + k; synth_buf_r[k] = (FLOAT32)( ptr_cos_tab_trans_qmf[(k << 1) + 0] * qmf_buf_real[idx][ki] + ptr_cos_tab_trans_qmf[(k << 1) + 1] * qmf_buf_imag[idx][ki]); synth_buf_r[k + ptr_hbe_txposer->synth_size] = 0; } for (l = (20 * synth_size - 1); l >= 2 * synth_size; l--) { buffer[l] = buffer[l - 2 * synth_size]; } if (synth_size == 20) { FLOAT32 *psynth_cos_tab = synth_cos_tab; for (l = 0; l < (synth_size + 1); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[synth_size - l] = accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } for (l = (synth_size + 1); l < (2 * synth_size - synth_size / 2); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[3 * synth_size - l] = -accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[3 * synth_size >> 1] = accu_r; } else { FLOAT32 tmp; FLOAT32 *ptr_u = synth_out; WORD32 kmax = (synth_size >> 1); FLOAT32 *syn_buf = &buffer[kmax]; kmax += synth_size; if (ixheaacd_real_synth_fft != NULL) (*ixheaacd_real_synth_fft)(synth_buf_r, synth_out, synth_size * 2); else return -1; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } syn_buf = &buffer[0]; kmax -= synth_size; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } } for (i = 0; i < 5; i++) { memcpy(&g[(2 * i + 0) * synth_size], &buffer[(4 * i + 0) * synth_size], sizeof(FLOAT32) * synth_size); memcpy(&g[(2 * i + 1) * synth_size], &buffer[(4 * i + 3) * synth_size], sizeof(FLOAT32) * synth_size); } for (k = 0; k < 10 * synth_size; k++) { w[k] = g[k] * interp_window_coeff[k]; } for (i = 0; i < synth_size; i++) { accu_r = 0.0; for (j = 0; j < 10; j++) { accu_r = accu_r + w[synth_size * j + i]; } out_buf[i] = (FLOAT32)accu_r; } } return 0; } Commit Message: Fix for stack corruption in esbr Bug: 110769924 Test: poc from bug before/after Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e (cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a) (cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50) CWE ID: CWE-787 Target: 1 Example 2: Code: FindBar* BrowserView::CreateFindBar() { return chrome::CreateFindBar(this); } 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 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct packet_sock *po = pkt_sk(sk); int ret; if (level != SOL_PACKET) return -ENOPROTOOPT; switch (optname) { case PACKET_ADD_MEMBERSHIP: case PACKET_DROP_MEMBERSHIP: { struct packet_mreq_max mreq; int len = optlen; memset(&mreq, 0, sizeof(mreq)); if (len < sizeof(struct packet_mreq)) return -EINVAL; if (len > sizeof(mreq)) len = sizeof(mreq); if (copy_from_user(&mreq, optval, len)) return -EFAULT; if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address))) return -EINVAL; if (optname == PACKET_ADD_MEMBERSHIP) ret = packet_mc_add(sk, &mreq); else ret = packet_mc_drop(sk, &mreq); return ret; } case PACKET_RX_RING: case PACKET_TX_RING: { union tpacket_req_u req_u; int len; switch (po->tp_version) { case TPACKET_V1: case TPACKET_V2: len = sizeof(req_u.req); break; case TPACKET_V3: default: len = sizeof(req_u.req3); break; } if (optlen < len) return -EINVAL; if (copy_from_user(&req_u.req, optval, len)) return -EFAULT; return packet_set_ring(sk, &req_u, 0, optname == PACKET_TX_RING); } case PACKET_COPY_THRESH: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; pkt_sk(sk)->copy_thresh = val; return 0; } case PACKET_VERSION: { int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; switch (val) { case TPACKET_V1: case TPACKET_V2: case TPACKET_V3: po->tp_version = val; return 0; default: return -EINVAL; } } case PACKET_RESERVE: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_reserve = val; return 0; } case PACKET_LOSS: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_loss = !!val; return 0; } case PACKET_AUXDATA: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->auxdata = !!val; return 0; } case PACKET_ORIGDEV: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->origdev = !!val; return 0; } case PACKET_VNET_HDR: { int val; if (sock->type != SOCK_RAW) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->has_vnet_hdr = !!val; return 0; } case PACKET_TIMESTAMP: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tstamp = val; return 0; } case PACKET_FANOUT: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; return fanout_add(sk, val & 0xffff, val >> 16); } case PACKET_FANOUT_DATA: { if (!po->fanout) return -EINVAL; return fanout_set_data(po, optval, optlen); } case PACKET_TX_HAS_OFF: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tx_has_off = !!val; return 0; } case PACKET_QDISC_BYPASS: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->xmit = val ? packet_direct_xmit : dev_queue_xmit; return 0; } default: return -ENOPROTOOPT; } } Commit Message: packet: fix race condition in packet_set_ring When packet_set_ring creates a ring buffer it will initialize a struct timer_list if the packet version is TPACKET_V3. This value can then be raced by a different thread calling setsockopt to set the version to TPACKET_V1 before packet_set_ring has finished. This leads to a use-after-free on a function pointer in the struct timer_list when the socket is closed as the previously initialized timer will not be deleted. The bug is fixed by taking lock_sock(sk) in packet_setsockopt when changing the packet version while also taking the lock at the start of packet_set_ring. Fixes: f6fb8f100b80 ("af-packet: TPACKET_V3 flexible buffer implementation.") Signed-off-by: Philip Pettersson <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) { DCHECK(message_loop()->BelongsToCurrentThread()); if (!stream_id_) return; if (state == AudioOutputIPCDelegate::kError) { DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)"; base::AutoLock auto_lock_(audio_thread_lock_); if (audio_thread_.get() && !audio_thread_->IsStopped()) callback_->OnRenderError(); } } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 1 Example 2: Code: WORD32 ih264d_parse_pmb_ref_index_cavlc(UWORD32 u4_num_part, /* Number of partitions in MB */ dec_bit_stream_t *ps_bitstrm, /* Pointer to bitstream Structure. */ WORD8 *pi1_ref_idx, /* pointer to reference index array */ UWORD32 u4_num_ref_idx_active_minus1 /* Number of active references - 1 */ ) { UWORD32 u4_i; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstream_off = &ps_bitstrm->u4_ofst; for(u4_i = 0; u4_i < u4_num_part; u4_i++) { UWORD32 u4_ref_idx; UWORD32 u4_bitstream_offset = *pu4_bitstream_off; UWORD32 u4_word, u4_ldz; /***************************************************************/ /* Find leading zeros in next 32 bits */ /***************************************************************/ NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf); u4_ldz = CLZ(u4_word); /* Flush the ps_bitstrm */ u4_bitstream_offset += (u4_ldz + 1); /* Read the suffix from the ps_bitstrm */ u4_word = 0; if(u4_ldz) GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf, u4_ldz); *pu4_bitstream_off = u4_bitstream_offset; u4_ref_idx = ((1 << u4_ldz) + u4_word - 1); if(u4_ref_idx > u4_num_ref_idx_active_minus1) return ERROR_REF_IDX; /* Storing Reference Idx Information */ pi1_ref_idx[u4_i] = (WORD8)u4_ref_idx; } return OK; } Commit Message: Decoder: Fix stack underflow in CAVLC 4x4 parse functions Bug: 26399350 Change-Id: Id768751672a7b093ab6e53d4fc0b3188d470920e CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int mwifiex_uap_prepare_cmd(struct mwifiex_private *priv, u16 cmd_no, u16 cmd_action, u32 type, void *data_buf, void *cmd_buf) { struct host_cmd_ds_command *cmd = cmd_buf; switch (cmd_no) { case HostCmd_CMD_UAP_SYS_CONFIG: if (mwifiex_cmd_uap_sys_config(cmd, cmd_action, type, data_buf)) return -1; break; case HostCmd_CMD_UAP_BSS_START: case HostCmd_CMD_UAP_BSS_STOP: case HOST_CMD_APCMD_SYS_RESET: case HOST_CMD_APCMD_STA_LIST: cmd->command = cpu_to_le16(cmd_no); cmd->size = cpu_to_le16(S_DS_GEN); break; case HostCmd_CMD_UAP_STA_DEAUTH: if (mwifiex_cmd_uap_sta_deauth(priv, cmd, data_buf)) return -1; break; case HostCmd_CMD_CHAN_REPORT_REQUEST: if (mwifiex_cmd_issue_chan_report_request(priv, cmd_buf, data_buf)) return -1; break; default: mwifiex_dbg(priv->adapter, ERROR, "PREP_CMD: unknown cmd %#x\n", cmd_no); return -1; } return 0; } Commit Message: mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and mwifiex_set_wmm_params() call memcpy() without checking the destination size.Since the source is given from user-space, this may trigger a heap buffer overflow. Fix them by putting the length check before performing memcpy(). This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816. Signed-off-by: Wen Huang <[email protected]> Acked-by: Ganapathi Bhat <[email protected]> Signed-off-by: Kalle Valo <[email protected]> CWE ID: CWE-120 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::string GetDMToken() { std::string dm_token = *GetTestingDMToken(); #if !defined(OS_CHROMEOS) if (dm_token.empty() && policy::ChromeBrowserCloudManagementController::IsEnabled()) { dm_token = policy::BrowserDMTokenStorage::Get()->RetrieveDMToken(); } #endif return dm_token; } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20 Target: 1 Example 2: Code: void WebGLRenderingContextBase::DrawingBufferClientRestoreScissorTest() { if (destruction_in_progress_) return; if (!ContextGL()) return; if (scissor_enabled_) ContextGL()->Enable(GL_SCISSOR_TEST); else ContextGL()->Disable(GL_SCISSOR_TEST); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct blk_flush_queue *blk_alloc_flush_queue(struct request_queue *q, int node, int cmd_size) { struct blk_flush_queue *fq; int rq_sz = sizeof(struct request); fq = kzalloc_node(sizeof(*fq), GFP_KERNEL, node); if (!fq) goto fail; if (q->mq_ops) { spin_lock_init(&fq->mq_flush_lock); rq_sz = round_up(rq_sz + cmd_size, cache_line_size()); } fq->flush_rq = kzalloc_node(rq_sz, GFP_KERNEL, node); if (!fq->flush_rq) goto fail_rq; INIT_LIST_HEAD(&fq->flush_queue[0]); INIT_LIST_HEAD(&fq->flush_queue[1]); INIT_LIST_HEAD(&fq->flush_data_in_flight); return fq; fail_rq: kfree(fq); fail: return NULL; } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: gdImageScaleTwoPass(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height) { const unsigned int src_width = src->sx; const unsigned int src_height = src->sy; gdImagePtr tmp_im = NULL; gdImagePtr dst = NULL; /* First, handle the trivial case. */ if (src_width == new_width && src_height == new_height) { return gdImageClone(src); }/* if */ /* Convert to truecolor if it isn't; this code requires it. */ if (!src->trueColor) { gdImagePaletteToTrueColor(src); }/* if */ /* Scale horizontally unless sizes are the same. */ if (src_width == new_width) { tmp_im = src; } else { tmp_im = gdImageCreateTrueColor(new_width, src_height); if (tmp_im == NULL) { return NULL; } gdImageSetInterpolationMethod(tmp_im, src->interpolation_id); _gdScalePass(src, src_width, tmp_im, new_width, src_height, HORIZONTAL); }/* if .. else*/ /* If vertical sizes match, we're done. */ if (src_height == new_height) { assert(tmp_im != src); return tmp_im; }/* if */ /* Otherwise, we need to scale vertically. */ dst = gdImageCreateTrueColor(new_width, new_height); if (dst != NULL) { gdImageSetInterpolationMethod(dst, src->interpolation_id); _gdScalePass(tmp_im, src_height, dst, new_height, new_width, VERTICAL); }/* if */ if (src != tmp_im) { gdFree(tmp_im); }/* if */ return dst; }/* gdImageScaleTwoPass*/ Commit Message: gdImageScaleTwoPass memory leak fix Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and confirmed by @vapier. This bug actually bit me in production and I'm very thankful that it was reported with an easy fix. Fixes #173. CWE ID: CWE-399 Target: 1 Example 2: Code: void WebPagePrivate::releaseLayerResourcesCompositingThread() { m_compositor->releaseLayerResources(); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int clear_hub_feature(struct usb_device *hdev, int feature) { return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0), USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000); } Commit Message: USB: fix invalid memory access in hub_activate() Commit 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") changed the hub_activate() routine to make part of it run in a workqueue. However, the commit failed to take a reference to the usb_hub structure or to lock the hub interface while doing so. As a result, if a hub is plugged in and quickly unplugged before the work routine can run, the routine will try to access memory that has been deallocated. Or, if the hub is unplugged while the routine is running, the memory may be deallocated while it is in active use. This patch fixes the problem by taking a reference to the usb_hub at the start of hub_activate() and releasing it at the end (when the work is finished), and by locking the hub interface while the work routine is running. It also adds a check at the start of the routine to see if the hub has already been disconnected, in which nothing should be done. Signed-off-by: Alan Stern <[email protected]> Reported-by: Alexandru Cornea <[email protected]> Tested-by: Alexandru Cornea <[email protected]> Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SessionRestoreImpl(Profile* profile, Browser* browser, bool synchronous, bool clobber_existing_tab, bool always_create_tabbed_browser, const std::vector<GURL>& urls_to_open) : profile_(profile), browser_(browser), synchronous_(synchronous), clobber_existing_tab_(clobber_existing_tab), always_create_tabbed_browser_(always_create_tabbed_browser), urls_to_open_(urls_to_open), restore_started_(base::TimeTicks::Now()), browser_shown_(false) { if (profiles_getting_restored == NULL) profiles_getting_restored = new std::set<const Profile*>(); CHECK(profiles_getting_restored->find(profile) == profiles_getting_restored->end()); profiles_getting_restored->insert(profile); g_browser_process->AddRefModule(); } Commit Message: Lands http://codereview.chromium.org/9316065/ for Marja. I reviewed this, so I'm using TBR to land it. Don't crash if multiple SessionRestoreImpl:s refer to the same Profile. It shouldn't ever happen but it seems to happen anyway. BUG=111238 TEST=NONE [email protected] [email protected] Review URL: https://chromiumcodereview.appspot.com/9343005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120648 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: int FLTIsTemporalFilterType(const char *pszValue) { if (pszValue) { if ( strcasecmp(pszValue, "During") == 0 ) return MS_TRUE; } return MS_FALSE; } Commit Message: security fix (patch by EvenR) CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct pgpath *alloc_pgpath(void) { struct pgpath *pgpath = kzalloc(sizeof(*pgpath), GFP_KERNEL); if (pgpath) { pgpath->is_active = 1; INIT_DELAYED_WORK(&pgpath->activate_path, activate_path); } return pgpath; } Commit Message: dm: do not forward ioctls from logical volumes to the underlying device A logical volume can map to just part of underlying physical volume. In this case, it must be treated like a partition. Based on a patch from Alasdair G Kergon. Cc: Alasdair G Kergon <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int vorbis_book_unpack(oggpack_buffer *opb,codebook *s){ char *lengthlist=NULL; int quantvals=0; long i,j; int maptype; memset(s,0,sizeof(*s)); /* make sure alignment is correct */ if(oggpack_read(opb,24)!=0x564342)goto _eofout; /* first the basic parameters */ s->dim=oggpack_read(opb,16); s->dec_buf=_ogg_malloc(sizeof(ogg_int32_t)*s->dim); if (s->dec_buf == NULL) goto _errout; s->entries=oggpack_read(opb,24); if(s->entries<=0)goto _eofout; if(s->dim<=0)goto _eofout; if(_ilog(s->dim)+_ilog(s->entries)>24)goto _eofout; if (s->dim > INT_MAX/s->entries) goto _eofout; /* codeword ordering.... length ordered or unordered? */ switch((int)oggpack_read(opb,1)){ case 0: /* unordered */ lengthlist=(char *)calloc(s->entries, sizeof(*lengthlist)); if(!lengthlist) goto _eofout; /* allocated but unused entries? */ if(oggpack_read(opb,1)){ /* yes, unused entries */ for(i=0;i<s->entries;i++){ if(oggpack_read(opb,1)){ long num=oggpack_read(opb,5); if(num==-1)goto _eofout; lengthlist[i]=(char)(num+1); s->used_entries++; if(num+1>s->dec_maxlength)s->dec_maxlength=num+1; }else lengthlist[i]=0; } }else{ /* all entries used; no tagging */ s->used_entries=s->entries; for(i=0;i<s->entries;i++){ long num=oggpack_read(opb,5); if(num==-1)goto _eofout; lengthlist[i]=(char)(num+1); if(num+1>s->dec_maxlength)s->dec_maxlength=num+1; } } break; case 1: /* ordered */ { long length=oggpack_read(opb,5)+1; s->used_entries=s->entries; lengthlist=(char *)calloc(s->entries, sizeof(*lengthlist)); if (!lengthlist) goto _eofout; for(i=0;i<s->entries;){ long num=oggpack_read(opb,_ilog(s->entries-i)); if(num<0)goto _eofout; for(j=0;j<num && i<s->entries;j++,i++) lengthlist[i]=(char)length; s->dec_maxlength=length; length++; } } break; default: /* EOF */ goto _eofout; } /* Do we have a mapping to unpack? */ if((maptype=oggpack_read(opb,4))>0){ s->q_min=_float32_unpack(oggpack_read(opb,32),&s->q_minp); s->q_del=_float32_unpack(oggpack_read(opb,32),&s->q_delp); s->q_bits=oggpack_read(opb,4)+1; s->q_seq=oggpack_read(opb,1); s->q_del>>=s->q_bits; s->q_delp+=s->q_bits; } switch(maptype){ case 0: /* no mapping; decode type 0 */ /* how many bytes for the indexing? */ /* this is the correct boundary here; we lose one bit to node/leaf mark */ s->dec_nodeb=_determine_node_bytes(s->used_entries,_ilog(s->entries)/8+1); s->dec_leafw=_determine_leaf_words(s->dec_nodeb,_ilog(s->entries)/8+1); s->dec_type=0; if(_make_decode_table(s,lengthlist,quantvals,opb,maptype)) goto _errout; break; case 1: /* mapping type 1; implicit values by lattice position */ quantvals=_book_maptype1_quantvals(s); /* dec_type choices here are 1,2; 3 doesn't make sense */ { /* packed values */ long total1=(s->q_bits*s->dim+8)/8; /* remember flag bit */ if (s->dim > (INT_MAX-8)/s->q_bits) goto _eofout; /* vector of column offsets; remember flag bit */ long total2=(_ilog(quantvals-1)*s->dim+8)/8+(s->q_bits+7)/8; if(total1<=4 && total1<=total2){ /* use dec_type 1: vector of packed values */ /* need quantized values before */ s->q_val=calloc(sizeof(ogg_uint16_t), quantvals); if (!s->q_val) goto _eofout; for(i=0;i<quantvals;i++) ((ogg_uint16_t *)s->q_val)[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits); if(oggpack_eop(opb)){ goto _eofout; } s->dec_type=1; s->dec_nodeb=_determine_node_bytes(s->used_entries, (s->q_bits*s->dim+8)/8); s->dec_leafw=_determine_leaf_words(s->dec_nodeb, (s->q_bits*s->dim+8)/8); if(_make_decode_table(s,lengthlist,quantvals,opb,maptype)){ goto _errout; } free(s->q_val); s->q_val=0; }else{ /* use dec_type 2: packed vector of column offsets */ /* need quantized values before */ if(s->q_bits<=8){ s->q_val=_ogg_malloc(quantvals); if (!s->q_val) goto _eofout; for(i=0;i<quantvals;i++) ((unsigned char *)s->q_val)[i]=(unsigned char)oggpack_read(opb,s->q_bits); }else{ s->q_val=_ogg_malloc(quantvals*2); if (!s->q_val) goto _eofout; for(i=0;i<quantvals;i++) ((ogg_uint16_t *)s->q_val)[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits); } if(oggpack_eop(opb))goto _eofout; s->q_pack=_ilog(quantvals-1); s->dec_type=2; s->dec_nodeb=_determine_node_bytes(s->used_entries, (_ilog(quantvals-1)*s->dim+8)/8); s->dec_leafw=_determine_leaf_words(s->dec_nodeb, (_ilog(quantvals-1)*s->dim+8)/8); if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout; } } break; case 2: /* mapping type 2; explicit array of values */ quantvals=s->entries*s->dim; /* dec_type choices here are 1,3; 2 is not possible */ if( (s->q_bits*s->dim+8)/8 <=4){ /* remember flag bit */ /* use dec_type 1: vector of packed values */ s->dec_type=1; s->dec_nodeb=_determine_node_bytes(s->used_entries,(s->q_bits*s->dim+8)/8); s->dec_leafw=_determine_leaf_words(s->dec_nodeb,(s->q_bits*s->dim+8)/8); if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout; }else{ /* use dec_type 3: scalar offset into packed value array */ s->dec_type=3; s->dec_nodeb=_determine_node_bytes(s->used_entries,_ilog(s->used_entries-1)/8+1); s->dec_leafw=_determine_leaf_words(s->dec_nodeb,_ilog(s->used_entries-1)/8+1); if(_make_decode_table(s,lengthlist,quantvals,opb,maptype))goto _errout; /* get the vals & pack them */ s->q_pack=(s->q_bits+7)/8*s->dim; s->q_val=_ogg_malloc(s->q_pack*s->used_entries); if(s->q_bits<=8){ for(i=0;i<s->used_entries*s->dim;i++) ((unsigned char *)(s->q_val))[i]=(unsigned char)oggpack_read(opb,s->q_bits); }else{ for(i=0;i<s->used_entries*s->dim;i++) ((ogg_uint16_t *)(s->q_val))[i]=(ogg_uint16_t)oggpack_read(opb,s->q_bits); } } break; default: goto _errout; } if (s->dec_nodeb==1) if (s->dec_leafw == 1) s->dec_method = 0; else s->dec_method = 1; else if (s->dec_nodeb==2) if (s->dec_leafw == 1) s->dec_method = 2; else s->dec_method = 3; else s->dec_method = 4; if(oggpack_eop(opb))goto _eofout; free(lengthlist); return 0; _errout: _eofout: vorbis_book_clear(s); free(lengthlist); free(s->q_val); return -1; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200 Target: 1 Example 2: Code: DECL_PIOCTL(PStoreBehind) { struct sbstruct sbr; if (afs_pd_getBytes(ain, &sbr, sizeof(struct sbstruct)) != 0) return EINVAL; if (sbr.sb_default != -1) { if (afs_osi_suser(*acred)) afs_defaultAsynchrony = sbr.sb_default; else return EPERM; } if (avc && (sbr.sb_thisfile != -1)) { if (afs_AccessOK (avc, PRSFS_WRITE | PRSFS_ADMINISTER, areq, DONT_CHECK_MODE_BITS)) avc->asynchrony = sbr.sb_thisfile; else return EACCES; } memset(&sbr, 0, sizeof(sbr)); sbr.sb_default = afs_defaultAsynchrony; if (avc) { sbr.sb_thisfile = avc->asynchrony; } return afs_pd_putBytes(aout, &sbr, sizeof(sbr)); } Commit Message: CWE ID: CWE-189 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: error::Error GLES2DecoderPassthroughImpl::DoEnableFeatureCHROMIUM( const char* feature) { NOTIMPLEMENTED(); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(void) { int fd, len, sock_opt; int error; struct cn_msg *message; struct pollfd pfd; struct nlmsghdr *incoming_msg; struct cn_msg *incoming_cn_msg; struct hv_kvp_msg *hv_msg; char *p; char *key_value; char *key_name; int op; int pool; char *if_name; struct hv_kvp_ipaddr_value *kvp_ip_val; daemon(1, 0); openlog("KVP", 0, LOG_USER); syslog(LOG_INFO, "KVP starting; pid is:%d", getpid()); /* * Retrieve OS release information. */ kvp_get_os_info(); if (kvp_file_init()) { syslog(LOG_ERR, "Failed to initialize the pools"); exit(EXIT_FAILURE); } fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); if (fd < 0) { syslog(LOG_ERR, "netlink socket creation failed; error:%d", fd); exit(EXIT_FAILURE); } addr.nl_family = AF_NETLINK; addr.nl_pad = 0; addr.nl_pid = 0; addr.nl_groups = CN_KVP_IDX; error = bind(fd, (struct sockaddr *)&addr, sizeof(addr)); if (error < 0) { syslog(LOG_ERR, "bind failed; error:%d", error); close(fd); exit(EXIT_FAILURE); } sock_opt = addr.nl_groups; setsockopt(fd, 270, 1, &sock_opt, sizeof(sock_opt)); /* * Register ourselves with the kernel. */ message = (struct cn_msg *)kvp_send_buffer; message->id.idx = CN_KVP_IDX; message->id.val = CN_KVP_VAL; hv_msg = (struct hv_kvp_msg *)message->data; hv_msg->kvp_hdr.operation = KVP_OP_REGISTER1; message->ack = 0; message->len = sizeof(struct hv_kvp_msg); len = netlink_send(fd, message); if (len < 0) { syslog(LOG_ERR, "netlink_send failed; error:%d", len); close(fd); exit(EXIT_FAILURE); } pfd.fd = fd; while (1) { struct sockaddr *addr_p = (struct sockaddr *) &addr; socklen_t addr_l = sizeof(addr); pfd.events = POLLIN; pfd.revents = 0; poll(&pfd, 1, -1); len = recvfrom(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0, addr_p, &addr_l); if (len < 0 || addr.nl_pid) { syslog(LOG_ERR, "recvfrom failed; pid:%u error:%d %s", addr.nl_pid, errno, strerror(errno)); close(fd); return -1; } incoming_msg = (struct nlmsghdr *)kvp_recv_buffer; incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg); hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data; /* * We will use the KVP header information to pass back * the error from this daemon. So, first copy the state * and set the error code to success. */ op = hv_msg->kvp_hdr.operation; pool = hv_msg->kvp_hdr.pool; hv_msg->error = HV_S_OK; if ((in_hand_shake) && (op == KVP_OP_REGISTER1)) { /* * Driver is registering with us; stash away the version * information. */ in_hand_shake = 0; p = (char *)hv_msg->body.kvp_register.version; lic_version = malloc(strlen(p) + 1); if (lic_version) { strcpy(lic_version, p); syslog(LOG_INFO, "KVP LIC Version: %s", lic_version); } else { syslog(LOG_ERR, "malloc failed"); } continue; } switch (op) { case KVP_OP_GET_IP_INFO: kvp_ip_val = &hv_msg->body.kvp_ip_val; if_name = kvp_mac_to_if_name((char *)kvp_ip_val->adapter_id); if (if_name == NULL) { /* * We could not map the mac address to an * interface name; return error. */ hv_msg->error = HV_E_FAIL; break; } error = kvp_get_ip_info( 0, if_name, KVP_OP_GET_IP_INFO, kvp_ip_val, (MAX_IP_ADDR_SIZE * 2)); if (error) hv_msg->error = error; free(if_name); break; case KVP_OP_SET_IP_INFO: kvp_ip_val = &hv_msg->body.kvp_ip_val; if_name = kvp_get_if_name( (char *)kvp_ip_val->adapter_id); if (if_name == NULL) { /* * We could not map the guid to an * interface name; return error. */ hv_msg->error = HV_GUID_NOTFOUND; break; } error = kvp_set_ip_info(if_name, kvp_ip_val); if (error) hv_msg->error = error; free(if_name); break; case KVP_OP_SET: if (kvp_key_add_or_modify(pool, hv_msg->body.kvp_set.data.key, hv_msg->body.kvp_set.data.key_size, hv_msg->body.kvp_set.data.value, hv_msg->body.kvp_set.data.value_size)) hv_msg->error = HV_S_CONT; break; case KVP_OP_GET: if (kvp_get_value(pool, hv_msg->body.kvp_set.data.key, hv_msg->body.kvp_set.data.key_size, hv_msg->body.kvp_set.data.value, hv_msg->body.kvp_set.data.value_size)) hv_msg->error = HV_S_CONT; break; case KVP_OP_DELETE: if (kvp_key_delete(pool, hv_msg->body.kvp_delete.key, hv_msg->body.kvp_delete.key_size)) hv_msg->error = HV_S_CONT; break; default: break; } if (op != KVP_OP_ENUMERATE) goto kvp_done; /* * If the pool is KVP_POOL_AUTO, dynamically generate * both the key and the value; if not read from the * appropriate pool. */ if (pool != KVP_POOL_AUTO) { if (kvp_pool_enumerate(pool, hv_msg->body.kvp_enum_data.index, hv_msg->body.kvp_enum_data.data.key, HV_KVP_EXCHANGE_MAX_KEY_SIZE, hv_msg->body.kvp_enum_data.data.value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE)) hv_msg->error = HV_S_CONT; goto kvp_done; } hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data; key_name = (char *)hv_msg->body.kvp_enum_data.data.key; key_value = (char *)hv_msg->body.kvp_enum_data.data.value; switch (hv_msg->body.kvp_enum_data.index) { case FullyQualifiedDomainName: kvp_get_domain_name(key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "FullyQualifiedDomainName"); break; case IntegrationServicesVersion: strcpy(key_name, "IntegrationServicesVersion"); strcpy(key_value, lic_version); break; case NetworkAddressIPv4: kvp_get_ip_info(AF_INET, NULL, KVP_OP_ENUMERATE, key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "NetworkAddressIPv4"); break; case NetworkAddressIPv6: kvp_get_ip_info(AF_INET6, NULL, KVP_OP_ENUMERATE, key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE); strcpy(key_name, "NetworkAddressIPv6"); break; case OSBuildNumber: strcpy(key_value, os_build); strcpy(key_name, "OSBuildNumber"); break; case OSName: strcpy(key_value, os_name); strcpy(key_name, "OSName"); break; case OSMajorVersion: strcpy(key_value, os_major); strcpy(key_name, "OSMajorVersion"); break; case OSMinorVersion: strcpy(key_value, os_minor); strcpy(key_name, "OSMinorVersion"); break; case OSVersion: strcpy(key_value, os_version); strcpy(key_name, "OSVersion"); break; case ProcessorArchitecture: strcpy(key_value, processor_arch); strcpy(key_name, "ProcessorArchitecture"); break; default: hv_msg->error = HV_S_CONT; break; } /* * Send the value back to the kernel. The response is * already in the receive buffer. Update the cn_msg header to * reflect the key value that has been added to the message */ kvp_done: incoming_cn_msg->id.idx = CN_KVP_IDX; incoming_cn_msg->id.val = CN_KVP_VAL; incoming_cn_msg->ack = 0; incoming_cn_msg->len = sizeof(struct hv_kvp_msg); len = netlink_send(fd, incoming_cn_msg); if (len < 0) { syslog(LOG_ERR, "net_link send failed; error:%d", len); exit(EXIT_FAILURE); } } } Commit Message: tools: hv: Netlink source address validation allows DoS The source code without this patch caused hypervkvpd to exit when it processed a spoofed Netlink packet which has been sent from an untrusted local user. Now Netlink messages with a non-zero nl_pid source address are ignored and a warning is printed into the syslog. Signed-off-by: Tomas Hozza <[email protected]> Acked-by: K. Y. Srinivasan <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Target: 1 Example 2: Code: void RenderFrameDevToolsAgentHost::RenderProcessGone( base::TerminationStatus status) { switch(status) { case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: #if defined(OS_CHROMEOS) case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM: #endif case base::TERMINATION_STATUS_PROCESS_CRASHED: #if defined(OS_ANDROID) case base::TERMINATION_STATUS_OOM_PROTECTED: #endif case base::TERMINATION_STATUS_LAUNCH_FAILED: for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); break; default: for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetDetached("Render process gone."); break; } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC) { GC_REFCOUNT(ht) = 1; GC_TYPE_INFO(ht) = IS_ARRAY; ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS; ht->nTableSize = zend_hash_check_size(nSize); ht->nTableMask = HT_MIN_MASK; HT_SET_DATA_ADDR(ht, &uninitialized_bucket); ht->nNumUsed = 0; ht->nNumOfElements = 0; ht->nInternalPointer = HT_INVALID_IDX; ht->nNextFreeElement = 0; ht->pDestructor = pDestructor; } Commit Message: Fix #73832 - leave the table in a safe state if the size is too big. CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ssl2_generate_key_material(SSL *s) { unsigned int i; EVP_MD_CTX ctx; unsigned char *km; unsigned char c = '0'; const EVP_MD *md5; int md_size; md5 = EVP_md5(); # ifdef CHARSET_EBCDIC c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see * SSLv2 docu */ # endif EVP_MD_CTX_init(&ctx); km = s->s2->key_material; if (s->session->master_key_length < 0 || s->session->master_key_length > (int)sizeof(s->session->master_key)) { SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } md_size = EVP_MD_size(md5); if (md_size < 0) return 0; for (i = 0; i < s->s2->key_material_length; i += md_size) { if (((km - s->s2->key_material) + md_size) > (int)sizeof(s->s2->key_material)) { /* * EVP_DigestFinal_ex() below would write beyond buffer */ SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR); return 0; } EVP_DigestInit_ex(&ctx, md5, NULL); OPENSSL_assert(s->session->master_key_length >= 0 && s->session->master_key_length < (int)sizeof(s->session->master_key)); EVP_DigestUpdate(&ctx, s->session->master_key, s->session->master_key_length); EVP_DigestUpdate(&ctx, &c, 1); c++; EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length); EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length); EVP_DigestFinal_ex(&ctx, km, NULL); km += md_size; } EVP_MD_CTX_cleanup(&ctx); return 1; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: virDomainGetVcpus(virDomainPtr domain, virVcpuInfoPtr info, int maxinfo, unsigned char *cpumaps, int maplen) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p, maxinfo=%d, cpumaps=%p, maplen=%d", info, maxinfo, cpumaps, maplen); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); virCheckPositiveArgGoto(maxinfo, error); /* Ensure that domainGetVcpus (aka remoteDomainGetVcpus) does not try to memcpy anything into a NULL pointer. */ if (cpumaps) virCheckPositiveArgGoto(maplen, error); else virCheckZeroArgGoto(maplen, error); if (cpumaps && INT_MULTIPLY_OVERFLOW(maxinfo, maplen)) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"), maxinfo, maplen); goto error; } conn = domain->conn; if (conn->driver->domainGetVcpus) { int ret; ret = conn->driver->domainGetVcpus(domain, info, maxinfo, cpumaps, maplen); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } Commit Message: virDomainGetTime: Deny on RO connections We have a policy that if API may end up talking to a guest agent it should require RW connection. We don't obey the rule in virDomainGetTime(). Signed-off-by: Michal Privoznik <[email protected]> CWE ID: CWE-254 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: double WebContentsImpl::GetZoomLevel() const { HostZoomMapImpl* zoom_map = static_cast<HostZoomMapImpl*>( HostZoomMap::GetForBrowserContext(GetBrowserContext())); if (!zoom_map) return 0; double zoom_level; if (temporary_zoom_settings_) { zoom_level = zoom_map->GetTemporaryZoomLevel( GetRenderProcessHost()->GetID(), GetRenderViewHost()->GetRoutingID()); } else { GURL url; NavigationEntry* active_entry = GetController().GetActiveEntry(); url = active_entry ? active_entry->GetURL() : GURL::EmptyGURL(); zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(), net::GetHostOrSpecFromURL(url)); } return zoom_level; } Commit Message: Cancel JavaScript dialogs when an interstitial appears. BUG=295695 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/24360011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: hb_buffer_clear (hb_buffer_t *buffer) { buffer->have_output = FALSE; buffer->have_positions = FALSE; buffer->len = 0; buffer->out_len = 0; buffer->i = 0; buffer->max_lig_id = 0; buffer->max_lig_id = 0; } Commit Message: CWE ID: Target: 1 Example 2: Code: void base_audio_entry_dump(GF_AudioSampleEntryBox *p, FILE * trace) { fprintf(trace, " DataReferenceIndex=\"%d\" SampleRate=\"%d\"", p->dataReferenceIndex, p->samplerate_hi); fprintf(trace, " Channels=\"%d\" BitsPerSample=\"%d\"", p->channel_count, p->bitspersample); } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int libevt_record_values_get_type( libevt_record_values_t *record_values, uint8_t *type, libcerror_error_t **error ) { static char *function = "libevt_record_values_get_type"; if( record_values == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid record values.", function ); return( -1 ); } if( type == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid type.", function ); return( -1 ); } *type = record_values->type; return( 1 ); } Commit Message: Applied updates and addition boundary checks for corrupted data CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static av_always_inline int filter_fast_3320(APEPredictor *p, const int decoded, const int filter, const int delayA) { int32_t predictionA; p->buf[delayA] = p->lastA[filter]; if (p->sample_pos < 3) { p->lastA[filter] = decoded; p->filterA[filter] = decoded; return decoded; } predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1]; p->lastA[filter] = decoded + (predictionA * p->coeffsA[filter][0] >> 9); if ((decoded ^ predictionA) > 0) p->coeffsA[filter][0]++; else p->coeffsA[filter][0]--; p->filterA[filter] += p->lastA[filter]; return p->filterA[filter]; } Commit Message: avcodec/apedec: Fix integer overflow Fixes: out of array access Fixes: PoC.ape and others Found-by: Bingchang, Liu@VARAS of IIE Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-125 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::CreateAudioOutputStreamFactory( mojom::RendererAudioOutputStreamFactoryRequest request) { if (base::FeatureList::IsEnabled(features::kAudioServiceAudioStreams)) { media::AudioSystem* audio_system = BrowserMainLoop::GetInstance()->audio_system(); MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); audio_service_audio_output_stream_factory_.emplace( this, audio_system, media_stream_manager, std::move(request)); } else { RendererAudioOutputStreamFactoryContext* factory_context = GetProcess()->GetRendererAudioOutputStreamFactoryContext(); DCHECK(factory_context); in_content_audio_output_stream_factory_ = RenderFrameAudioOutputStreamFactoryHandle::CreateFactory( factory_context, GetRoutingID(), std::move(request)); } } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod) { struct usbnet *dev; struct net_device *net; struct usb_host_interface *interface; struct driver_info *info; struct usb_device *xdev; int status; const char *name; struct usb_driver *driver = to_usb_driver(udev->dev.driver); /* usbnet already took usb runtime pm, so have to enable the feature * for usb interface, otherwise usb_autopm_get_interface may return * failure if RUNTIME_PM is enabled. */ if (!driver->supports_autosuspend) { driver->supports_autosuspend = 1; pm_runtime_enable(&udev->dev); } name = udev->dev.driver->name; info = (struct driver_info *) prod->driver_info; if (!info) { dev_dbg (&udev->dev, "blacklisted by %s\n", name); return -ENODEV; } xdev = interface_to_usbdev (udev); interface = udev->cur_altsetting; status = -ENOMEM; net = alloc_etherdev(sizeof(*dev)); if (!net) goto out; /* netdev_printk() needs this so do it as early as possible */ SET_NETDEV_DEV(net, &udev->dev); dev = netdev_priv(net); dev->udev = xdev; dev->intf = udev; dev->driver_info = info; dev->driver_name = name; dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); init_waitqueue_head(&dev->wait); skb_queue_head_init (&dev->rxq); skb_queue_head_init (&dev->txq); skb_queue_head_init (&dev->done); skb_queue_head_init(&dev->rxq_pause); dev->bh.func = usbnet_bh; dev->bh.data = (unsigned long) dev; INIT_WORK (&dev->kevent, usbnet_deferred_kevent); init_usb_anchor(&dev->deferred); dev->delay.function = usbnet_bh; dev->delay.data = (unsigned long) dev; init_timer (&dev->delay); mutex_init (&dev->phy_mutex); mutex_init(&dev->interrupt_mutex); dev->interrupt_count = 0; dev->net = net; strcpy (net->name, "usb%d"); memcpy (net->dev_addr, node_id, sizeof node_id); /* rx and tx sides can use different message sizes; * bind() should set rx_urb_size in that case. */ dev->hard_mtu = net->mtu + net->hard_header_len; net->netdev_ops = &usbnet_netdev_ops; net->watchdog_timeo = TX_TIMEOUT_JIFFIES; net->ethtool_ops = &usbnet_ethtool_ops; if (info->bind) { status = info->bind (dev, udev); if (status < 0) goto out1; if ((dev->driver_info->flags & FLAG_ETHER) != 0 && ((dev->driver_info->flags & FLAG_POINTTOPOINT) == 0 || (net->dev_addr [0] & 0x02) == 0)) strcpy (net->name, "eth%d"); /* WLAN devices should always be named "wlan%d" */ if ((dev->driver_info->flags & FLAG_WLAN) != 0) strcpy(net->name, "wlan%d"); /* WWAN devices should always be named "wwan%d" */ if ((dev->driver_info->flags & FLAG_WWAN) != 0) strcpy(net->name, "wwan%d"); /* devices that cannot do ARP */ if ((dev->driver_info->flags & FLAG_NOARP) != 0) net->flags |= IFF_NOARP; /* maybe the remote can't receive an Ethernet MTU */ if (net->mtu > (dev->hard_mtu - net->hard_header_len)) net->mtu = dev->hard_mtu - net->hard_header_len; } else if (!info->in || !info->out) status = usbnet_get_endpoints (dev, udev); else { dev->in = usb_rcvbulkpipe (xdev, info->in); dev->out = usb_sndbulkpipe (xdev, info->out); if (!(info->flags & FLAG_NO_SETINT)) status = usb_set_interface (xdev, interface->desc.bInterfaceNumber, interface->desc.bAlternateSetting); else status = 0; } if (status >= 0 && dev->status) status = init_status (dev, udev); if (status < 0) goto out3; if (!dev->rx_urb_size) dev->rx_urb_size = dev->hard_mtu; dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1); /* let userspace know we have a random address */ if (ether_addr_equal(net->dev_addr, node_id)) net->addr_assign_type = NET_ADDR_RANDOM; if ((dev->driver_info->flags & FLAG_WLAN) != 0) SET_NETDEV_DEVTYPE(net, &wlan_type); if ((dev->driver_info->flags & FLAG_WWAN) != 0) SET_NETDEV_DEVTYPE(net, &wwan_type); /* initialize max rx_qlen and tx_qlen */ usbnet_update_max_qlen(dev); if (dev->can_dma_sg && !(info->flags & FLAG_SEND_ZLP) && !(info->flags & FLAG_MULTI_PACKET)) { dev->padding_pkt = kzalloc(1, GFP_KERNEL); if (!dev->padding_pkt) { status = -ENOMEM; goto out4; } } status = register_netdev (net); if (status) goto out5; netif_info(dev, probe, dev->net, "register '%s' at usb-%s-%s, %s, %pM\n", udev->dev.driver->name, xdev->bus->bus_name, xdev->devpath, dev->driver_info->description, net->dev_addr); usb_set_intfdata (udev, dev); netif_device_attach (net); if (dev->driver_info->flags & FLAG_LINK_INTR) usbnet_link_change(dev, 0, 0); return 0; out5: kfree(dev->padding_pkt); out4: usb_free_urb(dev->interrupt); out3: if (info->unbind) info->unbind (dev, udev); out1: free_netdev(net); out: return status; } Commit Message: usbnet: cleanup after bind() in probe() In case bind() works, but a later error forces bailing in probe() in error cases work and a timer may be scheduled. They must be killed. This fixes an error case related to the double free reported in http://www.spinics.net/lists/netdev/msg367669.html and needs to go on top of Linus' fix to cdc-ncm. Signed-off-by: Oliver Neukum <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: int truncate_xattr_node(struct inode *inode, struct page *page) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); nid_t nid = F2FS_I(inode)->i_xattr_nid; struct dnode_of_data dn; struct page *npage; if (!nid) return 0; npage = get_node_page(sbi, nid); if (IS_ERR(npage)) return PTR_ERR(npage); f2fs_i_xnid_write(inode, 0); set_new_dnode(&dn, inode, page, npage, nid); if (page) dn.inode_page_locked = true; truncate_node(&dn); return 0; } Commit Message: f2fs: fix race condition in between free nid allocator/initializer In below concurrent case, allocated nid can be loaded into free nid cache and be allocated again. Thread A Thread B - f2fs_create - f2fs_new_inode - alloc_nid - __insert_nid_to_list(ALLOC_NID_LIST) - f2fs_balance_fs_bg - build_free_nids - __build_free_nids - scan_nat_page - add_free_nid - __lookup_nat_cache - f2fs_add_link - init_inode_metadata - new_inode_page - new_node_page - set_node_addr - alloc_nid_done - __remove_nid_from_list(ALLOC_NID_LIST) - __insert_nid_to_list(FREE_NID_LIST) This patch makes nat cache lookup and free nid list operation being atomical to avoid this race condition. Signed-off-by: Jaegeuk Kim <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-362 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void gdImageFilledArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color, int style) { gdPoint pts[363]; int i, pti; int lx = 0, ly = 0; int fx = 0, fy = 0; if ((s % 360) == (e % 360)) { s = 0; e = 360; } else { if (s > 360) { s = s % 360; } if (e > 360) { e = e % 360; } while (s < 0) { s += 360; } while (e < s) { e += 360; } if (s == e) { s = 0; e = 360; } } for (i = s, pti = 1; i <= e; i++, pti++) { int x, y; x = ((long) gdCosT[i % 360] * (long) w / (2 * 1024)) + cx; y = ((long) gdSinT[i % 360] * (long) h / (2 * 1024)) + cy; if (i != s) { if (!(style & gdChord)) { if (style & gdNoFill) { gdImageLine(im, lx, ly, x, y, color); } else { if (y == ly) { pti--; /* don't add this point */ if (((i > 270 || i < 90) && x > lx) || ((i > 90 && i < 270) && x < lx)) { /* replace the old x coord, if increasing on the right side or decreasing on the left side */ pts[pti].x = x; } } else { pts[pti].x = x; pts[pti].y = y; } } } } else { fx = x; fy = y; if (!(style & (gdChord | gdNoFill))) { pts[0].x = cx; pts[0].y = cy; pts[pti].x = x; pts[pti].y = y; } } lx = x; ly = y; } if (style & gdChord) { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine(im, cx, cy, lx, ly, color); gdImageLine(im, cx, cy, fx, fy, color); } gdImageLine(im, fx, fy, lx, ly, color); } else { pts[0].x = fx; pts[0].y = fy; pts[1].x = lx; pts[1].y = ly; pts[2].x = cx; pts[2].y = cy; gdImageFilledPolygon(im, pts, 3, color); } } else { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine(im, cx, cy, lx, ly, color); gdImageLine(im, cx, cy, fx, fy, color); } } else { pts[pti].x = cx; pts[pti].y = cy; gdImageFilledPolygon(im, pts, pti+1, color); } } } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ContentEncoding::ContentEncryption::ContentEncryption() : algo(0), key_id(NULL), key_id_len(0), signature(NULL), signature_len(0), sig_key_id(NULL), sig_key_id_len(0), sig_algo(0), sig_hash_algo(0) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static void stroke_list(private_stroke_socket_t *this, stroke_msg_t *msg, FILE *out) { if (msg->list.flags & LIST_CAINFOS) { this->ca->list(this->ca, msg, out); } this->list->list(this->list, msg, out); } Commit Message: CWE ID: CWE-787 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: __imlib_Ellipse_DrawToData(int xc, int yc, int a, int b, DATA32 color, DATA32 * dst, int dstw, int clx, int cly, int clw, int clh, ImlibOp op, char dst_alpha, char blend) { ImlibPointDrawFunction pfunc; int xx, yy, x, y, prev_x, prev_y, ty, by, lx, rx; DATA32 a2, b2, *tp, *bp; DATA64 dx, dy; if (A_VAL(&color) == 0xff) blend = 0; pfunc = __imlib_GetPointDrawFunction(op, dst_alpha, blend); if (!pfunc) return; xc -= clx; yc -= cly; dst += (dstw * cly) + clx; a2 = a * a; b2 = b * b; yy = b << 16; prev_y = b; dx = a2 * b; dy = 0; ty = yc - b - 1; by = yc + b; lx = xc - 1; rx = xc; tp = dst + (dstw * ty) + lx; bp = dst + (dstw * by) + lx; while (dy < dx) { int len; y = yy >> 16; y += ((yy - (y << 16)) >> 15); if (prev_y != y) { prev_y = y; dx -= a2; ty++; by--; tp += dstw; bp -= dstw; } len = rx - lx; if (IN_RANGE(lx, ty, clw, clh)) pfunc(color, tp); if (IN_RANGE(rx, ty, clw, clh)) pfunc(color, tp + len); if (IN_RANGE(lx, by, clw, clh)) pfunc(color, bp); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); dy += b2; yy -= ((dy << 16) / dx); lx--; if ((lx < 0) && (rx > clw)) return; if ((ty > clh) || (by < 0)) return; } xx = yy; prev_x = xx >> 16; dx = dy; ty++; by--; tp += dstw; bp -= dstw; while (ty < yc) { int len; x = xx >> 16; x += ((xx - (x << 16)) >> 15); if (prev_x != x) { prev_x = x; dy += b2; lx--; rx++; tp--; bp--; } len = rx - lx; if (IN_RANGE(lx, ty, clw, clh)) pfunc(color, tp); if (IN_RANGE(rx, ty, clw, clh)) pfunc(color, tp + len); if (IN_RANGE(lx, by, clw, clh)) pfunc(color, bp); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); dx -= a2; xx += ((dx << 16) / dy); ty++; if ((ty > clh) || (by < 0)) return; } } Commit Message: CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dtls1_process_buffered_records(SSL *s) { pitem *item; item = pqueue_peek(s->d1->unprocessed_rcds.q); if (item) { /* Check if epoch is current. */ if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) return(1); /* Nothing to do. */ /* Process all the records. */ while (pqueue_peek(s->d1->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if ( ! dtls1_process_record(s)) return(0); dtls1_buffer_record(s, &(s->d1->processed_rcds), s->s3->rrec.seq_num); } } /* sync epoch numbers once all the unprocessed records * have been processed */ s->d1->processed_rcds.epoch = s->d1->r_epoch; s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1; return(1); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void OnSuggestionModelRemoved(UiScene* scene, SuggestionBinding* binding) { scene->RemoveUiElement(binding->view()->id()); } 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 <[email protected]> Commit-Queue: Biao She <[email protected]> Cr-Commit-Position: refs/heads/master@{#525806} CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len) { struct sctp_chunk *sack; struct timer_list *timer; if (asoc->rwnd_over) { if (asoc->rwnd_over >= len) { asoc->rwnd_over -= len; } else { asoc->rwnd += (len - asoc->rwnd_over); asoc->rwnd_over = 0; } } else { asoc->rwnd += len; } /* If we had window pressure, start recovering it * once our rwnd had reached the accumulated pressure * threshold. The idea is to recover slowly, but up * to the initial advertised window. */ if (asoc->rwnd_press && asoc->rwnd >= asoc->rwnd_press) { int change = min(asoc->pathmtu, asoc->rwnd_press); asoc->rwnd += change; asoc->rwnd_press -= change; } pr_debug("%s: asoc:%p rwnd increased by %d to (%u, %u) - %u\n", __func__, asoc, len, asoc->rwnd, asoc->rwnd_over, asoc->a_rwnd); /* Send a window update SACK if the rwnd has increased by at least the * minimum of the association's PMTU and half of the receive buffer. * The algorithm used is similar to the one described in * Section 4.2.3.3 of RFC 1122. */ if (sctp_peer_needs_update(asoc)) { asoc->a_rwnd = asoc->rwnd; pr_debug("%s: sending window update SACK- asoc:%p rwnd:%u " "a_rwnd:%u\n", __func__, asoc, asoc->rwnd, asoc->a_rwnd); sack = sctp_make_sack(asoc); if (!sack) return; asoc->peer.sack_needed = 0; sctp_outq_tail(&asoc->outqueue, sack); /* Stop the SACK timer. */ timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK]; if (del_timer(timer)) sctp_association_put(asoc); } } Commit Message: net: sctp: inherit auth_capable on INIT collisions Jason reported an oops caused by SCTP on his ARM machine with SCTP authentication enabled: Internal error: Oops: 17 [#1] ARM CPU: 0 PID: 104 Comm: sctp-test Not tainted 3.13.0-68744-g3632f30c9b20-dirty #1 task: c6eefa40 ti: c6f52000 task.ti: c6f52000 PC is at sctp_auth_calculate_hmac+0xc4/0x10c LR is at sg_init_table+0x20/0x38 pc : [<c024bb80>] lr : [<c00f32dc>] psr: 40000013 sp : c6f538e8 ip : 00000000 fp : c6f53924 r10: c6f50d80 r9 : 00000000 r8 : 00010000 r7 : 00000000 r6 : c7be4000 r5 : 00000000 r4 : c6f56254 r3 : c00c8170 r2 : 00000001 r1 : 00000008 r0 : c6f1e660 Flags: nZcv IRQs on FIQs on Mode SVC_32 ISA ARM Segment user Control: 0005397f Table: 06f28000 DAC: 00000015 Process sctp-test (pid: 104, stack limit = 0xc6f521c0) Stack: (0xc6f538e8 to 0xc6f54000) [...] Backtrace: [<c024babc>] (sctp_auth_calculate_hmac+0x0/0x10c) from [<c0249af8>] (sctp_packet_transmit+0x33c/0x5c8) [<c02497bc>] (sctp_packet_transmit+0x0/0x5c8) from [<c023e96c>] (sctp_outq_flush+0x7fc/0x844) [<c023e170>] (sctp_outq_flush+0x0/0x844) from [<c023ef78>] (sctp_outq_uncork+0x24/0x28) [<c023ef54>] (sctp_outq_uncork+0x0/0x28) from [<c0234364>] (sctp_side_effects+0x1134/0x1220) [<c0233230>] (sctp_side_effects+0x0/0x1220) from [<c02330b0>] (sctp_do_sm+0xac/0xd4) [<c0233004>] (sctp_do_sm+0x0/0xd4) from [<c023675c>] (sctp_assoc_bh_rcv+0x118/0x160) [<c0236644>] (sctp_assoc_bh_rcv+0x0/0x160) from [<c023d5bc>] (sctp_inq_push+0x6c/0x74) [<c023d550>] (sctp_inq_push+0x0/0x74) from [<c024a6b0>] (sctp_rcv+0x7d8/0x888) While we already had various kind of bugs in that area ec0223ec48a9 ("net: sctp: fix sctp_sf_do_5_1D_ce to verify if we/peer is AUTH capable") and b14878ccb7fa ("net: sctp: cache auth_enable per endpoint"), this one is a bit of a different kind. Giving a bit more background on why SCTP authentication is needed can be found in RFC4895: SCTP uses 32-bit verification tags to protect itself against blind attackers. These values are not changed during the lifetime of an SCTP association. Looking at new SCTP extensions, there is the need to have a method of proving that an SCTP chunk(s) was really sent by the original peer that started the association and not by a malicious attacker. To cause this bug, we're triggering an INIT collision between peers; normal SCTP handshake where both sides intent to authenticate packets contains RANDOM; CHUNKS; HMAC-ALGO parameters that are being negotiated among peers: ---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------> <------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------- -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- RFC4895 says that each endpoint therefore knows its own random number and the peer's random number *after* the association has been established. The local and peer's random number along with the shared key are then part of the secret used for calculating the HMAC in the AUTH chunk. Now, in our scenario, we have 2 threads with 1 non-blocking SEQ_PACKET socket each, setting up common shared SCTP_AUTH_KEY and SCTP_AUTH_ACTIVE_KEY properly, and each of them calling sctp_bindx(3), listen(2) and connect(2) against each other, thus the handshake looks similar to this, e.g.: ---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------> <------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------- <--------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------- -------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------> ... Since such collisions can also happen with verification tags, the RFC4895 for AUTH rather vaguely says under section 6.1: In case of INIT collision, the rules governing the handling of this Random Number follow the same pattern as those for the Verification Tag, as explained in Section 5.2.4 of RFC 2960 [5]. Therefore, each endpoint knows its own Random Number and the peer's Random Number after the association has been established. In RFC2960, section 5.2.4, we're eventually hitting Action B: B) In this case, both sides may be attempting to start an association at about the same time but the peer endpoint started its INIT after responding to the local endpoint's INIT. Thus it may have picked a new Verification Tag not being aware of the previous Tag it had sent this endpoint. The endpoint should stay in or enter the ESTABLISHED state but it MUST update its peer's Verification Tag from the State Cookie, stop any init or cookie timers that may running and send a COOKIE ACK. In other words, the handling of the Random parameter is the same as behavior for the Verification Tag as described in Action B of section 5.2.4. Looking at the code, we exactly hit the sctp_sf_do_dupcook_b() case which triggers an SCTP_CMD_UPDATE_ASSOC command to the side effect interpreter, and in fact it properly copies over peer_{random, hmacs, chunks} parameters from the newly created association to update the existing one. Also, the old asoc_shared_key is being released and based on the new params, sctp_auth_asoc_init_active_key() updated. However, the issue observed in this case is that the previous asoc->peer.auth_capable was 0, and has *not* been updated, so that instead of creating a new secret, we're doing an early return from the function sctp_auth_asoc_init_active_key() leaving asoc->asoc_shared_key as NULL. However, we now have to authenticate chunks from the updated chunk list (e.g. COOKIE-ACK). That in fact causes the server side when responding with ... <------------------ AUTH; COOKIE-ACK ----------------- ... to trigger a NULL pointer dereference, since in sctp_packet_transmit(), it discovers that an AUTH chunk is being queued for xmit, and thus it calls sctp_auth_calculate_hmac(). Since the asoc->active_key_id is still inherited from the endpoint, and the same as encoded into the chunk, it uses asoc->asoc_shared_key, which is still NULL, as an asoc_key and dereferences it in ... crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len) ... causing an oops. All this happens because sctp_make_cookie_ack() called with the *new* association has the peer.auth_capable=1 and therefore marks the chunk with auth=1 after checking sctp_auth_send_cid(), but it is *actually* sent later on over the then *updated* association's transport that didn't initialize its shared key due to peer.auth_capable=0. Since control chunks in that case are not sent by the temporary association which are scheduled for deletion, they are issued for xmit via SCTP_CMD_REPLY in the interpreter with the context of the *updated* association. peer.auth_capable was 0 in the updated association (which went from COOKIE_WAIT into ESTABLISHED state), since all previous processing that performed sctp_process_init() was being done on temporary associations, that we eventually throw away each time. The correct fix is to update to the new peer.auth_capable value as well in the collision case via sctp_assoc_update(), so that in case the collision migrated from 0 -> 1, sctp_auth_asoc_init_active_key() can properly recalculate the secret. This therefore fixes the observed server panic. Fixes: 730fc3d05cd4 ("[SCTP]: Implete SCTP-AUTH parameter processing") Reported-by: Jason Gunthorpe <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Tested-by: Jason Gunthorpe <[email protected]> Cc: Vlad Yasevich <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: standard_row_validate(standard_display *dp, png_const_structp pp, int iImage, int iDisplay, png_uint_32 y) { int where; png_byte std[STANDARD_ROWMAX]; /* The row must be pre-initialized to the magic number here for the size * tests to pass: */ memset(std, 178, sizeof std); standard_row(pp, std, dp->id, y); /* At the end both the 'row' and 'display' arrays should end up identical. * In earlier passes 'row' will be partially filled in, with only the pixels * that have been read so far, but 'display' will have those pixels * replicated to fill the unread pixels while reading an interlaced image. #if PNG_LIBPNG_VER < 10506 * The side effect inside the libpng sequential reader is that the 'row' * array retains the correct values for unwritten pixels within the row * bytes, while the 'display' array gets bits off the end of the image (in * the last byte) trashed. Unfortunately in the progressive reader the * row bytes are always trashed, so we always do a pixel_cmp here even though * a memcmp of all cbRow bytes will succeed for the sequential reader. #endif */ if (iImage >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iImage, y)[where-1]); png_error(pp, msg); } #if PNG_LIBPNG_VER < 10506 /* In this case use pixel_cmp because we need to compare a partial * byte at the end of the row if the row is not an exact multiple * of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is * changed to match!) */ #endif if (iDisplay >= 0 && (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y), dp->bit_width)) != 0) { char msg[64]; sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x", (unsigned long)y, where-1, std[where-1], store_image_row(dp->ps, pp, iDisplay, y)[where-1]); png_error(pp, msg); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: int ProfileChooserView::GetDiceSigninPromoShowCount() const { return browser_->profile()->GetPrefs()->GetInteger( prefs::kDiceSigninUserMenuPromoCount); } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool blk_mq_attempt_merge(struct request_queue *q, struct blk_mq_ctx *ctx, struct bio *bio) { struct request *rq; int checked = 8; list_for_each_entry_reverse(rq, &ctx->rq_list, queuelist) { int el_ret; if (!checked--) break; if (!blk_rq_merge_ok(rq, bio)) continue; el_ret = blk_try_merge(rq, bio); if (el_ret == ELEVATOR_BACK_MERGE) { if (bio_attempt_back_merge(q, rq, bio)) { ctx->rq_merged++; return true; } break; } else if (el_ret == ELEVATOR_FRONT_MERGE) { if (bio_attempt_front_merge(q, rq, bio)) { ctx->rq_merged++; return true; } break; } } return false; } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void ext4_invalidatepage(struct page *page, unsigned long offset) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); /* * If it's a full truncate we just forget about the pending dirtying */ if (offset == 0) ClearPageChecked(page); if (journal) jbd2_journal_invalidatepage(journal, page, offset); else block_invalidatepage(page, offset); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Target: 1 Example 2: Code: static MXFDescriptor* mxf_resolve_multidescriptor(MXFContext *mxf, MXFDescriptor *descriptor, int track_id) { MXFDescriptor *sub_descriptor = NULL; int i; if (!descriptor) return NULL; if (descriptor->type == MultipleDescriptor) { for (i = 0; i < descriptor->sub_descriptors_count; i++) { sub_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->sub_descriptors_refs[i], Descriptor); if (!sub_descriptor) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n"); continue; } if (sub_descriptor->linked_track_id == track_id) { return sub_descriptor; } } } else if (descriptor->type == Descriptor) return descriptor; return NULL; } Commit Message: avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array() Fixes: 20170829A.mxf Co-Author: 张洪亮(望初)" <[email protected]> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::DidCreateScriptContext(v8::Local<v8::Context> context, int world_id) { if ((enabled_bindings_ & BINDINGS_POLICY_MOJO_WEB_UI) && IsMainFrame() && world_id == ISOLATED_WORLD_ID_GLOBAL) { blink::WebContextFeatures::EnableMojoJS(context, true); } for (auto& observer : observers_) observer.DidCreateScriptContext(context, world_id); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int msg_cache_check(const char *id, struct BodyCache *bcache, void *data) { struct Context *ctx = (struct Context *) data; if (!ctx) return -1; struct PopData *pop_data = (struct PopData *) ctx->data; if (!pop_data) return -1; #ifdef USE_HCACHE /* keep hcache file if hcache == bcache */ if (strcmp(HC_FNAME "." HC_FEXT, id) == 0) return 0; #endif for (int i = 0; i < ctx->msgcount; i++) { /* if the id we get is known for a header: done (i.e. keep in cache) */ if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0)) return 0; } /* message not found in context -> remove it from cache * return the result of bcache, so we stop upon its first error */ return mutt_bcache_del(bcache, id); } Commit Message: sanitise cache paths Co-authored-by: JerikoOne <[email protected]> CWE ID: CWE-22 Target: 1 Example 2: Code: void QQuickWebViewExperimental::setFlickableViewportEnabled(bool enable) { s_flickableViewportEnabled = enable; } Commit Message: [Qt][WK2] Allow transparent WebViews https://bugs.webkit.org/show_bug.cgi?id=80608 Reviewed by Tor Arne Vestbø. Added support for transparentBackground in QQuickWebViewExperimental. This uses the existing drawsTransparentBackground property in WebKit2. Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes, otherwise the change doesn't take effect. A new API test was added. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::setTransparentBackground): (QQuickWebViewPrivate::transparentBackground): (QQuickWebViewExperimental::transparentBackground): (QQuickWebViewExperimental::setTransparentBackground): * UIProcess/API/qt/qquickwebview_p.h: * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): * UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp: (tst_QQuickWebView): (tst_QQuickWebView::transparentWebViews): * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::LayerTreeHostQt::LayerTreeHostQt): (WebKit::LayerTreeHostQt::setRootCompositingLayer): git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-189 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: chrm_modification_init(chrm_modification *me, png_modifier *pm, PNG_CONST color_encoding *encoding) { CIE_color white = white_point(encoding); /* Original end points: */ me->encoding = encoding; /* Chromaticities (in fixed point): */ me->wx = fix(chromaticity_x(white)); me->wy = fix(chromaticity_y(white)); me->rx = fix(chromaticity_x(encoding->red)); me->ry = fix(chromaticity_y(encoding->red)); me->gx = fix(chromaticity_x(encoding->green)); me->gy = fix(chromaticity_y(encoding->green)); me->bx = fix(chromaticity_x(encoding->blue)); me->by = fix(chromaticity_y(encoding->blue)); modification_init(&me->this); me->this.chunk = CHUNK_cHRM; me->this.modify_fn = chrm_modify; me->this.add = CHUNK_PLTE; me->this.next = pm->modifications; pm->modifications = &me->this; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert3(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); c* (toc(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->convert3(); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: static inline int decode_attr_length(struct xdr_stream *xdr, uint32_t *attrlen, __be32 **savep) { __be32 *p; READ_BUF(4); READ32(*attrlen); *savep = xdr->p; return 0; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int dtls1_process_buffered_records(SSL *s) { pitem *item; SSL3_BUFFER *rb; item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q); if (item) { /* Check if epoch is current. */ if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch) return (1); /* Nothing to do. */ rb = RECORD_LAYER_get_rbuf(&s->rlayer); */ return 1; } /* Process all the records. */ while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if (!dtls1_process_record(s)) return (0); if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds), /* Process all the records. */ while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if (!dtls1_process_record(s)) return (0); if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds), SSL3_RECORD_get_seq_num(s->rlayer.rrec)) < 0) return -1; } } * here, anything else is handled by higher layers * Application data protocol * none of our business */ s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch; s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1; return (1); } Commit Message: CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void keyring_describe(const struct key *keyring, struct seq_file *m) { if (keyring->description) seq_puts(m, keyring->description); else seq_puts(m, "[anon]"); if (key_is_instantiated(keyring)) { if (keyring->keys.nr_leaves_on_tree != 0) seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree); else seq_puts(m, ": empty"); } } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_coding_ext(dec_state_t *ps_dec) { stream_t *ps_stream; IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T) IV_SUCCESS; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); /* extension code identifier */ impeg2d_bit_stream_get(ps_stream,4); ps_dec->au2_f_code[0][0] = impeg2d_bit_stream_get(ps_stream,4); ps_dec->au2_f_code[0][1] = impeg2d_bit_stream_get(ps_stream,4); ps_dec->au2_f_code[1][0] = impeg2d_bit_stream_get(ps_stream,4); ps_dec->au2_f_code[1][1] = impeg2d_bit_stream_get(ps_stream,4); ps_dec->u2_intra_dc_precision = impeg2d_bit_stream_get(ps_stream,2); ps_dec->u2_picture_structure = impeg2d_bit_stream_get(ps_stream,2); if (ps_dec->u2_picture_structure < TOP_FIELD || ps_dec->u2_picture_structure > FRAME_PICTURE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } ps_dec->u2_top_field_first = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_frame_pred_frame_dct = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_concealment_motion_vectors = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_q_scale_type = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_intra_vlc_format = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_alternate_scan = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_repeat_first_field = impeg2d_bit_stream_get_bit(ps_stream); /* Flush chroma_420_type */ impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_progressive_frame = impeg2d_bit_stream_get_bit(ps_stream); if (impeg2d_bit_stream_get_bit(ps_stream)) { /* Flush v_axis, field_sequence, burst_amplitude, sub_carrier_phase */ impeg2d_bit_stream_flush(ps_stream,20); } impeg2d_next_start_code(ps_dec); if(VERTICAL_SCAN == ps_dec->u2_alternate_scan) { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_vertical; } else { ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_zig_zag; } return e_error; } Commit Message: Adding check for min_width and min_height Add check for min_wd and min_ht. Stride is updated if header decode is done. Bug: 74078669 Change-Id: Ided95395e1138335dbb4b05131a8551f6f7bbfcd (cherry picked from commit 84eba4863dd50083951db83ea3cc81e015bf51da) CWE ID: CWE-787 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { bool oldHorizontalWritingMode = isHorizontalWritingMode(); RenderBoxModelObject::styleDidChange(diff, oldStyle); RenderStyle* newStyle = style(); if (needsLayout() && oldStyle) { RenderBlock::removePercentHeightDescendantIfNeeded(this); if (isOutOfFlowPositioned() && newStyle->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle->marginBefore() && parent() && !parent()->normalChildNeedsLayout()) parent()->setChildNeedsLayout(); } if (RenderBlock::hasPercentHeightContainerMap() && firstChild() && oldHorizontalWritingMode != isHorizontalWritingMode()) RenderBlock::clearPercentHeightDescendantsFrom(this); if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) { if (int left = layer()->scrollableArea()->scrollXOffset()) { left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToXOffset(left); } if (int top = layer()->scrollableArea()->scrollYOffset()) { top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToYOffset(top); } } if (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer) { RenderObject* parentToInvalidate = parent(); for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) { parentToInvalidate->invalidateBackgroundObscurationStatus(); parentToInvalidate = parentToInvalidate->parent(); } } if (isDocumentElement() || isBody()) document().view()->recalculateScrollbarOverlayStyle(); updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle); updateGridPositionAfterStyleChange(oldStyle); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void OffscreenCanvas::Dispose() { if (context_) { context_->DetachHost(); context_ = nullptr; } if (HasPlaceholderCanvas() && GetTopExecutionContext() && GetTopExecutionContext()->IsWorkerGlobalScope()) { WorkerAnimationFrameProvider* animation_frame_provider = To<WorkerGlobalScope>(GetTopExecutionContext()) ->GetAnimationFrameProvider(); if (animation_frame_provider) animation_frame_provider->DeregisterOffscreenCanvas(this); } } Commit Message: Clean up CanvasResourceDispatcher on finalizer We may have pending mojo messages after GC, so we want to drop the dispatcher as soon as possible. Bug: 929757,913964 Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0 Reviewed-on: https://chromium-review.googlesource.com/c/1489175 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Auto-Submit: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#635833} CWE ID: CWE-416 Target: 1 Example 2: Code: static void conditionalLongAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { ExceptionState exceptionState(ExceptionState::SetterContext, "conditionalLongAttribute", "TestObjectPython", info.Holder(), info.GetIsolate()); TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); V8TRYCATCH_EXCEPTION_VOID(int, cppValue, toInt32(jsValue, exceptionState), exceptionState); imp->setConditionalLongAttribute(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SkiaOutputSurfaceImpl::DiscardBackbuffer() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); auto callback = base::BindOnce(&SkiaOutputSurfaceImplOnGpu::DiscardBackbuffer, base::Unretained(impl_on_gpu_.get())); task_sequence_->ScheduleOrRetainTask(std::move(callback), std::vector<gpu::SyncToken>()); } Commit Message: SkiaRenderer: Support changing color space SkiaOutputSurfaceImpl did not handle the color space changing after it was created previously. The SkSurfaceCharacterization color space was only set during the first time Reshape() ran when the charactization is returned from the GPU thread. If the color space was changed later the SkSurface and SkDDL color spaces no longer matched and draw failed. Bug: 1009452 Change-Id: Ib6d2083efc7e7eb6f94782342e92a809b69d6fdc Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1841811 Reviewed-by: Peng Huang <[email protected]> Commit-Queue: kylechar <[email protected]> Cr-Commit-Position: refs/heads/master@{#702946} CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0644); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269 Target: 1 Example 2: Code: bool RenderWidgetHostImpl::KeyPressListenersHandleEvent( const NativeWebKeyboardEvent& event) { if (event.skip_in_browser || event.GetType() != WebKeyboardEvent::kRawKeyDown) return false; for (size_t i = 0; i < key_press_event_callbacks_.size(); i++) { size_t original_size = key_press_event_callbacks_.size(); if (key_press_event_callbacks_[i].Run(event)) return true; size_t current_size = key_press_event_callbacks_.size(); if (current_size != original_size) { DCHECK_EQ(original_size - 1, current_size); --i; } } return false; } Commit Message: Start rendering timer after first navigation Currently the new content rendering timer in the browser process, which clears an old page's contents 4 seconds after a navigation if the new page doesn't draw in that time, is not set on the first navigation for a top-level frame. This is problematic because content can exist before the first navigation, for instance if it was created by a javascript: URL. This CL removes the code that skips the timer activation on the first navigation. Bug: 844881 Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584 Reviewed-on: https://chromium-review.googlesource.com/1188589 Reviewed-by: Fady Samuel <[email protected]> Reviewed-by: ccameron <[email protected]> Commit-Queue: Ken Buchanan <[email protected]> Cr-Commit-Position: refs/heads/master@{#586913} CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::DidStartResponse( const GURL& response_url, int request_id, const network::ResourceResponseHead& response_head, content::ResourceType resource_type) { for (auto& observer : observers_) observer.DidStartResponse(response_url, request_id, response_head, resource_type); } Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s) ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl. We need to reset external_popup_menu_ before calling it. Bug: 912211 Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc Reviewed-on: https://chromium-review.googlesource.com/c/1381325 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#618026} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const { USHORT Res; auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset), GetDataLength(), __FUNCTION__); if (ppr.ipStatus != ppresNotIP) { Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize); } else { DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__)); Res = 0; } return Res; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: exsltDateFormat (const exsltDateValPtr dt) { if (dt == NULL) return NULL; switch (dt->type) { case XS_DURATION: return exsltDateFormatDuration(&(dt->value.dur)); case XS_DATETIME: return exsltDateFormatDateTime(&(dt->value.date)); case XS_DATE: return exsltDateFormatDate(&(dt->value.date)); case XS_TIME: return exsltDateFormatTime(&(dt->value.date)); default: break; } if (dt->type & XS_GYEAR) { xmlChar buf[20], *cur = buf; FORMAT_GYEAR(dt->value.date.year, cur); if (dt->type == XS_GYEARMONTH) { *cur = '-'; cur++; FORMAT_GMONTH(dt->value.date.mon, cur); } if (dt->value.date.tz_flag || (dt->value.date.tzo != 0)) { FORMAT_TZ(dt->value.date.tzo, cur); } *cur = 0; return xmlStrdup(buf); } return NULL; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: char* _single_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( len + 1 ); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; return chr; } Commit Message: New Pre Source CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: header_put_marker (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_marker */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119 Target: 1 Example 2: Code: get_pa_etype_info(krb5_context context, krb5_kdc_configuration *config, METHOD_DATA *md, Key *ckey) { krb5_error_code ret = 0; ETYPE_INFO pa; unsigned char *buf; size_t len; pa.len = 1; pa.val = calloc(1, sizeof(pa.val[0])); if(pa.val == NULL) return ENOMEM; ret = make_etype_info_entry(context, &pa.val[0], ckey); if (ret) { free_ETYPE_INFO(&pa); return ret; } ASN1_MALLOC_ENCODE(ETYPE_INFO, buf, len, &pa, &len, ret); free_ETYPE_INFO(&pa); if(ret) return ret; ret = realloc_method_data(md); if(ret) { free(buf); return ret; } md->val[md->len - 1].padata_type = KRB5_PADATA_ETYPE_INFO; md->val[md->len - 1].padata_value.length = len; md->val[md->len - 1].padata_value.data = buf; return 0; } Commit Message: Security: Avoid NULL structure pointer member dereference This can happen in the error path when processing malformed AS requests with a NULL client name. Bug originally introduced on Fri Feb 13 09:26:01 2015 +0100 in commit: a873e21d7c06f22943a90a41dc733ae76799390d kdc: base _kdc_fast_mk_error() on krb5_mk_error_ext() Original patch by Jeffrey Altman <[email protected]> CWE ID: CWE-476 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebGL2RenderingContextBase::texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, GLintptr offset) { if (isContextLost()) return; if (!ValidateTexture3DBinding("texImage3D", target)) return; if (!bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texImage3D", "no bound PIXEL_UNPACK_BUFFER"); return; } if (!ValidateTexFunc("texImage3D", kTexImage, kSourceUnpackBuffer, target, level, internalformat, width, height, depth, border, format, type, 0, 0, 0)) return; if (!ValidateValueFitNonNegInt32("texImage3D", "offset", offset)) return; ContextGL()->TexImage3D(target, level, ConvertTexInternalFormat(internalformat, type), width, height, depth, border, format, type, reinterpret_cast<const void*>(offset)); } Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA. BUG=774174 TEST=https://github.com/KhronosGroup/WebGL/pull/2555 [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;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: I4f4e7636314502451104730501a5048a5d7b9f3f Reviewed-on: https://chromium-review.googlesource.com/808665 Commit-Queue: Zhenyao Mo <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#522003} CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) { if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) { MediaBuffer *mBuf; uint32_t numSamples = 0; uint64_t curGranulePosition = 0; while (true) { status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false); if (err != OK && err != ERROR_END_OF_STREAM) { return err; } if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) { break; } curGranulePosition = mCurrentPage.mGranulePosition; numSamples += getNumSamplesInPacket(mBuf); mBuf->release(); mBuf = NULL; } if (curGranulePosition > numSamples) { mStartGranulePosition = curGranulePosition - numSamples; } else { mStartGranulePosition = 0; } seekToOffset(0); } status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false); if (err != OK) { return err; } int32_t currentPageSamples; if ((*out)->meta_data()->findInt32(kKeyValidSamples, &currentPageSamples)) { if (mOffset == mFirstDataOffset) { currentPageSamples -= mStartGranulePosition; (*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples); } mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples; } int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition); (*out)->meta_data()->setInt64(kKeyTime, timeUs); uint32_t frames = getNumSamplesInPacket(*out); mCurGranulePosition += frames; return OK; } Commit Message: Fix memory leak in OggExtractor Test: added a temporal log and run poc Bug: 63581671 Change-Id: I436a08e54d5e831f9fbdb33c26d15397ce1fbeba (cherry picked from commit 63079e7c8e12cda4eb124fbe565213d30b9ea34c) CWE ID: CWE-772 Target: 1 Example 2: Code: GLvoid StubGLBlendFunc(GLenum sfactor, GLenum dfactor) { glBlendFunc(sfactor, dfactor); } Commit Message: Add chromium_code: 1 to surface.gyp and gl.gyp to pick up -Werror. It looks like this was dropped accidentally in http://codereview.chromium.org/6718027 (surface.gyp) and http://codereview.chromium.org/6722026 (gl.gyp) Remove now-redudant code that's implied by chromium_code: 1. Fix the warnings that have crept in since chromium_code: 1 was removed. BUG=none TEST=none Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=91598 Review URL: http://codereview.chromium.org/7227009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91813 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool CSPSource::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const { if (!schemeMatches(url)) return false; if (isSchemeOnly()) return true; bool pathsMatch = (redirectStatus == ContentSecurityPolicy::DidRedirect) || pathMatches(url); return hostMatches(url) && portMatches(url) && pathsMatch; } Commit Message: CSP: Source expressions can no longer lock sites into insecurity. CSP's matching algorithm has been updated to make clever folks like Yan slightly less able to gather data on user's behavior based on CSP reports[1]. This matches Firefox's existing behavior (they apparently changed this behavior a few months ago, via a happy accident[2]), and mitigates the CSP-variant of Sniffly[3]. On the dashboard at https://www.chromestatus.com/feature/6653486812889088. [1]: https://github.com/w3c/webappsec-csp/commit/0e81d81b64c42ca3c81c048161162b9697ff7b60 [2]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218524#c2 [3]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218778#c7 BUG=544765,558232 Review URL: https://codereview.chromium.org/1455973003 Cr-Commit-Position: refs/heads/master@{#360562} CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool FrameworkListener::onDataAvailable(SocketClient *c) { char buffer[CMD_BUF_SIZE]; int len; len = TEMP_FAILURE_RETRY(read(c->getSocket(), buffer, sizeof(buffer))); if (len < 0) { SLOGE("read() failed (%s)", strerror(errno)); return false; } else if (!len) return false; if(buffer[len-1] != '\0') SLOGW("String is not zero-terminated"); int offset = 0; int i; for (i = 0; i < len; i++) { if (buffer[i] == '\0') { /* IMPORTANT: dispatchCommand() expects a zero-terminated string */ dispatchCommand(c, buffer + offset); offset = i + 1; } } return true; } Commit Message: Fix vold vulnerability in FrameworkListener Modify FrameworkListener to ignore commands that exceed the maximum buffer length and send an error message. Bug: 29831647 Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950 Signed-off-by: Connor O'Brien <[email protected]> (cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a) (cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e) CWE ID: CWE-264 Target: 1 Example 2: Code: static struct avl_table *create_t1_glyph_tree(char **glyph_names) { int i; void **aa; static struct avl_table *gl_tree; gl_tree = avl_create(comp_t1_glyphs, NULL, &avl_xallocator); assert(gl_tree != NULL); for (i = 0; i < 256; i++) { if (glyph_names[i] != notdef && (char **) avl_find(gl_tree, &glyph_names[i]) == NULL) { /* no strdup here, just point to the glyph_names array members */ aa = avl_probe(gl_tree, &glyph_names[i]); assert(aa != NULL); } } return gl_tree; } Commit Message: writet1 protection against buffer overflow git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751 CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct fb_info *file_fb_info(struct file *file) { struct inode *inode = file_inode(file); int fbidx = iminor(inode); struct fb_info *info = registered_fb[fbidx]; if (info != file->private_data) info = NULL; return info; } Commit Message: vm: convert fb_mmap to vm_iomap_memory() helper This is my example conversion of a few existing mmap users. The fb_mmap() case is a good example because it is a bit more complicated than some: fb_mmap() mmaps one of two different memory areas depending on the page offset of the mmap (but happily there is never any mixing of the two, so the helper function still works). Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EnumTraits<media::mojom::VideoCaptureError, media::VideoCaptureError>::ToMojom( media::VideoCaptureError input) { switch (input) { case media::VideoCaptureError::kNone: return media::mojom::VideoCaptureError::kNone; case media::VideoCaptureError:: kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested: return media::mojom::VideoCaptureError:: kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested; case media::VideoCaptureError::kVideoCaptureControllerIsAlreadyInErrorState: return media::mojom::VideoCaptureError:: kVideoCaptureControllerIsAlreadyInErrorState; case media::VideoCaptureError::kVideoCaptureManagerDeviceConnectionLost: return media::mojom::VideoCaptureError:: kVideoCaptureManagerDeviceConnectionLost; case media::VideoCaptureError:: kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError: return media::mojom::VideoCaptureError:: kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError; case media::VideoCaptureError:: kFrameSinkVideoCaptureDeviceEncounteredFatalError: return media::mojom::VideoCaptureError:: kFrameSinkVideoCaptureDeviceEncounteredFatalError; case media::VideoCaptureError::kV4L2FailedToOpenV4L2DeviceDriverFile: return media::mojom::VideoCaptureError:: kV4L2FailedToOpenV4L2DeviceDriverFile; case media::VideoCaptureError::kV4L2ThisIsNotAV4L2VideoCaptureDevice: return media::mojom::VideoCaptureError:: kV4L2ThisIsNotAV4L2VideoCaptureDevice; case media::VideoCaptureError::kV4L2FailedToFindASupportedCameraFormat: return media::mojom::VideoCaptureError:: kV4L2FailedToFindASupportedCameraFormat; case media::VideoCaptureError::kV4L2FailedToSetVideoCaptureFormat: return media::mojom::VideoCaptureError:: kV4L2FailedToSetVideoCaptureFormat; case media::VideoCaptureError::kV4L2UnsupportedPixelFormat: return media::mojom::VideoCaptureError::kV4L2UnsupportedPixelFormat; case media::VideoCaptureError::kV4L2FailedToSetCameraFramerate: return media::mojom::VideoCaptureError::kV4L2FailedToSetCameraFramerate; case media::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers: return media::mojom::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers; case media::VideoCaptureError::kV4L2AllocateBufferFailed: return media::mojom::VideoCaptureError::kV4L2AllocateBufferFailed; case media::VideoCaptureError::kV4L2VidiocStreamonFailed: return media::mojom::VideoCaptureError::kV4L2VidiocStreamonFailed; case media::VideoCaptureError::kV4L2VidiocStreamoffFailed: return media::mojom::VideoCaptureError::kV4L2VidiocStreamoffFailed; case media::VideoCaptureError::kV4L2FailedToVidiocReqbufsWithCount0: return media::mojom::VideoCaptureError:: kV4L2FailedToVidiocReqbufsWithCount0; case media::VideoCaptureError::kV4L2PollFailed: return media::mojom::VideoCaptureError::kV4L2PollFailed; case media::VideoCaptureError:: kV4L2MultipleContinuousTimeoutsWhileReadPolling: return media::mojom::VideoCaptureError:: kV4L2MultipleContinuousTimeoutsWhileReadPolling; case media::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer: return media::mojom::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer; case media::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer: return media::mojom::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer; case media::VideoCaptureError:: kSingleClientVideoCaptureHostLostConnectionToDevice: return media::mojom::VideoCaptureError:: kSingleClientVideoCaptureHostLostConnectionToDevice; case media::VideoCaptureError::kSingleClientVideoCaptureDeviceLaunchAborted: return media::mojom::VideoCaptureError:: kSingleClientVideoCaptureDeviceLaunchAborted; case media::VideoCaptureError:: kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed: return media::mojom::VideoCaptureError:: kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed; case media::VideoCaptureError::kFileVideoCaptureDeviceCouldNotOpenVideoFile: return media::mojom::VideoCaptureError:: kFileVideoCaptureDeviceCouldNotOpenVideoFile; case media::VideoCaptureError:: kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate: return media::mojom::VideoCaptureError:: kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate; case media::VideoCaptureError:: kErrorFakeDeviceIntentionallyEmittingErrorEvent: return media::mojom::VideoCaptureError:: kErrorFakeDeviceIntentionallyEmittingErrorEvent; case media::VideoCaptureError::kDeviceClientTooManyFramesDroppedY16: return media::mojom::VideoCaptureError:: kDeviceClientTooManyFramesDroppedY16; case media::VideoCaptureError:: kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType: return media::mojom::VideoCaptureError:: kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType; case media::VideoCaptureError:: kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound: return media::mojom::VideoCaptureError:: kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound; case media::VideoCaptureError:: kInProcessDeviceLauncherFailedToCreateDeviceInstance: return media::mojom::VideoCaptureError:: kInProcessDeviceLauncherFailedToCreateDeviceInstance; case media::VideoCaptureError:: kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart: return media::mojom::VideoCaptureError:: kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart; case media::VideoCaptureError:: kServiceDeviceLauncherServiceRespondedWithDeviceNotFound: return media::mojom::VideoCaptureError:: kServiceDeviceLauncherServiceRespondedWithDeviceNotFound; case media::VideoCaptureError:: kServiceDeviceLauncherConnectionLostWhileWaitingForCallback: return media::mojom::VideoCaptureError:: kServiceDeviceLauncherConnectionLostWhileWaitingForCallback; case media::VideoCaptureError::kIntentionalErrorRaisedByUnitTest: return media::mojom::VideoCaptureError::kIntentionalErrorRaisedByUnitTest; case media::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread: return media::mojom::VideoCaptureError:: kCrosHalV3FailedToStartDeviceThread; case media::VideoCaptureError::kCrosHalV3DeviceDelegateMojoConnectionError: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateMojoConnectionError; case media::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToGetCameraInfo: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToGetCameraInfo; case media::VideoCaptureError:: kCrosHalV3DeviceDelegateMissingSensorOrientationInfo: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateMissingSensorOrientationInfo; case media::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToOpenCameraDevice: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToOpenCameraDevice; case media::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice; case media::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToConfigureStreams: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToConfigureStreams; case media::VideoCaptureError:: kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured; case media::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings; case media::VideoCaptureError:: kCrosHalV3BufferManagerHalRequestedTooManyBuffers: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerHalRequestedTooManyBuffers; case media::VideoCaptureError:: kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer; case media::VideoCaptureError:: kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer; case media::VideoCaptureError:: kCrosHalV3BufferManagerUnsupportedVideoPixelFormat: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerUnsupportedVideoPixelFormat; case media::VideoCaptureError::kCrosHalV3BufferManagerFailedToDupFd: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerFailedToDupFd; case media::VideoCaptureError:: kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle; case media::VideoCaptureError:: kCrosHalV3BufferManagerFailedToRegisterBuffer: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerFailedToRegisterBuffer; case media::VideoCaptureError:: kCrosHalV3BufferManagerProcessCaptureRequestFailed: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerProcessCaptureRequestFailed; case media::VideoCaptureError:: kCrosHalV3BufferManagerInvalidPendingResultId: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerInvalidPendingResultId; case media::VideoCaptureError:: kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata; case media::VideoCaptureError:: kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived; case media::VideoCaptureError:: kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived; case media::VideoCaptureError:: kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame; case media::VideoCaptureError:: kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg; case media::VideoCaptureError:: kCrosHalV3BufferManagerReceivedInvalidShutterTime: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerReceivedInvalidShutterTime; case media::VideoCaptureError::kCrosHalV3BufferManagerFatalDeviceError: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerFatalDeviceError; case media::VideoCaptureError:: kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder; case media::VideoCaptureError:: kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd; case media::VideoCaptureError:: kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut; case media::VideoCaptureError::kCrosHalV3BufferManagerInvalidJpegBlob: return media::mojom::VideoCaptureError:: kCrosHalV3BufferManagerInvalidJpegBlob; case media::VideoCaptureError::kAndroidFailedToAllocate: return media::mojom::VideoCaptureError::kAndroidFailedToAllocate; case media::VideoCaptureError::kAndroidFailedToStartCapture: return media::mojom::VideoCaptureError::kAndroidFailedToStartCapture; case media::VideoCaptureError::kAndroidFailedToStopCapture: return media::mojom::VideoCaptureError::kAndroidFailedToStopCapture; case media::VideoCaptureError::kAndroidApi1CameraErrorCallbackReceived: return media::mojom::VideoCaptureError:: kAndroidApi1CameraErrorCallbackReceived; case media::VideoCaptureError::kAndroidApi2CameraDeviceErrorReceived: return media::mojom::VideoCaptureError:: kAndroidApi2CameraDeviceErrorReceived; case media::VideoCaptureError::kAndroidApi2CaptureSessionConfigureFailed: return media::mojom::VideoCaptureError:: kAndroidApi2CaptureSessionConfigureFailed; case media::VideoCaptureError::kAndroidApi2ImageReaderUnexpectedImageFormat: return media::mojom::VideoCaptureError:: kAndroidApi2ImageReaderUnexpectedImageFormat; case media::VideoCaptureError:: kAndroidApi2ImageReaderSizeDidNotMatchImageSize: return media::mojom::VideoCaptureError:: kAndroidApi2ImageReaderSizeDidNotMatchImageSize; case media::VideoCaptureError::kAndroidApi2ErrorRestartingPreview: return media::mojom::VideoCaptureError:: kAndroidApi2ErrorRestartingPreview; case media::VideoCaptureError::kAndroidScreenCaptureUnsupportedFormat: return media::mojom::VideoCaptureError:: kAndroidScreenCaptureUnsupportedFormat; case media::VideoCaptureError:: kAndroidScreenCaptureFailedToStartCaptureMachine: return media::mojom::VideoCaptureError:: kAndroidScreenCaptureFailedToStartCaptureMachine; case media::VideoCaptureError:: kAndroidScreenCaptureTheUserDeniedScreenCapture: return media::mojom::VideoCaptureError:: kAndroidScreenCaptureTheUserDeniedScreenCapture; case media::VideoCaptureError:: kAndroidScreenCaptureFailedToStartScreenCapture: return media::mojom::VideoCaptureError:: kAndroidScreenCaptureFailedToStartScreenCapture; case media::VideoCaptureError::kWinDirectShowCantGetCaptureFormatSettings: return media::mojom::VideoCaptureError:: kWinDirectShowCantGetCaptureFormatSettings; case media::VideoCaptureError:: kWinDirectShowFailedToGetNumberOfCapabilities: return media::mojom::VideoCaptureError:: kWinDirectShowFailedToGetNumberOfCapabilities; case media::VideoCaptureError:: kWinDirectShowFailedToGetCaptureDeviceCapabilities: return media::mojom::VideoCaptureError:: kWinDirectShowFailedToGetCaptureDeviceCapabilities; case media::VideoCaptureError:: kWinDirectShowFailedToSetCaptureDeviceOutputFormat: return media::mojom::VideoCaptureError:: kWinDirectShowFailedToSetCaptureDeviceOutputFormat; case media::VideoCaptureError::kWinDirectShowFailedToConnectTheCaptureGraph: return media::mojom::VideoCaptureError:: kWinDirectShowFailedToConnectTheCaptureGraph; case media::VideoCaptureError::kWinDirectShowFailedToPauseTheCaptureDevice: return media::mojom::VideoCaptureError:: kWinDirectShowFailedToPauseTheCaptureDevice; case media::VideoCaptureError::kWinDirectShowFailedToStartTheCaptureDevice: return media::mojom::VideoCaptureError:: kWinDirectShowFailedToStartTheCaptureDevice; case media::VideoCaptureError::kWinDirectShowFailedToStopTheCaptureGraph: return media::mojom::VideoCaptureError:: kWinDirectShowFailedToStopTheCaptureGraph; case media::VideoCaptureError::kWinMediaFoundationEngineIsNull: return media::mojom::VideoCaptureError::kWinMediaFoundationEngineIsNull; case media::VideoCaptureError::kWinMediaFoundationEngineGetSourceFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationEngineGetSourceFailed; case media::VideoCaptureError:: kWinMediaFoundationFillPhotoCapabilitiesFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationFillPhotoCapabilitiesFailed; case media::VideoCaptureError:: kWinMediaFoundationFillVideoCapabilitiesFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationFillVideoCapabilitiesFailed; case media::VideoCaptureError::kWinMediaFoundationNoVideoCapabilityFound: return media::mojom::VideoCaptureError:: kWinMediaFoundationNoVideoCapabilityFound; case media::VideoCaptureError:: kWinMediaFoundationGetAvailableDeviceMediaTypeFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationGetAvailableDeviceMediaTypeFailed; case media::VideoCaptureError:: kWinMediaFoundationSetCurrentDeviceMediaTypeFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationSetCurrentDeviceMediaTypeFailed; case media::VideoCaptureError::kWinMediaFoundationEngineGetSinkFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationEngineGetSinkFailed; case media::VideoCaptureError:: kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed; case media::VideoCaptureError:: kWinMediaFoundationSinkRemoveAllStreamsFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationSinkRemoveAllStreamsFailed; case media::VideoCaptureError:: kWinMediaFoundationCreateSinkVideoMediaTypeFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationCreateSinkVideoMediaTypeFailed; case media::VideoCaptureError:: kWinMediaFoundationConvertToVideoSinkMediaTypeFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationConvertToVideoSinkMediaTypeFailed; case media::VideoCaptureError::kWinMediaFoundationSinkAddStreamFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationSinkAddStreamFailed; case media::VideoCaptureError:: kWinMediaFoundationSinkSetSampleCallbackFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationSinkSetSampleCallbackFailed; case media::VideoCaptureError::kWinMediaFoundationEngineStartPreviewFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationEngineStartPreviewFailed; case media::VideoCaptureError::kWinMediaFoundationGetMediaEventStatusFailed: return media::mojom::VideoCaptureError:: kWinMediaFoundationGetMediaEventStatusFailed; case media::VideoCaptureError::kMacSetCaptureDeviceFailed: return media::mojom::VideoCaptureError::kMacSetCaptureDeviceFailed; case media::VideoCaptureError::kMacCouldNotStartCaptureDevice: return media::mojom::VideoCaptureError::kMacCouldNotStartCaptureDevice; case media::VideoCaptureError::kMacReceivedFrameWithUnexpectedResolution: return media::mojom::VideoCaptureError:: kMacReceivedFrameWithUnexpectedResolution; case media::VideoCaptureError::kMacUpdateCaptureResolutionFailed: return media::mojom::VideoCaptureError::kMacUpdateCaptureResolutionFailed; case media::VideoCaptureError::kMacDeckLinkDeviceIdNotFoundInTheSystem: return media::mojom::VideoCaptureError:: kMacDeckLinkDeviceIdNotFoundInTheSystem; case media::VideoCaptureError::kMacDeckLinkErrorQueryingInputInterface: return media::mojom::VideoCaptureError:: kMacDeckLinkErrorQueryingInputInterface; case media::VideoCaptureError::kMacDeckLinkErrorCreatingDisplayModeIterator: return media::mojom::VideoCaptureError:: kMacDeckLinkErrorCreatingDisplayModeIterator; case media::VideoCaptureError::kMacDeckLinkCouldNotFindADisplayMode: return media::mojom::VideoCaptureError:: kMacDeckLinkCouldNotFindADisplayMode; case media::VideoCaptureError:: kMacDeckLinkCouldNotSelectTheVideoFormatWeLike: return media::mojom::VideoCaptureError:: kMacDeckLinkCouldNotSelectTheVideoFormatWeLike; case media::VideoCaptureError::kMacDeckLinkCouldNotStartCapturing: return media::mojom::VideoCaptureError:: kMacDeckLinkCouldNotStartCapturing; case media::VideoCaptureError::kMacDeckLinkUnsupportedPixelFormat: return media::mojom::VideoCaptureError:: kMacDeckLinkUnsupportedPixelFormat; case media::VideoCaptureError:: kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification: return media::mojom::VideoCaptureError:: kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification; case media::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera: return media::mojom::VideoCaptureError:: kAndroidApi2ErrorConfiguringCamera; case media::VideoCaptureError::kCrosHalV3DeviceDelegateFailedToFlush: return media::mojom::VideoCaptureError:: kCrosHalV3DeviceDelegateFailedToFlush; } NOTREACHED(); return media::mojom::VideoCaptureError::kNone; } Commit Message: Revert "Enable camera blob stream when needed" This reverts commit 10f4b93635e12f9fa0cba1641a10938ca38ed448. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 601492 as the culprit for failures in the build cycles as shown on: https://findit-for-me.appspot.com/waterfall/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyRAsSDVdmU3VzcGVjdGVkQ0wiMWNocm9taXVtLzEwZjRiOTM2MzVlMTJmOWZhMGNiYTE2NDFhMTA5MzhjYTM4ZWQ0NDgM Sample Failed Build: https://ci.chromium.org/buildbot/chromium.memory/Linux%20ChromiumOS%20MSan%20Tests/9190 Sample Failed Step: capture_unittests Original change's description: > Enable camera blob stream when needed > > Since blob stream needs higher resolution, it causes higher cpu loading > to require higher resolution and resize to smaller resolution. > In hangout app, we don't need blob stream. Enabling blob stream when > needed can save a lot of cpu usage. > > BUG=b:114676133 > TEST=manually test in apprtc and CCA. make sure picture taking still > works in CCA. > > Change-Id: I9144461bc76627903d0b3b359ce9cf962ff3628c > Reviewed-on: https://chromium-review.googlesource.com/c/1261242 > Commit-Queue: Heng-ruey Hsu <[email protected]> > Reviewed-by: Ricky Liang <[email protected]> > Reviewed-by: Xiaohan Wang <[email protected]> > Reviewed-by: Robert Sesek <[email protected]> > Cr-Commit-Position: refs/heads/master@{#601492} No-Presubmit: true No-Tree-Checks: true No-Try: true BUG=b:114676133 Change-Id: If173ffe9259f7eca849b184806bd56e2a9fbaac4 Reviewed-on: https://chromium-review.googlesource.com/c/1292256 Cr-Commit-Position: refs/heads/master@{#601538} CWE ID: CWE-19 Target: 1 Example 2: Code: PerformanceEntryVector Performance::getEntriesByName(const String& name, const String& entry_type) { PerformanceEntryVector entries; PerformanceEntry::EntryType type = PerformanceEntry::ToEntryTypeEnum(entry_type); if (!entry_type.IsNull() && type == PerformanceEntry::kInvalid) return entries; if (entry_type.IsNull() || type == PerformanceEntry::kResource) { for (const auto& resource : resource_timing_buffer_) { if (resource->name() == name) entries.push_back(resource); } } if (entry_type.IsNull() || type == PerformanceEntry::kNavigation) { if (!navigation_timing_) navigation_timing_ = CreateNavigationTimingInstance(); if (navigation_timing_ && navigation_timing_->name() == name) entries.push_back(navigation_timing_); } if (entry_type.IsNull() || type == PerformanceEntry::kComposite || type == PerformanceEntry::kRender) { for (const auto& frame : frame_timing_buffer_) { if (frame->name() == name && (entry_type.IsNull() || entry_type == frame->entryType())) entries.push_back(frame); } } if (user_timing_) { if (entry_type.IsNull() || type == PerformanceEntry::kMark) entries.AppendVector(user_timing_->GetMarks(name)); if (entry_type.IsNull() || type == PerformanceEntry::kMeasure) entries.AppendVector(user_timing_->GetMeasures(name)); } if (entry_type.IsNull() || type == PerformanceEntry::kPaint) { if (first_paint_timing_ && first_paint_timing_->name() == name) entries.push_back(first_paint_timing_); if (first_contentful_paint_timing_ && first_contentful_paint_timing_->name() == name) entries.push_back(first_contentful_paint_timing_); } std::sort(entries.begin(), entries.end(), PerformanceEntry::StartTimeCompareLessThan); return entries; } Commit Message: Fix timing allow check algorithm for service workers This CL uses the OriginalURLViaServiceWorker() in the timing allow check algorithm if the response WasFetchedViaServiceWorker(). This way, if a service worker changes a same origin request to become cross origin, then the timing allow check algorithm will still fail. resource-timing-worker.js is changed so it avoids an empty Response, which is an odd case in terms of same origin checks. Bug: 837275 Change-Id: I7e497a6fcc2ee14244121b915ca5f5cceded417a Reviewed-on: https://chromium-review.googlesource.com/1038229 Commit-Queue: Nicolás Peña Moreno <[email protected]> Reviewed-by: Yoav Weiss <[email protected]> Reviewed-by: Timothy Dresser <[email protected]> Cr-Commit-Position: refs/heads/master@{#555476} CWE ID: CWE-200 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2, int fragmented) { char *cp; const struct icmp *dp; const struct icmp_ext_t *ext_dp; const struct ip *ip; const char *str, *fmt; const struct ip *oip; const struct udphdr *ouh; const uint8_t *obj_tptr; uint32_t raw_label; const u_char *snapend_save; const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header; u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype; char buf[MAXHOSTNAMELEN + 100]; struct cksum_vec vec[1]; dp = (const struct icmp *)bp; ext_dp = (const struct icmp_ext_t *)bp; ip = (const struct ip *)bp2; str = buf; ND_TCHECK(dp->icmp_code); switch (dp->icmp_type) { case ICMP_ECHO: case ICMP_ECHOREPLY: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u", dp->icmp_type == ICMP_ECHO ? "request" : "reply", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_UNREACH: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_UNREACH_PROTOCOL: ND_TCHECK(dp->icmp_ip.ip_p); (void)snprintf(buf, sizeof(buf), "%s protocol %d unreachable", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), dp->icmp_ip.ip_p); break; case ICMP_UNREACH_PORT: ND_TCHECK(dp->icmp_ip.ip_p); oip = &dp->icmp_ip; hlen = IP_HL(oip) * 4; ouh = (const struct udphdr *)(((const u_char *)oip) + hlen); ND_TCHECK(ouh->uh_dport); dport = EXTRACT_16BITS(&ouh->uh_dport); switch (oip->ip_p) { case IPPROTO_TCP: (void)snprintf(buf, sizeof(buf), "%s tcp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), tcpport_string(ndo, dport)); break; case IPPROTO_UDP: (void)snprintf(buf, sizeof(buf), "%s udp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), udpport_string(ndo, dport)); break; default: (void)snprintf(buf, sizeof(buf), "%s protocol %d port %d unreachable", ipaddr_string(ndo, &oip->ip_dst), oip->ip_p, dport); break; } break; case ICMP_UNREACH_NEEDFRAG: { register const struct mtu_discovery *mp; mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void; mtu = EXTRACT_16BITS(&mp->nexthopmtu); if (mtu) { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag (mtu %d)", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu); } else { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag", ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); } } break; default: fmt = tok2str(unreach2str, "#%d %%s unreachable", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); break; } break; case ICMP_REDIRECT: ND_TCHECK(dp->icmp_ip.ip_dst); fmt = tok2str(type2str, "redirect-#%d %%s to net %%s", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst), ipaddr_string(ndo, &dp->icmp_gwaddr)); break; case ICMP_ROUTERADVERT: { register const struct ih_rdiscovery *ihp; register const struct id_rdiscovery *idp; u_int lifetime, num, size; (void)snprintf(buf, sizeof(buf), "router advertisement"); cp = buf + strlen(buf); ihp = (const struct ih_rdiscovery *)&dp->icmp_void; ND_TCHECK(*ihp); (void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf)); cp = buf + strlen(buf); lifetime = EXTRACT_16BITS(&ihp->ird_lifetime); if (lifetime < 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u", lifetime); } else if (lifetime < 60 * 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u", lifetime / 60, lifetime % 60); } else { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u:%02u", lifetime / 3600, (lifetime % 3600) / 60, lifetime % 60); } cp = buf + strlen(buf); num = ihp->ird_addrnum; (void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num); cp = buf + strlen(buf); size = ihp->ird_addrsiz; if (size != 2) { (void)snprintf(cp, sizeof(buf) - (cp - buf), " [size %d]", size); break; } idp = (const struct id_rdiscovery *)&dp->icmp_data; while (num-- > 0) { ND_TCHECK(*idp); (void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}", ipaddr_string(ndo, &idp->ird_addr), EXTRACT_32BITS(&idp->ird_pref)); cp = buf + strlen(buf); ++idp; } } break; case ICMP_TIMXCEED: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_TIMXCEED_INTRANS: str = "time exceeded in-transit"; break; case ICMP_TIMXCEED_REASS: str = "ip reassembly time exceeded"; break; default: (void)snprintf(buf, sizeof(buf), "time exceeded-#%d", dp->icmp_code); break; } break; case ICMP_PARAMPROB: if (dp->icmp_code) (void)snprintf(buf, sizeof(buf), "parameter problem - code %d", dp->icmp_code); else { ND_TCHECK(dp->icmp_pptr); (void)snprintf(buf, sizeof(buf), "parameter problem - octet %d", dp->icmp_pptr); } break; case ICMP_MASKREPLY: ND_TCHECK(dp->icmp_mask); (void)snprintf(buf, sizeof(buf), "address mask is 0x%08x", EXTRACT_32BITS(&dp->icmp_mask)); break; case ICMP_TSTAMP: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "time stamp query id %u seq %u", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_TSTAMPREPLY: ND_TCHECK(dp->icmp_ttime); (void)snprintf(buf, sizeof(buf), "time stamp reply id %u seq %u: org %s", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq), icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime))); break; default: str = tok2str(icmp2str, "type-#%d", dp->icmp_type); break; } ND_PRINT((ndo, "ICMP %s, length %u", str, plen)); if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */ uint16_t sum, icmp_sum; if (ND_TTEST2(*bp, plen)) { vec[0].ptr = (const uint8_t *)(const void *)dp; vec[0].len = plen; sum = in_cksum(vec, 1); if (sum != 0) { icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum); ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)", icmp_sum, in_cksum_shouldbe(icmp_sum, sum))); } } } /* * print the remnants of the IP packet. * save the snaplength as this may get overidden in the IP printer. */ if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) { bp += 8; ND_PRINT((ndo, "\n\t")); ip = (const struct ip *)bp; snapend_save = ndo->ndo_snapend; ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len)); ndo->ndo_snapend = snapend_save; } /* * Attempt to decode the MPLS extensions only for some ICMP types. */ if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) { ND_TCHECK(*ext_dp); /* * Check first if the mpls extension header shows a non-zero length. * If the length field is not set then silently verify the checksum * to check if an extension header is present. This is expedient, * however not all implementations set the length field proper. */ if (!ext_dp->icmp_length) { vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = plen - ICMP_EXTD_MINLEN; if (in_cksum(vec, 1)) { return; } } ND_PRINT((ndo, "\n\tMPLS extension v%u", ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)))); /* * Sanity checking of the header. */ if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) != ICMP_MPLS_EXT_VERSION) { ND_PRINT((ndo, " packet not supported")); return; } hlen = plen - ICMP_EXTD_MINLEN; vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = hlen; ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u", EXTRACT_16BITS(ext_dp->icmp_ext_checksum), in_cksum(vec, 1) ? "in" : "", hlen)); hlen -= 4; /* subtract common header size */ obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data; while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) { icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr; ND_TCHECK(*icmp_mpls_ext_object_header); obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length); obj_class_num = icmp_mpls_ext_object_header->class_num; obj_ctype = icmp_mpls_ext_object_header->ctype; obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t); ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u", tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num), obj_class_num, obj_ctype, obj_tlen)); hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */ /* infinite loop protection */ if ((obj_class_num == 0) || (obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) { return; } obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t); switch (obj_class_num) { case 1: switch(obj_ctype) { case 1: ND_TCHECK2(*obj_tptr, 4); raw_label = EXTRACT_32BITS(obj_tptr); ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label))); if (MPLS_STACK(raw_label)) ND_PRINT((ndo, ", [S]")); ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label))); break; default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case 2: default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); break; } if (hlen < obj_tlen) break; hlen -= obj_tlen; obj_tptr += obj_tlen; } } return; trunc: ND_PRINT((ndo, "[|icmp]")); } Commit Message: CVE-2017-12895/ICMP: Check the availability of data before checksumming it. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() { return GetBooleanParam( switches::kEnableContextualSearchNowOnTapBarIntegration, &is_now_on_tap_bar_integration_enabled_cached_, &is_now_on_tap_bar_integration_enabled_); } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID: Target: 1 Example 2: Code: hncp_print(netdissect_options *ndo, const u_char *cp, u_int length) { ND_PRINT((ndo, "hncp (%d)", length)); hncp_print_rec(ndo, cp, length, 1); } Commit Message: CVE-2017-13044/HNCP: add DHCPv4-Data bounds checks dhcpv4_print() in print-hncp.c had the same bug as dhcpv6_print(), apply a fix along the same lines. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ext4_ext_check_inode(struct inode *inode) { return ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode)); } Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio We assumed that at the time we call ext4_convert_unwritten_extents_endio() extent in question is fully inside [map.m_lblk, map->m_len] because it was already split during submission. But this may not be true due to a race between writeback vs fallocate. If extent in question is larger than requested we will split it again. Special precautions should being done if zeroout required because [map.m_lblk, map->m_len] already contains valid data. Signed-off-by: Dmitry Monakhov <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [email protected] CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void jslTokenAsString(int token, char *str, size_t len) { if (token>32 && token<128) { assert(len>=4); str[0] = '\''; str[1] = (char)token; str[2] = '\''; str[3] = 0; return; } switch (token) { case LEX_EOF : strncpy(str, "EOF", len); return; case LEX_ID : strncpy(str, "ID", len); return; case LEX_INT : strncpy(str, "INT", len); return; case LEX_FLOAT : strncpy(str, "FLOAT", len); return; case LEX_STR : strncpy(str, "STRING", len); return; case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return; case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return; case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return; case LEX_REGEX : strncpy(str, "REGEX", len); return; case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return; case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return; } if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) { const char tokenNames[] = /* LEX_EQUAL : */ "==\0" /* LEX_TYPEEQUAL : */ "===\0" /* LEX_NEQUAL : */ "!=\0" /* LEX_NTYPEEQUAL : */ "!==\0" /* LEX_LEQUAL : */ "<=\0" /* LEX_LSHIFT : */ "<<\0" /* LEX_LSHIFTEQUAL : */ "<<=\0" /* LEX_GEQUAL : */ ">=\0" /* LEX_RSHIFT : */ ">>\0" /* LEX_RSHIFTUNSIGNED */ ">>>\0" /* LEX_RSHIFTEQUAL : */ ">>=\0" /* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0" /* LEX_PLUSEQUAL : */ "+=\0" /* LEX_MINUSEQUAL : */ "-=\0" /* LEX_PLUSPLUS : */ "++\0" /* LEX_MINUSMINUS */ "--\0" /* LEX_MULEQUAL : */ "*=\0" /* LEX_DIVEQUAL : */ "/=\0" /* LEX_MODEQUAL : */ "%=\0" /* LEX_ANDEQUAL : */ "&=\0" /* LEX_ANDAND : */ "&&\0" /* LEX_OREQUAL : */ "|=\0" /* LEX_OROR : */ "||\0" /* LEX_XOREQUAL : */ "^=\0" /* LEX_ARROW_FUNCTION */ "=>\0" /*LEX_R_IF : */ "if\0" /*LEX_R_ELSE : */ "else\0" /*LEX_R_DO : */ "do\0" /*LEX_R_WHILE : */ "while\0" /*LEX_R_FOR : */ "for\0" /*LEX_R_BREAK : */ "return\0" /*LEX_R_CONTINUE */ "continue\0" /*LEX_R_FUNCTION */ "function\0" /*LEX_R_RETURN */ "return\0" /*LEX_R_VAR : */ "var\0" /*LEX_R_LET : */ "let\0" /*LEX_R_CONST : */ "const\0" /*LEX_R_THIS : */ "this\0" /*LEX_R_THROW : */ "throw\0" /*LEX_R_TRY : */ "try\0" /*LEX_R_CATCH : */ "catch\0" /*LEX_R_FINALLY : */ "finally\0" /*LEX_R_TRUE : */ "true\0" /*LEX_R_FALSE : */ "false\0" /*LEX_R_NULL : */ "null\0" /*LEX_R_UNDEFINED */ "undefined\0" /*LEX_R_NEW : */ "new\0" /*LEX_R_IN : */ "in\0" /*LEX_R_INSTANCEOF */ "instanceof\0" /*LEX_R_SWITCH */ "switch\0" /*LEX_R_CASE */ "case\0" /*LEX_R_DEFAULT */ "default\0" /*LEX_R_DELETE */ "delete\0" /*LEX_R_TYPEOF : */ "typeof\0" /*LEX_R_VOID : */ "void\0" /*LEX_R_DEBUGGER : */ "debugger\0" /*LEX_R_CLASS : */ "class\0" /*LEX_R_EXTENDS : */ "extends\0" /*LEX_R_SUPER : */ "super\0" /*LEX_R_STATIC : */ "static\0" ; unsigned int p = 0; int n = token-_LEX_OPERATOR_START; while (n>0 && p<sizeof(tokenNames)) { while (tokenNames[p] && p<sizeof(tokenNames)) p++; p++; // skip the zero n--; // next token } assert(n==0); strncpy(str, &tokenNames[p], len); return; } assert(len>=10); espruino_snprintf(str, len, "?[%d]", token); } Commit Message: remove strncpy usage as it's effectively useless, replace with an assertion since fn is only used internally (fix #1426) CWE ID: CWE-787 Target: 1 Example 2: Code: void AwContents::ClearCache( JNIEnv* env, jobject obj, jboolean include_disk_files) { DCHECK_CURRENTLY_ON(BrowserThread::UI); render_view_host_ext_->ClearCache(); if (include_disk_files) { RemoveHttpDiskCache(web_contents_->GetBrowserContext(), web_contents_->GetRoutingID()); } } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int btrfs_dentry_delete(const struct dentry *dentry) { struct btrfs_root *root; struct inode *inode = dentry->d_inode; if (!inode && !IS_ROOT(dentry)) inode = dentry->d_parent->d_inode; if (inode) { root = BTRFS_I(inode)->root; if (btrfs_root_refs(&root->root_item) == 0) return 1; if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return 1; } return 0; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 0; } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190 Target: 1 Example 2: Code: NO_INLINE JsVar *jspNewPrototype(const char *instanceOf) { JsVar *objFuncName = jsvFindChildFromString(execInfo.root, instanceOf, true); if (!objFuncName) // out of memory return 0; JsVar *objFunc = jsvSkipName(objFuncName); if (!objFunc) { objFunc = jspNewBuiltin(instanceOf); if (!objFunc) { // out of memory jsvUnLock(objFuncName); return 0; } jsvSetValueOfName(objFuncName, objFunc); } JsVar *prototypeName = jsvFindChildFromString(objFunc, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(objFunc, prototypeName); // make sure it's an object jsvUnLock2(objFunc, objFuncName); return prototypeName; } Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437) CWE ID: CWE-125 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: irc_server_xfer_send_ready_cb (void *data, const char *signal, const char *type_data, void *signal_data) { struct t_infolist *infolist; struct t_irc_server *ptr_server; const char *plugin_name, *plugin_id, *type, *filename; int spaces_in_name; /* make C compiler happy */ (void) data; (void) signal; (void) type_data; infolist = (struct t_infolist *)signal_data; if (weechat_infolist_next (infolist)) { plugin_name = weechat_infolist_string (infolist, "plugin_name"); plugin_id = weechat_infolist_string (infolist, "plugin_id"); if (plugin_name && (strcmp (plugin_name, IRC_PLUGIN_NAME) == 0) && plugin_id) { ptr_server = irc_server_search (plugin_id); if (ptr_server) { type = weechat_infolist_string (infolist, "type"); if (type) { if (strcmp (type, "file_send") == 0) { filename = weechat_infolist_string (infolist, "filename"); spaces_in_name = (strchr (filename, ' ') != NULL); irc_server_sendf (ptr_server, IRC_SERVER_SEND_OUTQ_PRIO_HIGH, NULL, "PRIVMSG %s :\01DCC SEND %s%s%s " "%s %d %s\01", weechat_infolist_string (infolist, "remote_nick"), (spaces_in_name) ? "\"" : "", filename, (spaces_in_name) ? "\"" : "", weechat_infolist_string (infolist, "address"), weechat_infolist_integer (infolist, "port"), weechat_infolist_string (infolist, "size")); } else if (strcmp (type, "chat_send") == 0) { irc_server_sendf (ptr_server, IRC_SERVER_SEND_OUTQ_PRIO_HIGH, NULL, "PRIVMSG %s :\01DCC CHAT chat %s %d\01", weechat_infolist_string (infolist, "remote_nick"), weechat_infolist_string (infolist, "address"), weechat_infolist_integer (infolist, "port")); } } } } } weechat_infolist_reset_item_cursor (infolist); return WEECHAT_RC_OK; } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int tls1_process_ticket(SSL *s, unsigned char *session_id, int len, const unsigned char *limit, SSL_SESSION **ret) { /* Point after session ID in client hello */ const unsigned char *p = session_id + len; unsigned short i; *ret = NULL; s->tlsext_ticket_expected = 0; /* * If tickets disabled behave as if no ticket present to permit stateful * resumption. */ if (SSL_get_options(s) & SSL_OP_NO_TICKET) return 0; if ((s->version <= SSL3_VERSION) || !limit) return 0; if (p >= limit) return -1; /* Skip past DTLS cookie */ if (SSL_IS_DTLS(s)) { i = *(p++); p += i; if (p >= limit) return -1; } /* Skip past cipher list */ n2s(p, i); p += i; if (p >= limit) return -1; /* Skip past compression algorithm list */ i = *(p++); p += i; if (p > limit) return -1; /* Now at start of extensions */ if ((p + 2) >= limit) return 0; n2s(p, i); while ((p + 4) <= limit) { unsigned short type, size; n2s(p, type); n2s(p, size); if (p + size > limit) return 0; if (type == TLSEXT_TYPE_session_ticket) { int r; */ s->tlsext_ticket_expected = 1; return 1; } if (s->tls_session_secret_cb) { /* * Indicate that the ticket couldn't be decrypted rather than * generating the session from ticket now, trigger * abbreviated handshake based on external mechanism to * calculate the master secret later. */ return 2; } r = tls_decrypt_ticket(s, p, size, session_id, len, ret); switch (r) { case 2: /* ticket couldn't be decrypted */ s->tlsext_ticket_expected = 1; return 2; case 3: /* ticket was decrypted */ return r; case 4: /* ticket decrypted but need to renew */ s->tlsext_ticket_expected = 1; return 3; default: /* fatal error */ return -1; } } p += size; } Commit Message: CWE ID: CWE-190 Target: 1 Example 2: Code: Value* ChromeNetworkDelegate::SessionNetworkStatsInfoToValue() const { DictionaryValue* dict = new DictionaryValue(); dict->SetString("session_received_content_length", base::Int64ToString(received_content_length_)); dict->SetString("session_original_content_length", base::Int64ToString(original_content_length_)); return dict; } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) { assert(len <= UINT_MAX); int index = 1; lua_newtable(L); while(len--) { lua_pushnumber(L,index++); mp_decode_to_lua_type(L,c); if (c->err) return; lua_settable(L,-3); } } Commit Message: Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems. CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static UINT dvcman_receive_channel_data(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr, UINT32 ChannelId, wStream* data) { UINT status = CHANNEL_RC_OK; DVCMAN_CHANNEL* channel; size_t dataSize = Stream_GetRemainingLength(data); channel = (DVCMAN_CHANNEL*) dvcman_find_channel_by_id(pChannelMgr, ChannelId); if (!channel) { /* Windows 8.1 tries to open channels not created. * Ignore cases like this. */ WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %"PRIu32" not found!", ChannelId); return CHANNEL_RC_OK; } if (channel->dvc_data) { /* Fragmented data */ if (Stream_GetPosition(channel->dvc_data) + dataSize > (UINT32) Stream_Capacity( channel->dvc_data)) { WLog_Print(drdynvc->log, WLOG_ERROR, "data exceeding declared length!"); Stream_Release(channel->dvc_data); channel->dvc_data = NULL; return ERROR_INVALID_DATA; } Stream_Write(channel->dvc_data, Stream_Pointer(data), dataSize); if (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length) { Stream_SealLength(channel->dvc_data); Stream_SetPosition(channel->dvc_data, 0); status = channel->channel_callback->OnDataReceived(channel->channel_callback, channel->dvc_data); Stream_Release(channel->dvc_data); channel->dvc_data = NULL; } } else { status = channel->channel_callback->OnDataReceived(channel->channel_callback, data); } return status; } Commit Message: Fix for #4866: Added additional length checks CWE ID: Target: 1 Example 2: Code: EOFStream::EOFStream(Stream *strA): FilterStream(strA) { } Commit Message: CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: dump_xml_formatted(xmlNode * an_xml_node) { char *buffer = NULL; int offset = 0, max = 0; crm_xml_dump(an_xml_node, xml_log_option_formatted, &buffer, &offset, &max, 0); return buffer; } Commit Message: Fix: acl: Do not delay evaluation of added nodes in some situations It is not appropriate when the node has no children as it is not a placeholder CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> idbKeyCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.idbKey"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(RefPtr<IDBKey>, key, createIDBKeyFromValue(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->idbKey(key.get()); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { vpx_codec_pts_t duration = pkt->data.frame.pts - last_pts_; if (duration > 1) { if (!first_drop_) first_drop_ = last_pts_ + 1; num_drops_ += static_cast<int>(duration - 1); tot_frame_number_ += static_cast<int>(duration - 1); } int layer = SetLayerId(tot_frame_number_, cfg_.ts_number_layers); bits_in_buffer_model_ += static_cast<int64_t>( duration * timebase_ * cfg_.rc_target_bitrate * 1000); ASSERT_GE(bits_in_buffer_model_, 0) << "Buffer Underrun at frame " << pkt->data.frame.pts; const size_t frame_size_in_bits = pkt->data.frame.sz * 8; for (int i = layer; i < static_cast<int>(cfg_.ts_number_layers); ++i) { bits_total_[i] += frame_size_in_bits; } last_pts_ = pkt->data.frame.pts; ++frame_number_; ++tot_frame_number_; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderWidgetHostViewGuest::SelectionBoundsChanged( const gfx::Rect& start_rect, WebKit::WebTextDirection start_direction, const gfx::Rect& end_rect, WebKit::WebTextDirection end_direction) { NOTIMPLEMENTED(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info) { struct hwsim_new_radio_params param = { 0 }; const char *hwname = NULL; int ret; param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG]; param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE]; param.channels = channels; param.destroy_on_close = info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE]; if (info->attrs[HWSIM_ATTR_CHANNELS]) param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]); if (info->attrs[HWSIM_ATTR_NO_VIF]) param.no_vif = true; if (info->attrs[HWSIM_ATTR_RADIO_NAME]) { hwname = kasprintf(GFP_KERNEL, "%.*s", nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]), (char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME])); if (!hwname) return -ENOMEM; param.hwname = hwname; } if (info->attrs[HWSIM_ATTR_USE_CHANCTX]) param.use_chanctx = true; else param.use_chanctx = (param.channels > 1); if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]) param.reg_alpha2 = nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]); if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) { u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]); if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom)) return -EINVAL; param.regd = hwsim_world_regdom_custom[idx]; } ret = mac80211_hwsim_new_radio(info, &param); kfree(hwname); return ret; } Commit Message: mac80211_hwsim: fix possible memory leak in hwsim_new_radio_nl() 'hwname' is malloced in hwsim_new_radio_nl() and should be freed before leaving from the error handling cases, otherwise it will cause memory leak. Fixes: ff4dd73dd2b4 ("mac80211_hwsim: check HWSIM_ATTR_RADIO_NAME length") Signed-off-by: Wei Yongjun <[email protected]> Reviewed-by: Ben Hutchings <[email protected]> Signed-off-by: Johannes Berg <[email protected]> CWE ID: CWE-772 Target: 1 Example 2: Code: int usbnet_open (struct net_device *net) { struct usbnet *dev = netdev_priv(net); int retval; struct driver_info *info = dev->driver_info; if ((retval = usb_autopm_get_interface(dev->intf)) < 0) { netif_info(dev, ifup, dev->net, "resumption fail (%d) usbnet usb-%s-%s, %s\n", retval, dev->udev->bus->bus_name, dev->udev->devpath, info->description); goto done_nopm; } if (info->reset && (retval = info->reset (dev)) < 0) { netif_info(dev, ifup, dev->net, "open reset fail (%d) usbnet usb-%s-%s, %s\n", retval, dev->udev->bus->bus_name, dev->udev->devpath, info->description); goto done; } /* hard_mtu or rx_urb_size may change in reset() */ usbnet_update_max_qlen(dev); if (info->check_connect && (retval = info->check_connect (dev)) < 0) { netif_dbg(dev, ifup, dev->net, "can't open; %d\n", retval); goto done; } /* start any status interrupt transfer */ if (dev->interrupt) { retval = usbnet_status_start(dev, GFP_KERNEL); if (retval < 0) { netif_err(dev, ifup, dev->net, "intr submit %d\n", retval); goto done; } } set_bit(EVENT_DEV_OPEN, &dev->flags); netif_start_queue (net); netif_info(dev, ifup, dev->net, "open: enable queueing (rx %d, tx %d) mtu %d %s framing\n", (int)RX_QLEN(dev), (int)TX_QLEN(dev), dev->net->mtu, (dev->driver_info->flags & FLAG_FRAMING_NC) ? "NetChip" : (dev->driver_info->flags & FLAG_FRAMING_GL) ? "GeneSys" : (dev->driver_info->flags & FLAG_FRAMING_Z) ? "Zaurus" : (dev->driver_info->flags & FLAG_FRAMING_RN) ? "RNDIS" : (dev->driver_info->flags & FLAG_FRAMING_AX) ? "ASIX" : "simple"); /* reset rx error state */ dev->pkt_cnt = 0; dev->pkt_err = 0; clear_bit(EVENT_RX_KILL, &dev->flags); tasklet_schedule (&dev->bh); if (info->manage_power) { retval = info->manage_power(dev, 1); if (retval < 0) { retval = 0; set_bit(EVENT_NO_RUNTIME_PM, &dev->flags); } else { usb_autopm_put_interface(dev->intf); } } return retval; done: usb_autopm_put_interface(dev->intf); done_nopm: return retval; } Commit Message: usbnet: cleanup after bind() in probe() In case bind() works, but a later error forces bailing in probe() in error cases work and a timer may be scheduled. They must be killed. This fixes an error case related to the double free reported in http://www.spinics.net/lists/netdev/msg367669.html and needs to go on top of Linus' fix to cdc-ncm. Signed-off-by: Oliver Neukum <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AppCacheDatabase::UpgradeSchema() { return DeleteExistingAndCreateNewDatabase(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: construct_command_line(struct manager_ctx *manager, struct server *server) { static char cmd[BUF_SIZE]; char *method = manager->method; int i; build_config(working_dir, server); if (server->method) method = server->method; memset(cmd, 0, BUF_SIZE); snprintf(cmd, BUF_SIZE, "%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf", executable, method, manager->manager_address, working_dir, server->port, working_dir, server->port); if (manager->acl != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl); } if (manager->timeout != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout); } #ifdef HAVE_SETRLIMIT if (manager->nofile) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile); } #endif if (manager->user != NULL) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user); } if (manager->verbose) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -v"); } if (server->mode == NULL && manager->mode == UDP_ONLY) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -U"); } if (server->mode == NULL && manager->mode == TCP_AND_UDP) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -u"); } if (server->fast_open[0] == 0 && manager->fast_open) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --fast-open"); } if (manager->ipv6first) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -6"); } if (manager->mtu) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu); } if (server->plugin == NULL && manager->plugin) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin \"%s\"", manager->plugin); } if (server->plugin_opts == NULL && manager->plugin_opts) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --plugin-opts \"%s\"", manager->plugin_opts); } for (i = 0; i < manager->nameserver_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]); } for (i = 0; i < manager->host_num; i++) { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]); } { int len = strlen(cmd); snprintf(cmd + len, BUF_SIZE - len, " --reuse-port"); } if (verbose) { LOGI("cmd: %s", cmd); } return cmd; } Commit Message: Fix #1734 CWE ID: CWE-78 Target: 1 Example 2: Code: _message_handler(xmpp_conn_t *const conn, xmpp_stanza_t *const stanza, void *const userdata) { log_debug("Message stanza handler fired"); char *text; size_t text_size; xmpp_stanza_to_text(stanza, &text, &text_size); gboolean cont = plugins_on_message_stanza_receive(text); xmpp_free(connection_get_ctx(), text); if (!cont) { return 1; } const char *type = xmpp_stanza_get_type(stanza); if (g_strcmp0(type, STANZA_TYPE_ERROR) == 0) { _handle_error(stanza); } if (g_strcmp0(type, STANZA_TYPE_GROUPCHAT) == 0) { _handle_groupchat(stanza); } xmpp_stanza_t *mucuser = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_MUC_USER); if (mucuser) { _handel_muc_user(stanza); } xmpp_stanza_t *conference = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE); if (conference) { _handle_conference(stanza); } xmpp_stanza_t *captcha = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CAPTCHA); if (captcha) { _handle_captcha(stanza); } xmpp_stanza_t *receipts = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS); if (receipts) { _handle_receipt_received(stanza); } _handle_chat(stanza); return 1; } Commit Message: Add carbons from check CWE ID: CWE-346 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1451 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = key_validate(key); if (ret == 0) { ret = -EOPNOTSUPP; if (key->type->read) { /* read the data with the semaphore held (since we * might sleep) */ down_read(&key->sem); ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } } error2: key_put(key); error: return ret; } Commit Message: KEYS: Fix race between read and revoke This fixes CVE-2015-7550. There's a race between keyctl_read() and keyctl_revoke(). If the revoke happens between keyctl_read() checking the validity of a key and the key's semaphore being taken, then the key type read method will see a revoked key. This causes a problem for the user-defined key type because it assumes in its read method that there will always be a payload in a non-revoked key and doesn't check for a NULL pointer. Fix this by making keyctl_read() check the validity of a key after taking semaphore instead of before. I think the bug was introduced with the original keyrings code. This was discovered by a multithreaded test program generated by syzkaller (http://github.com/google/syzkaller). Here's a cleaned up version: #include <sys/types.h> #include <keyutils.h> #include <pthread.h> void *thr0(void *arg) { key_serial_t key = (unsigned long)arg; keyctl_revoke(key); return 0; } void *thr1(void *arg) { key_serial_t key = (unsigned long)arg; char buffer[16]; keyctl_read(key, buffer, 16); return 0; } int main() { key_serial_t key = add_key("user", "%", "foo", 3, KEY_SPEC_USER_KEYRING); pthread_t th[5]; pthread_create(&th[0], 0, thr0, (void *)(unsigned long)key); pthread_create(&th[1], 0, thr1, (void *)(unsigned long)key); pthread_create(&th[2], 0, thr0, (void *)(unsigned long)key); pthread_create(&th[3], 0, thr1, (void *)(unsigned long)key); pthread_join(th[0], 0); pthread_join(th[1], 0); pthread_join(th[2], 0); pthread_join(th[3], 0); return 0; } Build as: cc -o keyctl-race keyctl-race.c -lkeyutils -lpthread Run as: while keyctl-race; do :; done as it may need several iterations to crash the kernel. The crash can be summarised as: BUG: unable to handle kernel NULL pointer dereference at 0000000000000010 IP: [<ffffffff81279b08>] user_read+0x56/0xa3 ... Call Trace: [<ffffffff81276aa9>] keyctl_read_key+0xb6/0xd7 [<ffffffff81277815>] SyS_keyctl+0x83/0xe0 [<ffffffff815dbb97>] entry_SYSCALL_64_fastpath+0x12/0x6f Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David Howells <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Signed-off-by: James Morris <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: void ssl_set_rng( ssl_context *ssl, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ssl->f_rng = f_rng; ssl->p_rng = p_rng; } Commit Message: ssl_parse_certificate() now calls x509parse_crt_der() directly CWE ID: CWE-20 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: std::unique_ptr<service_manager::Service> CreateVideoCaptureService() { return base::MakeUnique<video_capture::ServiceImpl>(); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb) { struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp; struct sk_buff *opt_skb = NULL; /* Imagine: socket is IPv6. IPv4 packet arrives, goes to IPv4 receive handler and backlogged. From backlog it always goes here. Kerboom... Fortunately, tcp_rcv_established and rcv_established handle them correctly, but it is not case with tcp_v6_hnd_req and tcp_v6_send_reset(). --ANK */ if (skb->protocol == htons(ETH_P_IP)) return tcp_v4_do_rcv(sk, skb); if (sk_filter(sk, skb)) goto discard; /* * socket locking is here for SMP purposes as backlog rcv * is currently called with bh processing disabled. */ /* Do Stevens' IPV6_PKTOPTIONS. Yes, guys, it is the only place in our code, where we may make it not affecting IPv4. The rest of code is protocol independent, and I do not like idea to uglify IPv4. Actually, all the idea behind IPV6_PKTOPTIONS looks not very well thought. For now we latch options, received in the last packet, enqueued by tcp. Feel free to propose better solution. --ANK (980728) */ if (np->rxopt.all) opt_skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC)); if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */ struct dst_entry *dst = sk->sk_rx_dst; sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); if (dst) { if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif || dst->ops->check(dst, np->rx_dst_cookie) == NULL) { dst_release(dst); sk->sk_rx_dst = NULL; } } tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len); if (opt_skb) goto ipv6_pktoptions; return 0; } if (tcp_checksum_complete(skb)) goto csum_err; if (sk->sk_state == TCP_LISTEN) { struct sock *nsk = tcp_v6_cookie_check(sk, skb); if (!nsk) goto discard; if (nsk != sk) { sock_rps_save_rxhash(nsk, skb); sk_mark_napi_id(nsk, skb); if (tcp_child_process(sk, nsk, skb)) goto reset; if (opt_skb) __kfree_skb(opt_skb); return 0; } } else sock_rps_save_rxhash(sk, skb); if (tcp_rcv_state_process(sk, skb)) goto reset; if (opt_skb) goto ipv6_pktoptions; return 0; reset: tcp_v6_send_reset(sk, skb); discard: if (opt_skb) __kfree_skb(opt_skb); kfree_skb(skb); return 0; csum_err: TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); goto discard; ipv6_pktoptions: /* Do you ask, what is it? 1. skb was enqueued by tcp. 2. skb is added to tail of read queue, rather than out of order. 3. socket is not in passive state. 4. Finally, it really contains options, which user wants to receive. */ tp = tcp_sk(sk); if (TCP_SKB_CB(opt_skb)->end_seq == tp->rcv_nxt && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { if (np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo) np->mcast_oif = tcp_v6_iif(opt_skb); if (np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) np->mcast_hops = ipv6_hdr(opt_skb)->hop_limit; if (np->rxopt.bits.rxflow || np->rxopt.bits.rxtclass) np->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(opt_skb)); if (np->repflow) np->flow_label = ip6_flowlabel(ipv6_hdr(opt_skb)); if (ipv6_opt_accepted(sk, opt_skb, &TCP_SKB_CB(opt_skb)->header.h6)) { skb_set_owner_r(opt_skb, sk); tcp_v6_restore_cb(opt_skb); opt_skb = xchg(&np->pktoptions, opt_skb); } else { __kfree_skb(opt_skb); opt_skb = xchg(&np->pktoptions, NULL); } } kfree_skb(opt_skb); return 0; } Commit Message: tcp: take care of truncations done by sk_filter() With syzkaller help, Marco Grassi found a bug in TCP stack, crashing in tcp_collapse() Root cause is that sk_filter() can truncate the incoming skb, but TCP stack was not really expecting this to happen. It probably was expecting a simple DROP or ACCEPT behavior. We first need to make sure no part of TCP header could be removed. Then we need to adjust TCP_SKB_CB(skb)->end_seq Many thanks to syzkaller team and Marco for giving us a reproducer. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Marco Grassi <[email protected]> Reported-by: Vladis Dronov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-284 Target: 1 Example 2: Code: static int should_end_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root) { int ret; ret = btrfs_block_rsv_check(root, &root->fs_info->global_block_rsv, 5); return ret ? 1 : 0; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SkippedMBMotionComp( VideoDecData *video ) { Vop *prev = video->prevVop; Vop *comp; int ypos, xpos; PIXEL *c_comp, *c_prev; PIXEL *cu_comp, *cu_prev; PIXEL *cv_comp, *cv_prev; int width, width_uv; int32 offset; #ifdef PV_POSTPROC_ON // 2/14/2001 int imv; int32 size = (int32) video->nTotalMB << 8; uint8 *pp_dec_y, *pp_dec_u; uint8 *pp_prev1; int mvwidth = video->nMBPerRow << 1; #endif width = video->width; width_uv = width >> 1; ypos = video->mbnum_row << 4 ; xpos = video->mbnum_col << 4 ; offset = (int32)ypos * width + xpos; /* zero motion compensation for previous frame */ /*mby*width + mbx;*/ c_prev = prev->yChan + offset; /*by*width_uv + bx;*/ cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2); /*by*width_uv + bx;*/ cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2); comp = video->currVop; c_comp = comp->yChan + offset; cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2); cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2); /* Copy previous reconstructed frame into the current frame */ PutSKIPPED_MB(c_comp, c_prev, width); PutSKIPPED_B(cu_comp, cu_prev, width_uv); PutSKIPPED_B(cv_comp, cv_prev, width_uv); /* 10/24/2000 post_processing semaphore generation */ #ifdef PV_POSTPROC_ON // 2/14/2001 if (video->postFilterType != PV_NO_POST_PROC) { imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3); /* Post-processing mode (copy previous MB) */ pp_prev1 = video->pstprcTypPrv + imv; pp_dec_y = video->pstprcTypCur + imv; *pp_dec_y = *pp_prev1; *(pp_dec_y + 1) = *(pp_prev1 + 1); *(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth); *(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1); /* chrominance */ /*4*MB_in_width*MB_in_height*/ pp_prev1 = video->pstprcTypPrv + (size >> 6) + ((imv + (xpos >> 3)) >> 2); pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); *pp_dec_u = *pp_prev1; pp_dec_u[size>>8] = pp_prev1[size>>8]; } #endif /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/ return; } Commit Message: Fix NPDs in h263 decoder Bug: 35269635 Test: decoded PoC with and without patch Change-Id: I636a14360c7801cc5bca63c9cb44d1d235df8fd8 (cherry picked from commit 2ad2a92318a3b9daf78ebcdc597085adbf32600d) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) { if (!(boundary_value >= 0 && boundary_value <= 100 && sample >= 0 && sample < boundary_value)) { frontend_host_->BadMessageRecieved(); return; } if (name == kDevToolsActionTakenHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else if (name == kDevToolsPanelShownHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else frontend_host_->BadMessageRecieved(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200 Target: 1 Example 2: Code: ar6000_dset_data_req( void *context, u32 accessCookie, u32 offset, u32 length, u32 targBuf, u32 targReplyFn, u32 targReplyArg) { } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __videobuf_mmap_mapper(struct videobuf_queue *q, struct vm_area_struct *vma) { struct videbuf_vmalloc_memory *mem; struct videobuf_mapping *map; unsigned int first; int retval; unsigned long offset = vma->vm_pgoff << PAGE_SHIFT; if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED)) return -EINVAL; /* look for first buffer to map */ for (first = 0; first < VIDEO_MAX_FRAME; first++) { if (NULL == q->bufs[first]) continue; if (V4L2_MEMORY_MMAP != q->bufs[first]->memory) continue; if (q->bufs[first]->boff == offset) break; } if (VIDEO_MAX_FRAME == first) { dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n", (vma->vm_pgoff << PAGE_SHIFT)); return -EINVAL; } /* create mapping + update buffer list */ map = q->bufs[first]->map = kmalloc(sizeof(struct videobuf_mapping),GFP_KERNEL); if (NULL == map) return -ENOMEM; map->start = vma->vm_start; map->end = vma->vm_end; map->q = q; q->bufs[first]->baddr = vma->vm_start; vma->vm_ops = &videobuf_vm_ops; vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED; vma->vm_private_data = map; mem=q->bufs[first]->priv; BUG_ON (!mem); MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM); /* Try to remap memory */ retval=remap_vmalloc_range(vma, mem->vmalloc,0); if (retval<0) { dprintk(1,"mmap: postponing remap_vmalloc_range\n"); mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL); if (!mem->vma) { kfree(map); q->bufs[first]->map=NULL; return -ENOMEM; } memcpy(mem->vma,vma,sizeof(*vma)); } dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n", map,q,vma->vm_start,vma->vm_end, (long int) q->bufs[first]->bsize, vma->vm_pgoff,first); videobuf_vm_open(vma); return (0); } Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap This is pretty serious bug. map->count is never initialized after the call to kmalloc making the count start at some random trash value. The end result is leaking videobufs. Also, fix up the debug statements to print unsigned values. Pushed to http://ifup.org/hg/v4l-dvb too Signed-off-by: Brandon Philips <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2) { pdf_xref_entry *table; pdf_xref_entry *table; int i, n; if (i0 < 0 || i1 < 0 || i0 > INT_MAX - i1) fz_throw(ctx, FZ_ERROR_GENERIC, "negative xref stream entry index"); table = pdf_xref_find_subsection(ctx, doc, i0, i1); for (i = i0; i < i0 + i1; i++) for (i = i0; i < i0 + i1; i++) { pdf_xref_entry *entry = &table[i-i0]; int a = 0; int64_t b = 0; int c = 0; if (fz_is_eof(ctx, stm)) fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream"); for (n = 0; n < w0; n++) a = (a << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w1; n++) b = (b << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w2; n++) c = (c << 8) + fz_read_byte(ctx, stm); if (!entry->type) { int t = w0 ? a : 1; entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0; entry->ofs = w1 ? b : 0; entry->gen = w2 ? c : 0; entry->num = i; } } doc->has_xref_streams = 1; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: void vrend_renderer_resource_unref(uint32_t res_handle) { struct vrend_resource *res; struct vrend_context *ctx; res = vrend_resource_lookup(res_handle, 0); if (!res) return; /* find in all contexts and detach also */ /* remove from any contexts */ LIST_FOR_EACH_ENTRY(ctx, &vrend_state.active_ctx_list, ctx_entry) { vrend_renderer_detach_res_ctx_p(ctx, res->handle); } vrend_resource_remove(res->handle); } Commit Message: CWE ID: CWE-772 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: selReadStream(FILE *fp) { char *selname; char linebuf[L_BUF_SIZE]; l_int32 sy, sx, cy, cx, i, j, version, ignore; SEL *sel; PROCNAME("selReadStream"); if (!fp) return (SEL *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, " Sel Version %d\n", &version) != 1) return (SEL *)ERROR_PTR("not a sel file", procName, NULL); if (version != SEL_VERSION_NUMBER) return (SEL *)ERROR_PTR("invalid sel version", procName, NULL); if (fgets(linebuf, L_BUF_SIZE, fp) == NULL) return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL); selname = stringNew(linebuf); sscanf(linebuf, " ------ %s ------", selname); if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", &sy, &sx, &cy, &cx) != 4) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("dimensions not read", procName, NULL); } if ((sel = selCreate(sy, sx, selname)) == NULL) { LEPT_FREE(selname); return (SEL *)ERROR_PTR("sel not made", procName, NULL); } selSetOrigin(sel, cy, cx); for (i = 0; i < sy; i++) { ignore = fscanf(fp, " "); for (j = 0; j < sx; j++) ignore = fscanf(fp, "%1d", &sel->data[i][j]); ignore = fscanf(fp, "\n"); } ignore = fscanf(fp, "\n"); LEPT_FREE(selname); return sel; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sas_resume_port(struct asd_sas_phy *phy) { struct domain_device *dev; struct asd_sas_port *port = phy->port; struct sas_ha_struct *sas_ha = phy->ha; struct sas_internal *si = to_sas_internal(sas_ha->core.shost->transportt); if (si->dft->lldd_port_formed) si->dft->lldd_port_formed(phy); if (port->suspended) port->suspended = 0; else { /* we only need to handle "link returned" actions once */ return; } /* if the port came back: * 1/ presume every device came back * 2/ force the next revalidation to check all expander phys */ list_for_each_entry(dev, &port->dev_list, dev_list_node) { int i, rc; rc = sas_notify_lldd_dev_found(dev); if (rc) { sas_unregister_dev(port, dev); continue; } if (dev->dev_type == SAS_EDGE_EXPANDER_DEVICE || dev->dev_type == SAS_FANOUT_EXPANDER_DEVICE) { dev->ex_dev.ex_change_count = -1; for (i = 0; i < dev->ex_dev.num_phys; i++) { struct ex_phy *phy = &dev->ex_dev.ex_phy[i]; phy->phy_change_count = -1; } } } sas_discover_event(port, DISCE_RESUME); } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Target: 1 Example 2: Code: static int hfs_decompress_lzvn_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree) { if (rawBuf[0] == 0x06) { return hfs_decompress_noncompressed_attr( rawBuf, rawSize, uncSize, dstBuf, dstSize, dstBufFree); } char* uncBuf = (char *) tsk_malloc((size_t) uncSize); *dstSize = lzvn_decode_buffer(uncBuf, uncSize, rawBuf, rawSize); *dstBuf = uncBuf; *dstBufFree = TRUE; return 1; } Commit Message: hfs: fix keylen check in hfs_cat_traverse() If key->key_len is 65535, calculating "uint16_t keylen' would cause an overflow: uint16_t keylen; ... keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len) so the code bypasses the sanity check "if (keylen > nodesize)" which results in crash later: ./toolfs/fstools/fls -b 512 -f hfs <image> ================================================================= ==16==ERROR: AddressSanitizer: SEGV on unknown address 0x6210000256a4 (pc 0x00000054812b bp 0x7ffca548a8f0 sp 0x7ffca548a480 T0) ==16==The signal is caused by a READ memory access. #0 0x54812a in hfs_dir_open_meta_cb /fuzzing/sleuthkit/tsk/fs/hfs_dent.c:237:20 #1 0x51a96c in hfs_cat_traverse /fuzzing/sleuthkit/tsk/fs/hfs.c:1082:21 #2 0x547785 in hfs_dir_open_meta /fuzzing/sleuthkit/tsk/fs/hfs_dent.c:480:9 #3 0x50f57d in tsk_fs_dir_open_meta /fuzzing/sleuthkit/tsk/fs/fs_dir.c:290:14 #4 0x54af17 in tsk_fs_path2inum /fuzzing/sleuthkit/tsk/fs/ifind_lib.c:237:23 #5 0x522266 in hfs_open /fuzzing/sleuthkit/tsk/fs/hfs.c:6579:9 #6 0x508e89 in main /fuzzing/sleuthkit/tools/fstools/fls.cpp:267:19 #7 0x7f9daf67c2b0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202b0) #8 0x41d679 in _start (/fuzzing/sleuthkit/tools/fstools/fls+0x41d679) Make 'keylen' int type to prevent the overflow and fix that. Now, I get proper error message instead of crash: ./toolfs/fstools/fls -b 512 -f hfs <image> General file system error (hfs_cat_traverse: length of key 3 in leaf node 1 too large (65537 vs 4096)) CWE ID: CWE-190 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline struct sem_array *sem_lock_check(struct ipc_namespace *ns, int id) { struct kern_ipc_perm *ipcp = ipc_lock_check(&sem_ids(ns), id); if (IS_ERR(ipcp)) return ERR_CAST(ipcp); return container_of(ipcp, struct sem_array, sem_perm); } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ShellSurface::OnSurfaceCommit() { surface_->CheckIfSurfaceHierarchyNeedsCommitToNewSurfaces(); surface_->CommitSurfaceHierarchy(); if (enabled() && !widget_) CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL); origin_ += pending_origin_offset_; pending_origin_offset_ = gfx::Vector2d(); resize_component_ = pending_resize_component_; if (widget_) { geometry_ = pending_geometry_; UpdateWidgetBounds(); gfx::Point surface_origin = GetSurfaceOrigin(); gfx::Rect hit_test_bounds = surface_->GetHitTestBounds() + surface_origin.OffsetFromOrigin(); bool activatable = activatable_ && !hit_test_bounds.IsEmpty(); if (activatable != CanActivate()) { set_can_activate(activatable); aura::client::ActivationClient* activation_client = ash::Shell::GetInstance()->activation_client(); if (activatable) activation_client->ActivateWindow(widget_->GetNativeWindow()); else if (widget_->IsActive()) activation_client->DeactivateWindow(widget_->GetNativeWindow()); } surface_->window()->SetBounds( gfx::Rect(surface_origin, surface_->window()->layer()->size())); if (pending_scale_ != scale_) { gfx::Transform transform; DCHECK_NE(pending_scale_, 0.0); transform.Scale(1.0 / pending_scale_, 1.0 / pending_scale_); surface_->window()->SetTransform(transform); scale_ = pending_scale_; } if (pending_show_widget_) { DCHECK(!widget_->IsClosed()); DCHECK(!widget_->IsVisible()); pending_show_widget_ = false; widget_->Show(); } } } Commit Message: exo: Reduce side-effects of dynamic activation code. This code exists for clients that need to managed their own system modal dialogs. Since the addition of the remote surface API we can limit the impact of this to surfaces created for system modal container. BUG=29528396 Review-Url: https://codereview.chromium.org/2084023003 Cr-Commit-Position: refs/heads/master@{#401115} CWE ID: CWE-416 Target: 1 Example 2: Code: int id() { return id_; } 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 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static LayoutPoint VisualOffsetFromPaintOffsetRoot( const PaintPropertyTreeBuilderFragmentContext& context, const PaintLayer* child) { const LayoutObject* paint_offset_root = context.current.paint_offset_root; PaintLayer* painting_layer = paint_offset_root->PaintingLayer(); LayoutPoint result = child->VisualOffsetFromAncestor(painting_layer); if (!paint_offset_root->HasLayer() || ToLayoutBoxModelObject(paint_offset_root)->Layer() != painting_layer) { result.Move(-paint_offset_root->OffsetFromAncestorContainer( &painting_layer->GetLayoutObject())); } if (paint_offset_root->HasOverflowClip()) result += ToLayoutBox(paint_offset_root)->ScrolledContentOffset(); return result; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int MemBackendImpl::DoomEntriesBetween(Time initial_time, Time end_time, const CompletionCallback& callback) { if (end_time.is_null()) end_time = Time::Max(); DCHECK_GE(end_time, initial_time); base::LinkNode<MemEntryImpl>* node = lru_list_.head(); while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time) node = node->next(); while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) { MemEntryImpl* to_doom = node->value(); node = node->next(); to_doom->Doom(); } return net::OK; } Commit Message: [MemCache] Fix bug while iterating LRU list in range doom This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919 but on explicit mass-erase rather than eviction. Thanks to nedwilliamson@ (on gmail) for the report and testcase. Bug: 831963 Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102 Reviewed-on: https://chromium-review.googlesource.com/1014023 Commit-Queue: Maks Orlovich <[email protected]> Reviewed-by: Josh Karlin <[email protected]> Cr-Commit-Position: refs/heads/master@{#551205} CWE ID: CWE-416 Target: 1 Example 2: Code: static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return FILEID_INVALID; } else if (len < 3) { *lenp = 3; return FILEID_INVALID; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.parent_partref = 0; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17 Target: 0 Now 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'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) { SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader); DCHECK(it != headers.end()); if (!(it->second == "GET" || it->second == "HEAD")) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method " << it->second; Reset(QUIC_INVALID_PROMISE_METHOD); return; } if (!SpdyUtils::UrlIsValid(headers)) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL " << url_; Reset(QUIC_INVALID_PROMISE_URL); return; } if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) { Reset(QUIC_UNAUTHORIZED_PROMISE_URL); return; } request_headers_.reset(new SpdyHeaderBlock(headers.Clone())); } Commit Message: Fix Stack Buffer Overflow in QuicClientPromisedInfo::OnPromiseHeaders BUG=777728 Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I6a80db88aafdf20c7abd3847404b818565681310 Reviewed-on: https://chromium-review.googlesource.com/748425 Reviewed-by: Zhongyi Shi <[email protected]> Commit-Queue: Ryan Hamilton <[email protected]> Cr-Commit-Position: refs/heads/master@{#513105} CWE ID: CWE-119 Output:
1